Wednesday, 29 November 2017

python - Understanding slice notation

itemprop="text">

I need a good explanation (references
are a plus) on Python's slice notation.



To me,
this notation needs a bit of picking up.



It
looks extremely powerful, but I haven't quite got my head around
it.



itemprop="text">
class="normal">Answer



It's
pretty simple
really:



a[start:stop] # items
start through stop-1
a[start:] # items start through the rest of the
array
a[:stop] # items from the beginning through stop-1
a[:] # a
copy of the whole
array


There is also
the step value, which can be used with any of the
above:




a[start:stop:step]
# start through not past stop, by
step


The key point to
remember is that the :stop value represents the first value
that is not in the selected slice. So, the difference between
stop and start is the number of
elements selected (if step is 1, the
default).



The other feature is that
start or stop may be a
negative number, which means it counts from the end of the array
instead of the beginning.
So:



a[-1] # last item in the
array
a[-2:] # last two items in the array

a[:-2] #
everything except the last two
items


Similarly,
step may be a negative
number:



a[::-1] # all items in the
array, reversed
a[1::-1] # the first two items, reversed
a[:-3:-1] #
the last two items, reversed
a[-3::-1] # everything except the last two items,
reversed



Python
is kind to the programmer if there are fewer items than you ask for. For example, if you
ask for a[:-2] and a only contains one
element, you get an empty list instead of an error. Sometimes you would prefer the
error, so you have to be aware that this may
happen.



Relation to
slice() object



The
slicing operator [] is actually being used in the above code
with a slice() object using the :
notation (which is only valid within []),
i.e.:



a[start:stop:step]



is
equivalent to:



a[slice(start,
stop, step)]


Slice
objects also behave slightly differently depending on the number of arguments, similarly
to range(), i.e. both slice(stop) and
slice(start, stop[, step]) are supported.
To skip
specifying a given argument, one might use None, so that e.g.
a[start:] is equivalent to a[slice(start,
None)]
or a[::-1] is equivalent to
a[slice(None, None,
-1)]
.



While the
:-based notation is very helpful for simple slicing, the
explicit use of slice() objects simplifies the programmatic
generation of slicing.


film techniques - Why all the fancy technology in most movies?

In most of
the movies and TV-series I have watched, whenever there is some kind of "technology"
involved (say, like a tracking device or hacking something important), there is a lot of
unnecessary, impractical key-pressing and fancy colors and sounds (a lot of 1's and 0's
going on the screen and a lot of "beep"s).


For example,
take the TV-series href="http://www.imdb.com/title/tt0808096/">Primeval. Their device for
tracking anomalies have a lot of the things said above.


Why
do movies and TV-series employ this kind of false-looking tech? It would have been much
easier to use a real OS (like MacOS for normal things and Linux for hacking-kind-of
things), maybe with a custom-made software suited to the task. It would have been more
realistic.


So is there any specific reason for
this?



Answer



Well, I think there is perfect reason for it: audience
appeal. Of course those things are totally unrealistic and over the top, but show a
simple black-and-white console to the audience or a basic database application and they
will just find it boring to look at or think there is not much to
it.


Of course it bothers the hell out of those who know
better, but the average guy that uses his computer for YouTube, Facebook and maybe
Office is just more pleased with colorful displays and stunning graphics in a simple
database query and is more likely to accept that there is something interesting going
on. It's about conveying the information inherent in those abstract and hard to grasp
processes in an interesting and entertaining way, thus sacrificing some realism for the
sake of story-telling.


(And of course all hackers fluently
communicate in 0s and 1s, which makes them so awesome. ;-))



string - Using "==" in Java

public class Test { 
public
static void main(String[] args)
{
String s1 =
"HELLO";
String s2 = "HELLO";



System.out.println(s1 == s2); // true
}
}



But when I use
:



public class Test { 

public static void main(String[] args)

{
String s1 =
new String("HELLO");
String s2 = new String("HELLO");


System.out.println(s1 == s2); // false
}
}



Can anybody please
explain the difference here? Thankyou!

java - TCP server on android phone crashes at .accept()

itemprop="text">

I'm new to android but not to sockets.
I have a GUI with a button that runs the UAVServer thread. When I click it, the server
should listen for the client. The line of
code...



Socket client =
serverSocket.accept();


...Should
block until a client connects. But it just crashes saying "Unfortunately, DroidUAV has
stopped."




