Thursday 30 November 2017

php - Why would one omit the close tag?

itemprop="text">

I keep reading it is poor practice to
use the PHP close tag ?> at the end of the file. The header
problem seems irrelevant in the following context (and this is the only good argument so
far):




Modern
versions of PHP set the output_buffering flag in php.ini
If output buffering
is enabled, you can set HTTP headers and cookies after outputting HTML because the
returned code is not sent to the browser
immediately.





Every
good practice book and wiki starts with this 'rule' but nobody offers good
reasons.
Is there another good reason to skip the ending PHP
tag?


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



Sending
headers earlier than the normal course may have far reaching consequences. Below are
just a few of them that happened to come to my mind at the
moment:




  1. While
    current PHP releases may have output buffering on, the actual production
    servers
    you will be deploying your code on are far more important than
    any development or testing machines. And they do not always tend to follow latest PHP
    trends immediately.


  2. You may have
    headaches over inexplicable functionality loss. Say, you
    are implementing some kind payment gateway, and redirect user to a specific URL after
    successful confirmation by the payment processor. If some kind of PHP error, even a
    warning, or an excess line ending happens, the payment may remain unprocessed and the
    user may still seem unbilled. This is also one of the reasons why needless redirection
    is evil and if redirection is to be used, it must be used with
    caution.


  3. You may get "Page loading
    canceled" type of errors in Internet Explorer, even in the most recent versions. This is
    because an AJAX response/json include contains something
    that it shouldn't contain, because of the excess line endings in some PHP files, just as
    I've encountered a few days ago.


  4. If
    you have some file downloads in your app, they can break
    too, because of this. And you may not notice it, even after years, since the specific
    breaking habit of a download depends on the server, the browser, the type and content of
    the file (and possibly some other factors I don't want to bore you
    with).



  5. Finally, many PHP
    frameworks including href="http://symfony.com/doc/current/contributing/code/standards.html"
    rel="noreferrer">Symfony, href="http://framework.zend.com/manual/1.10/en/coding-standard.php-file-formatting.html"
    rel="noreferrer">Zend and Laravel (there is no mention of this in the href="https://github.com/laravel/framework/blob/master/CONTRIBUTING.md#coding-guidelines"
    rel="noreferrer">coding guidelines but it follows the suit) and the href="http://www.php-fig.org/psr/psr-2/" rel="noreferrer">PSR-2 standard
    (item 2.2) require omission of the closing tag. PHP manual itself ( href="http://php.net/basic-syntax.instruction-separation"
    rel="noreferrer">1, href="http://php.net/manual/en/language.basic-syntax.phptags.php"
    rel="noreferrer">2), href="http://make.wordpress.org/core/handbook/coding-standards/php/#remove-trailing-spaces"
    rel="noreferrer">Wordpress, href="https://www.drupal.org/coding-standards#phptags"
    rel="noreferrer">Drupal and many other PHP software I guess, advise to do
    so. If you simply make a habit of following the standard (and setup href="https://github.com/fabpot/PHP-CS-Fixer" rel="noreferrer">PHP-CS-Fixer
    for your code) you can forget the issue. Otherwise you will always need to keep the
    issue in your
    mind.




Bonus: a
few gotchas (actually currently one) related to these 2
characters:




  1. Even some
    well-known libraries may contain excess line endings after
    ?>. An example is Smarty, even the most recent versions of
    both 2.* and 3.* branch have this. So, as always, watch for third party
    code
    . Bonus in bonus: A regex for deleting needless PHP endings: replace
    (\s*\?>\s*)$ with empty text in all files that contain PHP
    code.


How to implement a dynamic sequence in Python (e.g. a "geometric range")?

A Python range is an interesting
object because it behaves like a generator when it comes to memory, but it otherwise
behaves like a sequence and it additionally has O(1) time
complexity for in operation, .index()
and .count().



This is
an example of a dynamic sequence, i.e. a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence"
rel="nofollow noreferrer">Sequence object that
does not store its elements in memory.



How do I
implement a dynamic sequence in
Python?




The
in operation, .index() and
.count methods implemented in O(1)
time, would, of course, be a nice addition.



/>

For concreteness, let us consider the case of a
Geometric
sequence
:



s_k = a * r **
k


where
k is an
integer.




Obviously, one cannot simply
use generator (simplified)
like:



def geom_seq(a, r, start,
stop=None):
if stop is None:
start, stop = 0, start

else:
start, stop = start, stop
item = a * r ** start

for _ in range(start, stop):

yield item
item *=
r


because this, while
being memory efficient would not behave like a Sequence,
e.g.:



a = geom_seq(1, 2,
8)

len(a)
#
TypeError...


list(a)
# [1, 2, 4, 8, 16, 32,
64, 128]
list(a) # generator is consumed...
#
[]


On the contrary,
something like:



a =
tuple(geom_seq(1, 2,
8))



will
be(have like) a Sequence but would not be memory
efficient:



import
sys


print(sys.getsizeof(geom_seq(1, 2,
1000)))
# 88
print(sys.getsizeof(tuple(geom_seq(1, 2,
1000))))

#
8048


/>



This is not a duplicate of
href="https://stackoverflow.com/questions/7875911/how-to-implement-a-minimal-class-that-behaves-like-a-sequence-in-python">How
to implement a minimal class that behaves like a sequence in Python? as time /
memory considerations are not discussed there.

java - How to count the number of 1's a number will have in binary?












How
do I count the number of 1's a number will have in
binary?