public class
UAVServer extends Thread {

private String TAG =
UAVServer.class.getSimpleName();

@Override
public void
run() {
ServerSocket serverSocket;
try {
serverSocket
= new ServerSocket(12345);
Log.d(TAG, "Fails at the next line of
code");

Socket client = serverSocket.accept();
} catch
(IOException e) {
// TODO Auto-generated catch block

e.printStackTrace();
}

}
}


This
seems pretty straight forward, why would it be crashing? Also how does android handle
blocking ports, this might have something to do with it. If it was on the wifi, I figure
it would be up to the router to unblock ports. But what if I was just on
4G?




NOTE: uses-permission
android:name="android.permission.INTERNET"
is in my manifest
file.



Edit:
I must be doing something
wrong, because I just tried to make it run the client instead and it crashes on this
line...



Socket s = new
Socket("192.168.1.102",4444);



Edit:
Added
errors...



FATAL EXCEPTION:
main
java.lang.IllegalStateException: Could not execute method of the
activity
at android.view.View$1.onClick(View.java:3071)
at
android.view.View.performClick(View.java:3538)
at
android.widget.CompoundButton.performClick(CompoundButton.java:103)
at
android.view.View$PerformClick.run(View.java:14319)
at
android.os.Handler.handleCallback(Handler.java:608)

at
android.os.Handler.dispatchMessage(Handler.java:92)
at
android.os.Looper.loop(Looper.java:156)
at
android.app.ActivityThread.main(ActivityThread.java:5099)
at
java.lang.reflect.Method.invokeNative(Native Method)
at
java.lang.reflect.Method.invoke(Method.java:511)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:991)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758)
at
dalvik.system.NativeStart.main(Native Method)
Caused by:
java.lang.reflect.InvocationTargetException
at
java.lang.reflect.Method.invokeNative(Native Method)

at
java.lang.reflect.Method.invoke(Method.java:511)
at
android.view.View$1.onClick(View.java:3066)
... 12 more
Caused by:
android.os.NetworkOnMainThreadException
at
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1190)

at libcore.io.BlockGuardOs.accept(BlockGuardOs.java:54)
at
java.net.PlainSocketImpl.accept(PlainSocketImpl.java:98)
at
java.net.ServerSocket.implAccept(ServerSocket.java:202)
at
java.net.ServerSocket.accept(ServerSocket.java:127)
at
com.example.droiduav.UAVServer.run(UAVServer.java:19)

at
com.example.droiduav.MainActivity.onToggleServer(MainActivity.java:31)
... 15
more

class="post-text" itemprop="text">
class="normal">Answer



Well, the
problem you are facing has to do with the following exception that can be seen in your
LogCat trace:



Caused by:
android.os.NetworkOnMainThreadException



What
it means is pretty straightforward guessable from the name. Don't perform any Network
code on the Main UI Thread. Solution: href="http://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask"
rel="nofollow noreferrer">Start your own thread for that (see href="http://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask"
rel="nofollow noreferrer">this Android Developer
article).




Why?



Network
code can take a "long time" (assume several seconds) to execute. If you would call all
your network code on the main thread, it will freeze the UI in the mean time (this is -
as one could guess - not really preferable and could and will result in href="http://developer.android.com/training/articles/perf-anr.html" rel="nofollow
noreferrer">ANR exceptions).



see
also these questions as they are related to your
problem:




plot explanation - How is it possible for Alexander to become a chancellor of the Vampire authority?

In href="http://www.imdb.com/title/tt2170049/" rel="nofollow">True Blood: Authority
Always Wins, Alexander Drew's character was great and fantastic, he was aged 9
years before being turned (according to href="http://trueblood.wikia.com/wiki/Alexander_Drew"
rel="nofollow">trueblood.wikia). But it also says that he serves the
Vampire Authority as a
Chancellor
.


According to href="http://trueblood.wikia.com/wiki/Alexander_Drew"
rel="nofollow">trueblood.wikia:




Alexander Drew is an angelic looking, yet impetuous vampire. He was

turned at the tender age of 9, and serves the Vampire Authority as a

Chancellor. He enjoys smoking cigarettes and taunting everyone around
him,
including his fellow
Chancellors.



Other vampires
such as rel="nofollow">Salome and href="http://trueblood.wikia.com/wiki/Godric" rel="nofollow">Godric are
aged 2000+ years. So, how does it possible for Alexander to become a
chancellor of the Vampire authority?



Answer


href="http://trueblood.wikia.com/wiki/Alexander_Drew" rel="nofollow">As the wiki
states, Alexander was aged 9 years old when he was
turned
.


Just like all vampires, they do not
age beyond what age they were when turned. For all we know he could be beyond age of all
vampires including Russell (2800 years old), Eric (1100+), and especially Bill (176).


This detail has not been made known yet, however but we
can assume he is a very old vampire, if not, very experienced to be on the
council.


Static variables in JavaScript

itemprop="text">

How can I create static variables in
Javascript?


itemprop="text">
class="normal">Answer



If you
come from a class-based, statically typed object-oriented language (like Java,
C++ or C#)
I assume that you are trying to create a variable or method
associated to a "type" but not to an
instance.



An example using a "classical"
approach, with constructor functions maybe could help you to catch the concepts of basic
OO JavaScript:




function
MyClass () { // constructor function
var privateVariable = "foo"; // Private
variable

this.publicVariable = "bar"; // Public variable


this.privilegedMethod = function () { // Public Method

alert(privateVariable);
};
}


//
Instance method will be available to all instances but only load once in memory

MyClass.prototype.publicMethod = function () {

alert(this.publicVariable);
};

// Static variable shared
by all instances
MyClass.staticProperty = "baz";

var
myInstance = new
MyClass();



staticProperty
is defined in the MyClass object (which is a function) and has nothing to do with its
created instances, JavaScript treats functions as href="http://en.wikipedia.org/wiki/First-class_function" rel="nofollow
noreferrer">first-class objects, so being an object, you can assign
properties to a
function.



UPDATE:
ES6 introduced the ability to href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"
rel="nofollow noreferrer">declare classes through the
class keyword. It is syntax sugar over the existing
prototype-based inheritance.



The href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static"
rel="nofollow noreferrer">static keyword allows
you to easily define static properties or methods in a
class.



Let's see the above example implemented
with ES6 classes:



data-hide="false" data-console="true" data-babel="true">

class="snippet-code">
class MyClass {
// class constructor,
equivalent to
// the function body of a constructor
constructor()
{
const privateVariable = 'private value'; // Private variable at the
constructor scope
this.publicVariable = 'public value'; // Public
property

this.privilegedMethod = function() {
// Public
Method with access to the constructor scope variables


console.log(privateVariable);
};
}

//
Prototype methods:
publicMethod() {

console.log(this.publicVariable);
}

// Static
properties shared by all instances

static staticProperty = 'static
value';

static staticMethod() {

console.log(this.staticProperty);
}
}

// We
can add properties to the class prototype
MyClass.prototype.additionalMethod =
function() {

console.log(this.publicVariable);

};

var
myInstance = new MyClass();
myInstance.publicMethod(); // "public
value"
myInstance.additionalMethod(); // "public
value"
myInstance.privilegedMethod(); // "private
value"
MyClass.staticMethod(); // "static
value"






java - Swing - Dispose a frame

First, it's not a good practice to name classes with a
lowercase, so try renaming to something like MakeGUI instead of
makeGUI.


The problem with your
commented code is that it creates a new instance of makeGUI
every time the button is clicked and the action listener is
invoked. The result is that when you click on the close button, a new frame is created,
then an inner one and this inner one gets immediately closed. The only thing you'd be
doing is creating more and more frames. You should keep the instance as a state, for
instance as a class member:


class MakeGUI
{
JFrame smallframe;
JButton close = new JButton("CLOSE
ME");
MakeGUI() {
frame f1 = new frame();
smallframe =
new JFrame(); //want to close this one
JPanel jp = new JPanel(new
FlowLayout());
smallframe.setSize(300, 300);

smallframe.setLocationRelativeTo(null);

smallframe.setDefaultCloseOperation(smallframe.DISPOSE_ON_CLOSE);

close.addActionListener(new action());
jp.add(close);

smallframe.add(jp);
smallframe.setVisible(true);
}

class action implements ActionListener {
public void
actionPerformed(ActionEvent e) {
if (e.getSource() == close) {
//
use this instead of dispose
smallframe.dispatchEvent(new
WindowEvent(smallframe, WindowEvent.WINDOW_CLOSING));

System.out.println("gotcha");
}
}

}
}

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...