So let's say I have the
number 45, which is equal to 101101 in
binary and has 4 1's in it. What's the most efficient way to
write an algorithm to do this?


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



Instead of
writing an algorithm to do this its best to use the built in function. href="http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#bitCount%28int%29"
rel="noreferrer">Integer.bitCount()



What makes this especially efficient is that
the JVM can treat this as an intrinsic. i.e. recognise and replace the whole thing with
a single machine code instruction on a platform which supports it e.g.
Intel/AMD






To
demonstrate how effective this optimisation
is




public static void
main(String... args) {
perfTestIntrinsic();


perfTestACopy();
}

private static void
perfTestIntrinsic() {
long start = System.nanoTime();
long
countBits = 0;
for (int i = 0; i < Integer.MAX_VALUE;
i++)

countBits += Integer.bitCount(i);
long time =
System.nanoTime() - start;
System.out.printf("Intrinsic: Each bit count took
%.1f ns, countBits=%d%n", (double) time / Integer.MAX_VALUE,
countBits);
}

private static void perfTestACopy()
{
long start2 = System.nanoTime();
long countBits2 = 0;

for (int i = 0; i < Integer.MAX_VALUE; i++)
countBits2 +=
myBitCount(i);

long time2 = System.nanoTime() - start2;

System.out.printf("Copy of same code: Each bit count took %.1f ns, countBits=%d%n",
(double) time2 / Integer.MAX_VALUE, countBits2);
}

//
Copied from Integer.bitCount()
public static int myBitCount(int i)
{
// HD, Figure 5-2
i = i - ((i >>> 1) &
0x55555555);
i = (i & 0x33333333) + ((i >>> 2) &
0x33333333);
i = (i + (i >>> 4)) &
0x0f0f0f0f;

i = i + (i >>> 8);
i = i + (i
>>> 16);
return i &
0x3f;
}


prints



Intrinsic:
Each bit count took 0.4 ns, countBits=33285996513
Copy of same code: Each bit
count took 2.4 ns,
countBits=33285996513



Each
bit count using the intrinsic version and loop takes just 0.4 nano-second on average.
Using a copy of the same code takes 6x longer (gets the
same result)


php - .htaccess issue with folder

I have an .htaccess file in my root directory with the
following contents:



RewriteEngine
On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$
https://website.com/$1 [R=301,L]
DirectoryIndex index.php
Options
-Indexes



Works
perfect in the root.



The problem is with
subfolders. If I manually go to:
rel="nofollow noreferrer">http://www.website.com/myfolder
it
pushes me to:
https://website.com/myfolder/.php (404
error)



My goal is to always remove the "www" and
redirect to SSL for the root and all subfolders. Obviously without the above error where
it somehow leaves the ".php"




Please
help!



Thanks!

php - The second argument to copy() function cannot be a directory and move_uploaded_file(): Unable to move





in the
code



if(isset($_POST['submit'])){



$post_image=$_FILES['post_image']['name'];


$post_image_tmp=$_FILES['post_image']['tmp_name'];


if($post_image='' ){
echo "";
exit();


}
else{

move_uploaded_file($post_image_tmp,"news_images/$post_image");

?>


I
get this error





Warning: move_uploaded_file(): The second argument to copy()
function
cannot be a directory in
C:\xampp\htdocs\MyCMS\admin\insert_post.php
on line 107





Warning: move_uploaded_file(): Unable to move

'C:\xampp\tmp\php946C.tmp' to 'news_images/' in

C:\xampp\htdocs\MyCMS\admin\insert_post.php on line
107




Please help
I'am just newbie.


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



= is
assignment operator.
use comparison operator ==
here.




if($post_image ==
'' ) {

c - What causes the error "undefined reference to (some function)"?





I get the
error:




main.o(.text+0x1ed):
In function `main':
: undefined reference to
`avergecolumns'
collect2: ld returned 1 exit
status


when I gcc *.o.
I'm not quite sure what causes this error. Other posters have explained it as the
function is not found or the function is empty. If someone could clarify or refine, it
would be greaty appreciated!



Here is my
function's code(I'm trying to calculate the average of the column in 2D
arrays):



#include
"my.h"


void averagecolumns (int x, int y, int**
a)
{
int i;
int j;
float sum;

float colAvg;

sum = 0;
colAvg =
0;


printf("i. The column averages are: \n");

for(i = 0; i < x; i++)
{
for(j = 0; j < y; j++)

{
sum += a[i][j];
colAvg = sum / (float)x;
}

printf("Column: %3d, Average: %6.2f", j, colAvg);

sum = 0;

colAvg = 0;

}


The relavent parts
of main are:



#include
"my.h"

int main (int argc, char*
argv[])

{
int** a;
float** colAvg;

int ROWS;
int COLS;
int i;
int j;
int**
table;
FILE* fpmyfile;
int
closeResult;


....

printme (ROWS,
COLS, a); // call functions a - j
oddvalues (ROWS, COLS, a);

oddlocations (ROWS, COLS, a);
countoddrows (ROWS, COLS, a);

addrows (ROWS, COLS, a);
findfirstsmall (ROWS, COLS, a);

findlastlarge (ROWS,COLS, a);

addcolumns (ROWS, COLS,
a);
avergecolumns (ROWS, COLS,
a);

....

}


Also,
is this a linker or a compile error (I wasn't sure which tag to
add).



Answer





It's a linker error.
ld is the linker, so if you get an error message ending with
"ld returned 1 exit status", that tells you that it's a linker
error.



The error message tells you that none of
the object files you're linking against contains a definition for
avergecolumns. The reason for that is that the function you've
defined is called averagecolumns (in other words: you
misspelled the function name when calling the function (and presumably in the header
file as well - otherwise you'd have gotten a different error at compile
time)).


c - MPI dynamic array using malloc

itemprop="text">

I am having problem while creating
dynamic array using both malloc and
calloc.





int main()
{
float *xd_real_send;
int Nooflines_Real;
int
*X;

float test[500];

Nooflines_Real =
count_lines(infile);
printf("Nooflines_Real: %d\n",
Nooflines_Real);

X = (int *)
malloc(Nooflines_Real*sizeof(int));
xd_real_send = (float *) calloc
(Nooflines_Real,sizeof(float));

printf("size of X %d, test %d and
size of xd_real_send %d\n",

sizeof(X)/sizeof(int),sizeof(test)/sizeof(float),


sizeof(xd_real_send)/sizeof(float));fflush(stdout);


}



And the output is




Nooflines_Real:
40

size of X 2, test 500 and size of xd_real_send
2


Could you please tell what Am I
doing wrong.


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




X and
xd_real_send are defined as pointers.



The sizeof operator
applied returns the amount of memory use by the pointer, not the size of what the
pointer refers to.



It not possible (in any
portable way) to request the size of a memory block once allocated dynamically and
refered by some pointer.




For
dynamically allocated memory the application needs to take care of keeping track of how
large those memory blocks are.



/>

test is defined expliciltly
as an array, so sizeof is able to determine the array's size.


android - I click HOME button and the program minimizes; but when I press the app icon, the program is launched twice

I have the following
problem:



When I press the Android HOME key, I
can see the "Desktop" and my app icon. Then I press my app icon and my application
launches twice. I don't want open my app
twice.



How my program
works:



I have 4 Activities (A, B, C,
D).



A - The Main Activity: It is the first to
open. It opens the other activity that has a lot of buttons. It's like a Java's main()
method. I show a SplashScreen and I call another Activity. Then I
finish my activity
"A".




B - The Menu Screen: In this
activity, I have some buttons, like a menu. I have a configuration button, update
button, and Login Button. When I click the login button, I finish this activity and open
the Login Screen (Activity "C").



C - The Login
Screen: The user writes the Login and Password. If the login is successful, I finish
this activity and open the Activity "D".



D - The
application main screen: It stays opened all the time and launches another Activities. I
finish this when I want close my
application.



P.S.: I tried change the launchMode
flag (androidManifest.xml), but didn't work.



My
AndroidManifest.xml
bellow:




            android:label="@string/app_name" android:icon="@drawable/icon"
android:name="MyApplication">

android:label="@string/app_name"

android:configChanges="orientation">



android:name="android.intent.category.LAUNCHER" />



android:name="br.com.site.B" android:label="@string/app_name"
/>

android:label="@string/app_name" />
android:name="br.com.site.D" android:label="@string/app_name"
/>



And
this is my Activity "A.java"
source:



public class A extends
Activity {

@Override

public void
onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

finish();

startActivity(new Intent(this, AtualizaDadosFrame.class));

}
}


I
don't want open my app
twice.




Thanks in
advance!

c# - What is a NullReferenceException, and how do I fix it?






I have some code and when it executes, it throws a
NullReferenceException,
saying:




Object
reference not set to an instance of an
object.




What does
this mean, and what can I do to fix this error?


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







Bottom
Line



You are trying to use something that is
null (or Nothing in VB.NET). This
means you either set it to null, or you never set it to
anything at all.



Like anything else,
null gets passed around. If it is null
in method "A", it could be that method "B" passed a
null to method
"A".



null can have
different meanings:




  1. Object
    variables which are uninitialized and hence
    point to nothing. In this case, if you access properties or
    methods of such objects, it causes a
    NullReferenceException.


  2. The
    developer is using null intentionally to indicate
    there is no meaningful value available.
    Note that C# has the concept of
    nullable datatypes for variables (like database tables can have nullable fields) - you
    can assign null to them to indicate there is no value stored in
    it, for example int? a = null; where the question mark
    indicates it is allowed to store null in variable a. You can
    check that either with if (a.HasValue) {...} or with
    if (a==null) {...}. Nullable variables, like
    a this example, allow to access the value via
    a.Value explicitly, or just as normal via
    a.
    Note that accessing
    it via a.Value throws an
    InvalidOperationException instead of a
    NullReferenceException if a is
    null - you should do the check beforehand, i.e. if you have
    another on-nullable variable int b; then you should do
    assignments like if (a.HasValue) { b = a.Value; } or shorter
    if (a != null) { b = a;
    }
    .



The rest
of this article goes into more detail and shows mistakes that many programmers often
make which can lead to a
NullReferenceException.



More
Specifically



The runtime throwing a
NullReferenceException always
means the same thing: you are trying to use a reference, and the reference is not
initialized (or it was once initialized, but is no
longer
initialized).



This means the
reference is null, and you cannot access members (such as
methods) through a null reference. The simplest
case:




string foo =
null;
foo.ToUpper();


This
will throw a NullReferenceException at the second line because
you can't call the instance method ToUpper() on a
string reference pointing to
null.





How
do you find the source of a NullReferenceException? Apart from
looking at the exception itself, which will be thrown exactly at the location where it
occurs, the general rules of debugging in Visual Studio apply: place strategic
breakpoints and rel="noreferrer">inspect your variables, either by hovering the mouse over
their names, opening a (Quick)Watch window or using the various debugging panels like
Locals and Autos.




If you want to find
out where the reference is or isn't set, right-click its name and select "Find All
References". You can then place a breakpoint at every found location and run your
program with the debugger attached. Every time the debugger breaks on such a breakpoint,
you need to determine whether you expect the reference to be non-null, inspect the
variable and and verify that it points to an instance when you expect it
to.



By following the program flow this way, you
can find the location where the instance should not be null, and why it isn't properly
set.





Some common scenarios
where the exception can be
thrown:



Generic




ref1.ref2.ref3.member


If
ref1 or ref2 or ref3 is null, then you'll get a
NullReferenceException. If you want to solve the problem, then
find out which one is null by rewriting the expression to its simpler
equivalent:



var r1 =
ref1;
var r2 = r1.ref2;
var r3 =
r2.ref3;
r3.member



Specifically,
in HttpContext.Current.User.Identity.Name, the
HttpContext.Current could be null, or the
User property could be null, or the
Identity property could be
null.



Indirect



public
class Person {
public int Age { get; set; }
}
public
class Book {

public Person Author { get; set;
}
}
public class Example {
public void Foo() {

Book b1 = new Book();
int authorAge = b1.Author.Age; // You never initialized
the Author property.
// there is no Person to get an Age from.

}
}



If
you want to avoid the child (Person) null reference, you could initialize it in the
parent (Book) object's constructor.



Nested
Object Initializers



The same applies to nested
object initializers:



Book b1 = new
Book { Author = { Age = 45 }
};



This
translates to



Book b1 = new
Book();
b1.Author.Age =
45;


While the
new keyword is used, it only creates a new instance of
Book, but not a new instance of
Person, so the Author the property is
still null.



Nested
Collection
Initializers




public
class Person {
public ICollection Books { get; set;
}
}
public class Book {
public string Title { get; set;
}
}


The
nested collection initializers behave the
same:




Person p1 = new
Person {
Books = {
new Book { Title = "Title1" },
new
Book { Title = "Title2" },

}
};


This
translates to




Person p1
= new Person();
p1.Books.Add(new Book { Title = "Title1"
});
p1.Books.Add(new Book { Title = "Title2"
});


The
new Person only creates an instance of
Person, but the Books collection is
still null. The collection initializer syntax does not create a
collection
for p1.Books, it only translates to the
p1.Books.Add(...)
statements.



Array




int[]
numbers = null;
int n = numbers[0]; // numbers is null. There is no array to
index.


Array
Elements



Person[] people = new
Person[5];
people[0].Age = 20 // people[0] is null. The array was allocated
but not
// initialized. There is no Person to set the Age
for.



Jagged
Arrays



long[][] array = new
long[1][];
array[0][0] = 3; // is null because only the first dimension is yet
initialized.
// Use array[0] = new long[2];
first.


Collection/List/Dictionary




Dictionary            int> agesForNames = null;
int age = agesForNames["Bob"]; // agesForNames is
null.
// There is no Dictionary to perform the
lookup.


Range
Variable
(Indirect/Deferred)



public class
Person {
public string Name { get; set;
}
}

var people = new
List();
people.Add(null);
var names = from p in people
select p.Name;
string firstName = names.First(); // Exception is thrown here,
but actually occurs
// on the line above. "p" is null because the

// first element we added to the list is
null.


Events




public
class Demo
{
public event EventHandler
StateChanged;

protected virtual void OnStateChanged(EventArgs
e)
{
StateChanged(this, e); // Exception is thrown here

// if no event handlers have been attached
// to StateChanged
event

}

}


Bad
Naming Conventions:



If you named fields
differently from locals, you might have realized that you never initialized the field.



public class Form1 {

private Customer customer;


private void
Form1_Load(object sender, EventArgs e) {
Customer customer = new
Customer();
customer.Name = "John";
}


private void Button_Click(object sender, EventArgs e) {

MessageBox.Show(customer.Name);

}
}



This
can be solved by following the convention to prefix fields with an
underscore:



private Customer
_customer;


ASP.NET
Page Life cycle:



public partial
class Issues_Edit : System.Web.UI.Page
{

protected
TestIssue myIssue;

protected void Page_Load(object sender,
EventArgs e)
{
if (!IsPostBack)
{
// Only
called on first load, not when button clicked
myIssue = new TestIssue();

}
}


protected void
SaveButton_Click(object sender, EventArgs e)
{
myIssue.Entry =
"NullReferenceException here!";

}
}


ASP.NET
Session Values




// if
the "FirstName" session value has not yet been set,
// then this line will
throw a NullReferenceException
string firstName =
Session["FirstName"].ToString();


ASP.NET
MVC empty view models



If the exception occurs
when referencing a property of @Model in an ASP.NET MVC view,
you need to understand that the Model gets set in your action
method, when you return a view. When you return an empty model
(or model property) from your controller, the exception occurs when the views access
it:



//
Controller

public class
Restaurant:Controller
{
public ActionResult Search()

{
return View(); // Forgot the provide a Model here.

}
}

// Razor view
@foreach (var
restaurantSearch in Model.RestaurantSearch) //
Throws.

{
}

@Model.somePropertyName





WPF Control
Creation Order and Events



WPF controls are
created during the call to InitializeComponent in the order
they appear in the visual tree. A NullReferenceException will
be raised in the case of early-created controls with event handlers, etc. , that fire
during InitializeComponent which reference late-created
controls.




For example
:






Margin="10"
SelectedIndex="0"

SelectionChanged="comboBox1_SelectionChanged">
Content="Item 1" />
/>











Here
comboBox1 is created before label1. If
comboBox1_SelectionChanged attempts to reference `label1, it
will not yet have been
created.



private void
comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs
e)
{
label1.Content = comboBox1.SelectedIndex.ToString(); //
NullReference
here!!
}


Changing
the order of the declarations in the XAML (i.e., listing label1
before comboBox1, ignoring issues of design philosophy, would
at least resolve the NullReferenceException
here.




Cast with
as



var
myThing = someObject as
Thing;


This doesn't
throw an InvalidCastException but returns a null when the cast
fails (and when someObject is itself null). So be aware of
that.



LINQ FirstOrDefault() and
SingleOrDefault()



The plain versions
First() and Single() throw exceptions
when there is nothing. The "OrDefault" versions return null in that case. So be aware of
that.




foreach



foreach
throws when you try to iterate null collection. Usually caused by unexpected
null result from methods that return
collections.



 List list
= null;
foreach(var v in list) { } //
exception


More
realistic example - select nodes from XML document. Will throw if nodes are not found
but initial debugging shows that all properties
valid:




 foreach (var
node in
myData.MyXml.DocumentNode.SelectNodes("//Data"))


/>



Explicitly check for
null and ignore null
values.




If you expect the reference
sometimes to be null, you can check for it being null before
accessing instance members:



void
PrintName(Person p) {
if (p != null) {

Console.WriteLine(p.Name);

}
}


Explicitly
check for null and provide a default
value.




Methods call you expect to
return an instance can return null, for example when the object
being sought cannot be found. You can choose to return a default value when this is the
case:



string GetCategory(Book b)
{
if (b == null)
return "Unknown";
return
b.Category;
}



Explicitly
check for null from method calls and throw a custom
exception.



You can also throw a custom
exception, only to catch it in the calling
code:



string GetCategory(string
bookTitle) {
var book = library.FindBook(bookTitle); // This may return
null
if (book == null)
throw new BookNotFoundException(bookTitle);
// Your custom exception
return
book.Category;
}



Use
Debug.Assert if a value should never be
null, to catch the problem earlier than the exception
occurs.



When you know during development that a
method maybe can, but never should return null, you can use
Debug.Assert() to break as soon as possible when it does
occur:



string GetTitle(int
knownBookID) {
// You know this should never return null.
var book
= library.GetBook(knownBookID);


// Exception will
occur on the next line instead of at the end of this method.

Debug.Assert(book != null, "Library didn't return a book for known book
ID.");

// Some other code

return book.Title;
// Will never throw NullReferenceException in Debug
mode.
}


Though
this check href="https://stackoverflow.com/questions/3021538/debug-assert-appears-in-release-mode">will
not end up in your release build, causing it to throw the
NullReferenceException again when book ==
null
at runtime in release
mode.




Use
GetValueOrDefault() for nullable value types to provide a
default value when they are
null.



DateTime?
appointment =
null;
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
//
Will display the default value provided (DateTime.Now), because appointment is
null.

appointment = new DateTime(2022, 10,
20);
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
//
Will display the appointment date, not the
default



Use
the null coalescing operator: ?? [C#] or
If() [VB].



The
shorthand to providing a default value when a null is
encountered:



IService
CreateService(ILogger log, Int32? frobPowerLevel)
{
var serviceImpl
= new MyService(log ?? NullLog.Instance);


// Note that
the above "GetValueOrDefault()" can also be rewritten to use
// the coalesce
operator:
serviceImpl.FrobPowerLevel = frobPowerLevel ??
5;
}


Use
the null condition operator: ?. or
?[x] for arrays (available in C# 6 and VB.NET
14):



This is also sometimes called the safe
navigation or Elvis (after its shape) operator. If the expression on the left side of
the operator is null, then the right side will not be evaluated, and null is returned
instead. That means cases like
this:




var title =
person.Title.ToUpper();


If
the person does not have a title, this will throw an exception because it is trying to
call ToUpper on a property with a null
value.



In C# 5 and below, this can be guarded
with:



var title = person.Title ==
null ? null :
person.Title.ToUpper();



Now
the title variable will be null instead of throwing an exception. C# 6 introduces a
shorter syntax for this:



var title
=
person.Title?.ToUpper();


This
will result in the title variable being null, and the call to
ToUpper is not made if person.Title is
null.



Of course, you
still have to check title for null or use
the null condition operator together with the null coalescing operator
(??) to supply a default
value:



// regular null
check

int titleLength = 0;
if (title != null)

titleLength = title.Length; // If title is null, this would throw
NullReferenceException

// combining the `?` and the `??`
operator
int titleLength = title?.Length ??
0;


Likewise, for
arrays you can use ?[i] as
follows:




int[]
myIntArray=null;
var i=5;
int? elem = myIntArray?[i];
if
(!elem.HasValue) Console.WriteLine("No
value");


This will do
the following: If myIntArray is null, the expression returns null and you can safely
check it. If it contains an array, it will do the same as:
elem =
myIntArray[i];
and returns the ith
element.



Use null context (available in C#
8):




Introduced in C# 8 there null
context's and nullable reference types perform static analysis on variables and provides
a compiler warning if a value can be potentially null or have been set to null. The
nullable reference types allows types to be explicitly allowed to be
null.



The nullable annotation context and
nullable warning context can be set for a project using the Nullable element in your
csproj file. This element configures how the compiler interprets the nullability of
types and what warnings are generated. Valid settings
are:




  • enable: The nullable
    annotation context is enabled. The nullable warning context is enabled. Variables of a
    reference type, string for example, are non-nullable. All nullability warnings are
    enabled.

  • disable: The nullable annotation context is
    disabled. The nullable warning context is disabled. Variables of a reference type are
    oblivious, just like earlier versions of C#. All nullability warnings are
    disabled.

  • safeonly: The nullable annotation context is
    enabled. The nullable warning context is safeonly. Variables of a reference type are
    nonnullable. All safety nullability warnings are
    enabled.

  • warnings: The nullable annotation context is
    disabled. The nullable warning context is enabled. Variables of a reference type are
    oblivious. All nullability warnings are
    enabled.


  • safeonlywarnings: The nullable
    annotation context is disabled. The nullable warning context is safeonly.

    Variables of a reference type are oblivious. All safety nullability warnings are
    enabled.



A nullable
reference type is noted using the same syntax as nullable value types: a
? is appended to the type of the
variable.



Special techniques for debugging and
fixing null derefs in iterators



C# supports
"iterator blocks" (called "generators" in some other popular languages). Null
dereference exceptions can be particularly tricky to debug in iterator blocks because of
deferred
execution:




public
IEnumerable GetFrobs(FrobFactory f, int count)
{
for
(int i = 0; i < count; ++i)
yield return
f.MakeFrob();
}
...
FrobFactory factory =
whatever;
IEnumerable frobs =
GetFrobs();
...
foreach(Frob frob in frobs) { ...
}



If
whatever results in null then
MakeFrob will throw. Now, you might think that the right thing
to do is this:



// DON'T DO
THIS
public IEnumerable GetFrobs(FrobFactory f, int
count)
{
if (f == null)
throw new
ArgumentNullException("f", "factory must not be null");
for (int i = 0; i
< count; ++i)

yield return
f.MakeFrob();
}


Why
is this wrong? Because the iterator block does not actually run
until the foreach! The call to
GetFrobs simply returns an object which when
iterated
will run the iterator
block.



By writing a null check like this you
prevent the null dereference, but you move the null argument exception to the point of
the iteration, not to the point of the call,
and that is very confusing to debug.



The correct fix
is:




// DO
THIS
public IEnumerable GetFrobs(FrobFactory f, int
count)
{
// No yields in a public method that throws!
if
(f == null)
throw new ArgumentNullException("f", "factory must not be
null");
return GetFrobsForReal(f, count);
}
private
IEnumerable GetFrobsForReal(FrobFactory f, int
count)
{

// Yields in a private method

Debug.Assert(f != null);
for (int i = 0; i < count; ++i)
yield
return
f.MakeFrob();
}


That
is, make a private helper method that has the iterator block logic, and a public surface
method that does the null check and returns the iterator. Now when
GetFrobs is called, the null check happens immediately, and
then GetFrobsForReal executes when the sequence is
iterated.



If you examine the reference source
for LINQ to Objects you will see that this technique is used throughout. It is slightly
more clunky to write, but it makes debugging nullity errors much easier.
Optimize your code for the convenience of the caller, not the convenience
of the author
.




A note
on null dereferences in unsafe code



C# has an
"unsafe" mode which is, as the name implies, extremely dangerous because the normal
safety mechanisms which provide memory safety and type safety are not enforced.
You should not be writing unsafe code unless you have a thorough and deep
understanding of how memory works
.



In unsafe mode, you should be aware of two
important
facts:




  • dereferencing a
    null pointer produces the same exception as dereferencing a
    null reference

  • dereferencing
    an invalid non-null pointer can produce that
    exception

    in some
    circumstances



To
understand why that is, it helps to understand how .NET produces null dereference
exceptions in the first place. (These details apply to .NET running on Windows; other
operating systems use similar
mechanisms.)



Memory is virtualized in Windows;
each process gets a virtual memory space of many "pages" of memory that are tracked by
the operating system. Each page of memory has flags set on it which determine how it may
be used: read from, written to, executed, and so on. The lowest
page is marked as "produce an error if ever used in any way".



Both a null pointer and a null reference in C#
are internally represented as the number zero, and so any attempt to dereference it into
its corresponding memory storage causes the operating system to produce an error. The
.NET runtime then detects this error and turns it into the null dereference
exception.



That's why dereferencing both a null
pointer and a null reference produces the same exception.




What about the second point?
Dereferencing any invalid pointer that falls in the lowest page of
virtual memory causes the same operating system error, and thereby the same
exception.



Why does this make sense? Well,
suppose we have a struct containing two ints, and an unmanaged pointer equal to null. If
we attempt to dereference the second int in the struct, the CLR will not attempt to
access the storage at location zero; it will access the storage at location four. But
logically this is a null dereference because we are getting to that address
via the null.



If you are
working with unsafe code and you get a null dereference exception, just be aware that
the offending pointer need not be null. It can be any location in the lowest page, and
this exception will be produced.


html - Go to another site automatically





How can I make a Web page that takes me automatically without
clicking to another site? (I use in
HTML)




I tried to find a answer but I
didn't find any answer that it in HTML.



I tried
to write like this:



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

class="snippet-code-html lang-html prettyprint-override"> href="http://www.boutell.com/newfaq/">







but this not take me automatically.

can someone help
me?
thanks!


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



Write this
in the head section of the HTML
document.



            http-equiv="refresh" content="0; url=randomname.com"
/>



As
soon as the page loads, on 0 seconds, you can go to your page.



java - Odd syntax in API "String::concat"

I was looking at some of the changes made to the Java SE
API with 1.8, and I when looking at the new method href="http://docs.oracle.com/javase/8/docs/api/java/util/Map.html#merge-K-V-java.util.function.BiFunction-"
rel="noreferrer">Map.merge it shows an example of how to use it with the
line



map.merge(key, msg,
String::concat)



I
understand how to use a lambda expressions to create anonymous functional interfaces,
but this seems to use a method as a BiFunction. I like to understand and use obscure
java syntaxes, but I can't find any mention of this one anywhere.

javascript - How to solve the "TypeError: array.splice is not a function" when 'var array = {}'?

itemprop="text">












I
am using jQuery and I am handling a variable this
way:



var array =
{};

array[an_object] = something
array[another_object] =
something_else
array[...] =
...


When I try to run
the rel="noreferrer">splice method on the
array I get a TypeError: array.splice is not a
function
. My intent is to remove the
an_object "key" and all its content from the
array
variable.




How can I make
that?



/>

Note: When I run the
console.log(array[an_object]) (the same is valid for
another_object and all other objects) I
get:



[Object { label="str1",
value=1 }, Object { label="str2", value=2 }, { label="strN", value=N
}]

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





First of all, name your variables
what they are. The name array you're using, is misleading if
you use it to create a object.



var
myObject = {};

myObject[an_object] =
"xyz";
myObject[another_object] =
"abc";


Now, you can
delete the entry in the object with the delete
statement:




delete
myObject[an_object]; // Returns true / false if the deletion is a success /
failure
console.log(myObject[an_object]) // Returns
undefined


/>

Now, that said, this will not work like you'd
expect. myObject[an_object] will contain "abc"
Don't
use objects as keys. Use strings, instead.
This is because of the fact that
any parameter entered in the [] will be converted to string. So
actually, you're entering myObject["[object
Object]"]


c++ - Issue with Constructor of Struct nested in Class Template

itemprop="text">

I need to turn a linked list class for
ints that I wrote into a class template. I'm having issues with the constructor and
destructor for a struct nested in the List Class, called node.



Layout:




template
class List
{


public:
//Stuff that's not important to this question

private:
struct Node
{
Node(T value); //
constructor
~Node(); // destructor
Node *next; // pointer to the
next Node
T data; // the actual data in the node
static int
nodes_alive; // count of nodes still allocated

};

};


Implementation:



template

typename List::Node::Node(T
value)
{
data = value;

next =
0;
}

template
typename
List::Node::~Node()
{

--nodes_alive;
}



Errors:




  1. Expected ';' at
    end of declaration



    typename List::Node::Node(T
    value)


  2. Expected an identifier or
    template ID after '::'



    typename
    List::Node::~Node()


  3. Expected the class
    name after '~' to name a
    destructor




    typename
    List::Node::~Node()




Not
really sure what's going on here. My implementation is in a separate file included at
the bottom of the header file. Any help would be greatly appreciated.


style="font-weight: bold;">

Answer




It's simple: Get rid of the
typename keyword. Since you're writing a constructor/destructor
and there is no return type, it is not
needed.



template             T>
List::Node::Node(T value)

{

data = value;
next = 0;
}

template

List::Node::~Node()
{

--nodes_alive;
}



Wednesday 29 November 2017

Insert text body and excel table body in email using VBA

rel="nofollow noreferrer">The ideal format of the email I wish to automate. Certain
parts blacked out for privacy.



I am
trying to create an email template for business use that can be sent using VBA because
the ultimate goal is that the user can only fill in the blanks via userform therefore
the text remains unchanged. I already have the userform, and have coded in such a way
that the proper blanks are filled in in the text portion and are included in the email
body, however I have not figured out how to include the table as well.



Here is what I have so far as my attempt to add
the table:



Sub SendEmail(what_address As String,
subject_line As String, mail_body As String, claim_info As
Range)



Dim olApp As
Outlook.Application
Set olApp =
CreateObject("Outlook.Application")




Dim
olMail As Outlook.MailItem
Set olMail =
olApp.CreateItem(olMailItem)

olMail.To =
what_address
olMail.Subject = subject_line
olMail.Body =
mail_body
olMail.HTMLBody =
RangeToHtml.claim_info
olMail.Send



End
Sub
Sub
SendClaimsEmail()



Dim
mail_body_message As String
Dim tracking_number As String
Dim
amount_paid As String
Dim date_paid As String
Dim payment_due As
String
Dim claim As Range


Set claim =
Nothing
On Error Resume Next
'Only send the visible cells in the
selection.
Set claim = Selection.SpecialCells(xlCellTypeVisible)
Set
claim = Sheets("Sheet1").RangeToHtml("B2:C9").SpecialCells(xlCellTypeVisible,
xlTextValues)
On Error GoTo 0

mail_body_message =
Sheet1.Range("A1")
tracking_number =
Sheet1.Range("G2")

amount_paid =
Sheet1.Range("G3")
date_paid = Sheet1.Range("G4")
payment_due =
Sheet1.Range("G5")
mail_body_message = Replace(mail_body_message,
"replace_tracking", tracking_number)
mail_body_message =
Replace(mail_body_message, "replace_amountpaid",
amount_paid)
mail_body_message = Replace(mail_body_message,
"replace_datepaid", date_paid)
mail_body_message = Replace(mail_body_message,
"replace_pmtdueto",
payment_due)




Call
SendEmail("email@email.com", "Subject Line", mail_body_message,
claim)


MsgBox
"Complete!"



End Sub

c++ - Undefined reference to vtable

itemprop="text">


When building my C++
program, I'm getting the error message




undefined
reference to
'vtable...




What is
the cause of this problem? How do I fix it?



/>


It so happens that I'm getting the error
for the following code (The class in question is CGameModule.) and I cannot for the life
of me understand what the problem is. At first, I thought it was related to forgetting
to give a virtual function a body, but as far as I understand, everything is all here.
The inheritance chain is a little long, but here is the related source code. I'm not
sure what other information I should
provide.



Note: The constructor is where this
error is happening, it'd seem.



My
code:



class CGameModule : public
CDasherModule {
public:
CGameModule(Dasher::CEventHandler
*pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface,
ModuleID_t iID, const char *szName)
: CDasherModule(pEventHandler,
pSettingsStore, iID, 0, szName)

{

g_pLogger->Log("Inside game module constructor");
m_pInterface =
pInterface;
}

virtual ~CGameModule()
{};

std::string GetTypedTarget();


std::string GetUntypedTarget();


bool
DecorateView(CDasherView *pView) {
//g_pLogger->Log("Decorating the
view");
return false;
}

void
SetDasherModel(CDasherModel *pModel) { m_pModel = pModel;
}


virtual void HandleEvent(Dasher::CEvent *pEvent);



private:




CDasherNode *pLastTypedNode;


CDasherNode
*pNextTargetNode;



std::string
m_sTargetString;


size_t
m_stCurrentStringPos;


CDasherModel
*m_pModel;



CDasherInterfaceBase
*m_pInterface;
};


Inherits
from...



class
CDasherModule;
typedef std::vector::size_type
ModuleID_t;

/// \ingroup Core

///
@{
class CDasherModule : public Dasher::CDasherComponent {

public:
CDasherModule(Dasher::CEventHandler * pEventHandler, CSettingsStore *
pSettingsStore, ModuleID_t iID, int iType, const char *szName);


virtual ModuleID_t GetID();
virtual void SetID(ModuleID_t);

virtual int GetType();
virtual const char
*GetName();


virtual bool GetSettings(SModuleSettings
**pSettings, int *iCount) {
return false;
};


private:
ModuleID_t m_iID;
int m_iType;
const char
*m_szName;
};



Which
inherits from....



namespace Dasher
{
class CEvent;
class CEventHandler;
class
CDasherComponent;
};

/// \ingroup
Core

/// @{
class Dasher::CDasherComponent {

public:
CDasherComponent(Dasher::CEventHandler* pEventHandler,
CSettingsStore* pSettingsStore);
virtual
~CDasherComponent();

void InsertEvent(Dasher::CEvent *
pEvent);
virtual void HandleEvent(Dasher::CEvent * pEvent)
{};

bool GetBoolParameter(int iParameter)
const;

void SetBoolParameter(int iParameter, bool bValue)
const;

long GetLongParameter(int iParameter) const;

void SetLongParameter(int iParameter, long lValue) const;


std::string GetStringParameter(int iParameter) const;
void
SetStringParameter(int iParameter, const std::string & sValue)
const;

ParameterType GetParameterType(int iParameter)
const;
std::string GetParameterName(int iParameter)
const;


protected:
Dasher::CEventHandler
*m_pEventHandler;
CSettingsStore
*m_pSettingsStore;
};
///
@}


#endif



Answer




So, I've figured out the issue and it was a
combination of bad logic and not being totally familiar with the automake/autotools
world. I was adding the correct files to my Makefile.am template, but I wasn't sure
which step in our build process actually created the makefile itself. So, I was
compiling with an old makefile that had no idea about my new files
whatsoever.



Thanks for the responses and the
link to the GCC FAQ. I will be sure to read that to avoid this problem occurring for a
real reason.


How to iterate the objects in array in jQuery?

itemprop="text">

I have a JSON
object:




[{

name:'bhavani',
age:'19',
gender:'Female'
},{

name:'bhavani',
age:'19',

gender:'Female'
},{

name:'bhavani',

age:'19',
gender:'Female'
}, {
// and so
on
}]


Now i
need to access the name in each object in this array in a JSP
page. I am unable to do it. Can anyone solve this problem for me
please.



Answer





To loop over an array or an
object's properties you can use the $.each
function.



Fiddle: href="http://jsfiddle.net/AtheistP3ace/ohswrnmn/"
rel="nofollow">http://jsfiddle.net/AtheistP3ace/ohswrnmn/



var
data = [{
name: 'bhavani',
age: '19',
gender:
'Female'
}, {
name: 'bhavani',

age:
'19',
gender: 'Female'
}, {
name: 'bhavani',

age: '19',
gender: 'Female'
}, ];

var $test =
$('#test');
$.each(data,

function (index, value)
{
$test.append(value.name + ' ');

}
);


jQuery
docs: rel="nofollow">http://api.jquery.com/jquery.each/



Example
looping over array and each objects
properties:




Fiddle: href="http://jsfiddle.net/AtheistP3ace/ohswrnmn/1/"
rel="nofollow">http://jsfiddle.net/AtheistP3ace/ohswrnmn/1/



var
data = [{
name: 'bhavani',
age: '19',
gender:
'Female'
}, {
name: 'bhavani',
age: '19',

gender: 'Female'

}, {
name: 'bhavani',
age:
'19',
gender: 'Female'
}, ];

var $test =
$('#test');
$.each(data,
function (index, value) {

$test.append(index + ': ');

$.each(value,
function
(index2, value2) {
$test.append(value2 + ' ');
}

);
$test.append(' - ');

}
);

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 &q...