Saturday 31 August 2019

PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in C:apache2triadhtdocsimagedisplay.php on line 28

hi i am getting an error during my execution of the code : PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in C:\apache2triad\htdocs\imagedisplay.php on line 28





$dir= "C:\apache2triad\htdocs\phppgadmin\images\phpimages";

$file_display= array('jpg', 'jpeg', 'png', 'gif');

if(file_exists($dir)== false)
{
echo "directory x not found";

}
else
{
$dir_content= scandir($dir);

foreach($dir_content as $file)
{
$file_type = strtolower(end(explode('.', $file)));

// echo "$file
";


if($file !=='.' && $file !=='..')
{
//echo "$file
";
echo "', $file, '";
}
}
}
?>



please help

plot explanation - Maximus fighting the masked champion in the arena with tigers - Movies & TV



When Maximus is knocked to the ground he lands a shot through his opponent's foot with an axe. His opponent then seems to be spitting blood (hard to tell due to the helmet) and then falls over dead.



Why did he die?


Answer



This is from the script. I couldn't find a video. The blood probably comes from the blow to the head. Tigris was pretty injured from this hit but was probably trying to hold back any sign of his being hurt that bad until the axe went into his foot and he couldn't stand the pain so the blood that was in his mouth from the hit to the head came out at that time.



Maximus finally manages to land a stunning blow to his opponent’s head causing Tigris to drop his axe. Maximus switches his sword to his other hand and stands ready to administer the killing blow. Suddenly a fourth tiger jumps out of the last door and leaps on Maximus and just as quickly, Maximus twists and turns his sword arm, impaling the tiger. He is thrown to the ground by the weight of the beast all the while stabbing and eventually killing the big cat. The crowd cheers.




Tigris seeing an advantage moves closer. Maximus, pinned under the weight of the tiger, reaches out and grabs Tigris lost axe. The axe has a spike on one end and in one movement; Maximus brings the spike down and into the top of Tigris foot. Tigris bends over from the pain, blood pouring from the mouth of his mask. Maximus jumps to his feet and kicks Tigris to the ground. Maximus standing over the fallen Tigris lifts the other man’s face cover and raised the axe. He looks to Commodus for direction. The crowd yells.


sql - How to combine rows in Amazon Redshift

Redshift provides a function LISTAGG() for what you need



SELECT id, name, LISTAGG(Color,' ') AS Colors
FROM yourtable
GROUP BY id, name




For each group in a query, the LISTAGG aggregate function orders the
rows for that group according to the ORDER BY expression, then
concatenates the values into a single string.
http://docs.aws.amazon.com/redshift/latest/dg/r_LISTAGG.html




SELECT id, name
, LISTAGG(Color,' ') WITHIN GROUP (ORDER BY name) AS Colors
FROM yourtable
GROUP BY id, name

Easiest way to convert int to string in C++




What is the easiest way to convert from int to equivalent string in C++. I am aware of two methods. Is there any easier way?



(1)



int a = 10;
char *intStr = itoa(a);
string str = string(intStr);



(2)



int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

Answer



C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.




#include  

std::string s = std::to_string(42);


is therefore the shortest way I can think of. You can even omit naming the type, using the auto keyword:



auto s = std::to_string(42);



Note: see [string.conversions] (21.5 in n3242)


c++ - Structure of arrays and array of structures - performance difference



I have a class like this:



//Array of Structures
class Unit
{
public:
float v;

float u;
//And similarly many other variables of float type, upto 10-12 of them.
void update()
{
v+=u;
v=v*i*t;
//And many other equations
}
};



I create an array of objects of Unit type. And call update on them.



int NUM_UNITS = 10000;
void ProcessUpdate()
{
Unit *units = new Unit[NUM_UNITS];
for(int i = 0; i < NUM_UNITS; i++)
{
units[i].update();

}
}


In order to speed up things, and possibly autovectorize the loop, I converted AoS to structure of arrays.



//Structure of Arrays:
class Unit
{
public:

Unit(int NUM_UNITS)
{
v = new float[NUM_UNITS];
}
float *v;
float *u;
//Mnay other variables
void update()
{
for(int i = 0; i < NUM_UNITS; i++)

{
v[i]+=u[i];
//Many other equations
}
}
};


When the loop fails to autovectorize, i am getting a very bad performance for structure of arrays. For 50 units, SoA's update is slightly faster than AoS.But then from 100 units onwards, SoA is slower than AoS. At 300 units, SoA is almost twice as worse. At 100K units, SoA is 4x slower than AoS. While cache might be an issue for SoA, i didnt expect the performance difference to be this high. Profiling on cachegrind shows similar number of misses for both approach. Size of a Unit object is 48 bytes. L1 cache is 256K, L2 is 1MB and L3 is 8MB. What am i missing here? Is this really a cache issue?




Edit:
I am using gcc 4.5.2. Compiler options are -o3 -msse4 -ftree-vectorize.



I did another experiment in SoA. Instead of dynamically allocating the arrays, i allocated "v" and "u" in compile time. When there are 100K units, this gives a performance which is 10x faster than the SoA with dynamically allocated arrays. Whats happening here? Why is there such a performance difference between static and dynamically allocated memory?


Answer



Structure of arrays is not cache friendly in this case.



You use both u and v together, but in case of 2 different arrays for them they will not be loaded simultaneously into one cache line and cache misses will cost huge performance penalty.



_mm_prefetch can be used to make AoS representation even faster.



java - What is the proper way to navigate between windows?





I am trying to make a simple Customer tracking program.It stars with a window with 4 buttons and you choose a task to do.



I need to navigate between different windows
-Home Menu
-New Customer
-Customer

-Reports



What i do is creating different Jframes for each task but i don't know if it is the right way to do.



So my question is What is the proper way to navigate between windows on Java?


Answer



Please do not create multiple JFrames unless absolutely necessary.



Why?





  • There's multiple icons in the taskbar (on Windows and Linux).

  • Switching windows is an added burden to the user.

  • It raises issues with, e.g., the close button (do they all close if any close? is there one master?), etc.



Instead:



Consider using a JTabbedPane.





To create a tabbed pane, instantiate JTabbedPane, create the components you wish it to display, and then add the components to the tabbed pane using the addTab method.




For example:



JTabbedPane tabbedPane = new JTabbedPane();

JComponent someComponent = ...
tabbedPane.addTab("Tab 1", someComponent);


JComponent anotherComponent = ...
tabbedPane.addTab("Tab 2", anotherComponent);





Alternatively, you could use a CardLayout if you only want your users to see one view at a time.





The CardLayout class manages two or more components (usually JPanel instances) that share the same display space. Conceptually, each component that a CardLayout manages is like a playing card or trading card in a stack, where only the top card is visible at any time.



c++ - shared_ptr magic :)




Mr. Lidström and I had an argument :)



Mr. Lidström's claim is that a construct shared_ptr p(new Derived); doesn't require Base to have a virtual destructor:




Armen Tsirunyan: "Really? Will the shared_ptr clean up correctly? Could you please in this case demonstrate how that effect could be implemented?"



Daniel Lidström: "The shared_ptr uses its own destructor to delete the Concrete instance. This is known as RAII within the C++ community. My advice is that you learn all you can about RAII. It will make your C++ coding so much easier when you use RAII in all situations."



Armen Tsirunyan: "I know about RAII, and I also know that eventually the shared_ptr destructor may delete the stored px when pn reaches 0. But if px had static type pointer to Base and dynamic type pointer to Derived, then unless Base has a virtual destructor, this will result in undefined behavior. Correct me if I am wrong."




Daniel Lidström: "The shared_ptr knows the static type is Concrete. It knows this since I passed it in its constructor! Seems a bit like magic, but I can assure you it is by design and extremely nice."




So, judge us. How is it possible (if it is) to implement shared_ptr without requiring polymorphic classes to have virtual destructor?
Thanks in advance


Answer



Yes, it is possible to implement shared_ptr that way. Boost does and the C++11 standard also requires this behaviour. As an added flexibility shared_ptr manages more than just a reference counter. A so-called deleter is usually put into the same memory block that also contains the reference counters. But the fun part is that the type of this deleter is not part of the shared_ptr type. This is called "type erasure" and is basically the same technique used for implementing the "polymorphic functions" boost::function or std::function for hiding the actual functor's type. To make your example work, we need a templated constructor:



template

class shared_ptr
{
public:
...
template
explicit shared_ptr(Y* p);
...
};



So, if you use this with your classes Base and Derived ...



class Base {};
class Derived : public Base {};

int main() {
shared_ptr sp (new Derived);
}



... the templated constructor with Y=Derived is used to construct the shared_ptr object. The constructor has thus the chance to create the appropriate deleter object and reference counters and stores a pointer to this control block as a data member. If the reference counter reaches zero, the previously created and Derived-aware deleter will be used to dispose of the object.



The C++11 standard has the following to say about this constructor (20.7.2.2.1):




Requires: p must be convertible to T*. Y shall be a complete type. The expression delete p shall be well formed, shall have well defined behaviour and shall not throw exceptions.



Effects: Constructs a shared_ptr object that owns the pointer p.







And for the destructor (20.7.2.2.2):




Effects: If *this is empty or shares ownership with another shared_ptr instance (use_count() > 1), there are no side effects.
Otherwise, if *this owns an object p and a deleter d, d(p) is called.
Otherwise, if *this owns a pointer p, and delete p is called.





(emphasis using bold font is mine).


indian cinema - Why do Bollywood movies have song and dance sequences?

Unlike Hollywood movies, Bollywood movies are quite different, because they're usually mixed with masala i.e dance, song and love sequences. This is the case in most films which are released in various languages in India.


Can someone explain, Why do Bollywood movies have song and dance sequences?


Answer


There may be quite a few reasons for this



  • There are not many bands that perform music on a large scale, at least not till recently

  • Peer Pressure, everybody is doing it

  • Pressure from Producers / Distributors

  • If Songs become a huge hit and even if the movie is not that great it can still fetch the producers and distributors enough money (Eg The movie 3).

  • The legacy left over from the 1950s, it just refuses to go away .


c# - The name 'ViewBag' does not exist in the current context - Visual Studio 2015



I'm starting to develop in ASP.NET again and I ran into a small error within Visual Studio. My .cshtml files show errors when using a few razor functions. For example "The name 'ViewBag' does not exist in the current context". Here is a picture:




screenshot of problem in visual studio 2015



I am using a demo project. You can find the project here: https://github.com/Wintellect/Angular-MVC-Cookbook/tree/master/BasicProject



I have looked through several other threads and most suggest to update the web.config file(s). These 2 config files are already present and since it's a pretty popular demo I assume it has all the required configuration in it. I have of course looked through these config files and they do indeed include the suggested solutions.



Other details:





  • I have already used clean & rebuild on the solution but that changed nothing.

  • When I create a completely new MVC project it does work

  • My friend has the same problem and we both use VS 2015 and Windows 10

  • I can still run the application and it does work.



Thanks in advance.


Answer



I had this issue despite having all the correct configuration.




It turned out to be some bad files in the Component Cache, preventing the Razor views from recognising ViewBag, Model, and HtmlHelpers. Deleting these files solved the problem (good versions of these files were created next time I opened Visual Studio).



The files are located here:



%LOCALAPPDATA%\Microsoft\VisualStudio\14.0\ComponentModelCache


Delete all four files:





  • Microsoft.VisualStudio.Default.cache

  • Microsoft.VisualStudio.Default.catalogs

  • Microsoft.VisualStudio.Default.err

  • Microsoft.VisualStudio.Default.external



I have subsequently seen the same issue on several other developer machines and this fix quickly solves it.


linux - sed - how to do regex groups using sed



Is there anyway you can do regex match group using sed like java regex pattern/match/group?




if i have string like



test-artifact-201251-balbal-0.1-SNAPSHOT.jar


how do I use sed just to get the result like:



test-artifact-0.1-SNASHOT.jar



I am wondering does sed allow you to do something like java regex, you define the pattern like:



([a-z]*-[a-z]*-)([0-9]*-)([a-z]*-)([.]*SNAPSHOT.jar)


and then you can get the results as an array like:



test-artifact-
201251-

balbal-
0.1-SNAPSHOT.jar

Answer



You have to escape parentheses to group expressions:



\([a-z]*-[a-z]*-\)\([0-9]*-\)\([a-z]*-\)\([.]*SNAPSHOT.jar\)


And use them with \1, \2, etc.







EDIT: Also note just before SNAPSHOT that [.] will not match. Inside brackets . is literal. It should be [0-9.-]*


javascript - Pass unknown number of parameters to JS function




A pattern in some javascript libraries is to be able to pass any number of parameters to a function:




functiona(param1)
functiona(param1, param2, param3)
functiona(param1, param2)


I have an array of unknown length, and I'd like to pass all the array items as parameters to a function like functiona(). Is this possible? If so, what is the syntax for doing this?


Answer



What you want is probably Function.prototype.apply().



Usage:




var params = [param1, param2, param3];
functiona.apply(this, params);


As others noted, functiona declaration may use arguments, e.g.:



function functiona()
{
var param1 = this.arguments[0];

var param2 = this.arguments[1];
}


But it can use any number of normal parameters as well:



function foo(x, y)
{
console.log(x);
}

foo.apply(this, [10, 0, null]); // outputs 10

input - Java: Console class







Reading the java documentation, i found this statement about Console class





First, it suppresses echoing, so the password is not visible on the user's screen. Second, readPassword returns a character array, not a String, so the password can be overwritten, removing it from memory as soon as it is no longer needed.




Why a character array can be overwritten and a String not?
Or maybe a character array can be overwritted in a more simple way?

angular - How to loop through a JSON object with typescript (Angular2)

I am new to Angular2 and I am trying to loop through a JSON object that I am getting back from a GET request but can't work it out.




My JSON object:



{
Results: [{
Time: "2017-02-11T08:15:01.000+00:00",
Id: "data-mopdsjkajskda",
AuthorId: "58fSDNJD"
}, {
Time: "2017-03-11T06:23:34.000+00:00",
Id: "data-2371212hjb1",

AuthorId: "43555HHHJ"
}, {
Time: "2017-04-11T07:05:11.000+00:00",
Id: "data-kjskdha22112",
AuthorId: "XDSJKJSDH"
}]
}


Part of my Angular script:




interface res {
Time: string;
Id: string;
AuthorId: string;
}
export class AppComponent {
results: res;
constructor(private _httpservice: HTTPService) {}
this._httpservice.getQuery().subscribe(

data => {
this.results = data.Results
},
error => console.log(error),
() => console.log('Done')
);
}


I do get the data back - which is great. However, I want to push the Ids into an array. In Javascript I would do this:




var ids = [];

for (i = 0; i < data.Results.length; i++) {
ids.push(data.Results[i].Id)
}


The array after the push:




ids = ['data-mopdsjkajskda', 'data-2371212hjb1', 'data-kjskdha22112'];


I am struggling to find a way to achieve the same results with Angular2. Any help would be greatly appreciated!

c# - SMTP error: "Client does not have permission to submit mail to this server"

I'm getting the following error while sending email. What could be the cause?





Client does not have permission to
submit mail to this server. The server
response was: 5.5.1 STARTTLS may not
be repeated.




Here's the stack trace...




Stack Trace



at System.Net.Mail.StartTlsCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.StartTlsCommand.Send(SmtpConnection conn)
at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)



I'm connecting to smtp.gmail.com with SSL on port 587 / 465

SQL injection vulnerability to add more balance?

Let's say I have this SQL statement:



stmt.executeUpdate("INSERT INTO TUNEUSER (USERNAME,PASSWORD,BALANCE) VALUES ('"
+ daf.getString("username")
+ "','"

+ daf.getString("password")
+ "',0.00)");


and the application has a username and password field.



How can SQL injection be used to increased the balance from "0.00" to whatever you want?

Friday 30 August 2019

prepared statement - Mysqli - Are parameterized queries enough for preventing XSS second order attacks?




I am working on a dynamic application and I am not sure if parameterized queries are safe from XSS, second order attacks? Can you help me? Thanks!



I have this code as an example:




$stmt = $mysqli->prepare("INSERT INTO tb (1, 2, 3, 4, 5, 6, 7) VALUES (?, ?, ?, ?, ?, ?, ?)");

$stmt->bind_param('sssssss', $1, $2, $3, $4, $5, $6, $7);
$stmt->execute();

$stmt->close();

Answer



Nope.



A parametrized query protects against SQL Injection; that is it ensures query parameters are well formed and correctly escaped prior to processing by the SQL back end.



XSS is a different class of problem whereby input should be sanitized of HTML markup; given that a correctly parametrized SQL value can still contain markup, you need additional encoding (E.g. htmlspecialchars()).


c# - Huge performance difference (26x faster) when compiling for 32 and 64 bits



I was trying to measure the difference of using a for and a foreach when accessing lists of value types and reference types.



I used the following class to do the profiling.




public static class Benchmarker
{
public static void Profile(string description, int iterations, Action func)
{
Console.Write(description);

// Warm up
func();

Stopwatch watch = new Stopwatch();


// Clean up
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

watch.Start();
for (int i = 0; i < iterations; i++)
{
func();

}
watch.Stop();

Console.WriteLine(" average time: {0} ms", watch.Elapsed.TotalMilliseconds / iterations);
}
}


I used double for my value type.
And I created this 'fake class' to test reference types:




class DoubleWrapper
{
public double Value { get; set; }

public DoubleWrapper(double value)
{
Value = value;
}
}



Finally I ran this code and compared the time differences.



static void Main(string[] args)
{
int size = 1000000;
int iterationCount = 100;

var valueList = new List(size);

for (int i = 0; i < size; i++)
valueList.Add(i);

var refList = new List(size);
for (int i = 0; i < size; i++)
refList.Add(new DoubleWrapper(i));

double dummy;

Benchmarker.Profile("valueList for: ", iterationCount, () =>

{
double result = 0;
for (int i = 0; i < valueList.Count; i++)
{
unchecked
{
var temp = valueList[i];
result *= temp;
result += temp;
result /= temp;

result -= temp;
}
}
dummy = result;
});

Benchmarker.Profile("valueList foreach: ", iterationCount, () =>
{
double result = 0;
foreach (var v in valueList)

{
var temp = v;
result *= temp;
result += temp;
result /= temp;
result -= temp;
}
dummy = result;
});


Benchmarker.Profile("refList for: ", iterationCount, () =>
{
double result = 0;
for (int i = 0; i < refList.Count; i++)
{
unchecked
{
var temp = refList[i].Value;
result *= temp;
result += temp;

result /= temp;
result -= temp;
}
}
dummy = result;
});

Benchmarker.Profile("refList foreach: ", iterationCount, () =>
{
double result = 0;

foreach (var v in refList)
{
unchecked
{
var temp = v.Value;
result *= temp;
result += temp;
result /= temp;
result -= temp;
}

}

dummy = result;
});

SafeExit();
}


I selected Release and Any CPU options, ran the program and got the following times:




valueList for:  average time: 483,967938 ms
valueList foreach: average time: 477,873079 ms
refList for: average time: 490,524197 ms
refList foreach: average time: 485,659557 ms
Done!


Then I selected Release and x64 options, ran the program and got the following times:




valueList for:  average time: 16,720209 ms
valueList foreach: average time: 15,953483 ms
refList for: average time: 19,381077 ms
refList foreach: average time: 18,636781 ms
Done!


Why is x64 bit version so much faster? I expected some difference, but not something this big.



I do not have access to other computers. Could you please run this on your machines and tell me the results? I'm using Visual Studio 2015 and I have an Intel Core i7 930.




Here's the SafeExit() method, so you can compile/run by yourself:



private static void SafeExit()
{
Console.WriteLine("Done!");
Console.ReadLine();
System.Environment.Exit(1);
}



As requested, using double? instead of my DoubleWrapper:



Any CPU



valueList for:  average time: 482,98116 ms
valueList foreach: average time: 478,837701 ms
refList for: average time: 491,075915 ms
refList foreach: average time: 483,206072 ms
Done!



x64



valueList for:  average time: 16,393947 ms
valueList foreach: average time: 15,87007 ms
refList for: average time: 18,267736 ms
refList foreach: average time: 16,496038 ms
Done!



Last but not least: creating a x86 profile gives me almost the same results of using Any CPU.


Answer



I can reproduce this on 4.5.2. No RyuJIT here. Both x86 and x64 disassemblies look reasonable. Range checks and so on are the same. The same basic structure. No loop unrolling.



x86 uses a different set of float instructions. The performance of these instructions seems to be comparable with the x64 instructions except for the division:




  1. The 32 bit x87 float instructions use 10 byte precision internally.

  2. Extended precision division is super slow.




The division operation makes the 32 bit version extremely slow. Uncommenting the division equalizes performance to a large degree (32 bit down from 430ms to 3.25ms).



Peter Cordes points out that the instruction latencies of the two floating point units are not that dissimilar. Maybe some of the intermediate results are denormalized numbers or NaN. These might trigger a slow path in one of the units. Or, maybe the values diverge between the two implementations because of 10 byte vs. 8 byte float precision.



Peter Cordes also points out that all intermediate results are NaN... Removing this problem (valueList.Add(i + 1) so that no divisor is zero) mostly equalizes the results. Apparently, the 32 bit code does not like NaN operands at all. Let's print some intermediate values: if (i % 1000 == 0) Console.WriteLine(result);. This confirms that the data is now sane.



When benchmarking you need to benchmark a realistic workload. But who would have thought that an innocent division can mess up your benchmark?!




Try simply summing the numbers to get a better benchmark.



Division and modulo are always very slow. If you modify the BCL Dictionary code to simply not use the modulo operator to compute the bucket index performance measurable improves. This is how slow division is.



Here's the 32 bit code:



enter image description here



64 bit code (same structure, fast division):




enter image description here



This is not vectorized despite SSE instructions being used.


java - nextLine method in the Scanner



Possible Duplicate:
Scanner issue when using nextLine after nextInt






Why is the empty sc.nextLine(); under the husband so necessary? it did not equal to anything, and surely the wife did not have that line... but the program won't run without it. My book comments it as Skip over trailing newLine character. but I don't see how there's anything to skip!



public class FileTest {
public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("For your blended family, \n enter the wife's name");
String wife = sc.nextLine();
System.out.print("Enter the number of her children:");
int herkids = sc.nextInt();

System.out.print("Enter the husband's name:");
//sc.nextLine(); // Why is this line so necessary?
String husband = sc.nextLine();
System.out.print("Enter the number of his children:");

int hisKids = sc.nextInt();

System.out.println(wife + " and " + husband + " have " + (herkids + hisKids) + " children.");

}
}

reactjs - React routing on click event is not working




I am doing routing on button click event




  redirect(){

return ;

}


Its not working.



my home page- base component:




import React, { Fragment } from 'react';

render() {

const { value } = this.state;

return (


















} />


} />



} />






From my child component I have to redirect to another component,
here is my child component:




  



redirect(){

return ;

}



So but I am not getting any console error too.


Answer



is a component. So, you should use it like this.



class App extends React.Component{
state = {
isRedirect: false,
}


redirect = () => {
this.setState({ isRedirect: true });
}

render() {
return (
<>


{this.state.isRedirect ? : null }


)
}

}



OR




You can use history API



but you should add withRouter()



class App extends React.Component{
render(){
return(
<>



)
}
}

export default withRouter(App);


php - SQL Injection through mysql_query

I'm working on a site that has been hacked through SQL Injection (at first glance only db entries are corrupted with cross-site scripting) the potential vulnerability I found after looking at the code is that there's a lot of mysql_query call whose inputs are not escaped at all.



The good old :



$query = "SELECT * FROM mytable where name LIKE '%".$_GET['name']."%'"; /*HACK HERE*/
mysql_query($query, $connection);



Nevertheless I can't find how can we do something cool from that injection vulnerability (by cool I mean something like an INSERT or an UPDATE). I've tried to build a statement like this one :



SELECT * FROM mytable where name LIKE '%' AND WHERE id IN (INSERT INTO secondtable (id,description) VALUES (15, 'Fifteenth description');--%'


No success. I guess that the INSERT has nothing to do here.



I'm escaping all user's inputs in the code right now but I've not really get how hackers have penetrated this site, then I'm not 100% sure that my fix will do the job. Any brilliant suggestions ?




Thanks

Java Thread.sleep() on Windows 10 stops in S3 sleep status

There's a desktop application that uses Thread.sleep() to achieve long (minutes or hours) delays. This same application has been working fine from Windows XP through (at least) Windows 7. The application calculates how far in the future it needs to do something, then hits a Thread.sleep(msToWait). This has been working fine, even if the system happens to go into S3 sleep state during the wait.



As of Windows 10, though, the code after Thread.sleep() does not execute "on time" if the machine has been in S3. It appears that the machine begins executing code at "msToWait" plus the time the machine has been in S3 (not 100% sure of this right now, but likely).



Earlier versions of Windows did not exhibit this behavior; code after Thread.sleep() waited the right amount of time, irrespective of sleep status.



Testing has been on the current JVM 1.7.



Is this a Windows 10 bug? Is this a JVM bug? Is there a work-around?




ADDITIONAL DATA:



A test program and procedure were developed. The procedure is to run the program, cause the machine to sleep for about a minute, then wake the machine and wait for the program to finish.



If this the program is run on Windows 10 (reporting as 8) with JVM Version: 25.40-b25, it fails:



C:\Users\Tester\Downloads>SleepTester.exe
Wed Apr 01 10:47:35 PDT 2015 Using default number of minutes: 5
Wed Apr 01 10:47:35 PDT 2015 You can use "SleepTester -minutes 10" to have it sleep for 10 minutes, for example.

Wed Apr 01 10:47:35 PDT 2015 JVM Version: 25.40-b25 Windows Version: Windows 8
Wed Apr 01 10:47:35 PDT 2015 The program will now wait for 5 minutes. Expect wrap-up at Wed Apr 01 10:52:35 PDT 2015
Wed Apr 01 10:53:38 PDT 2015 The system has come through the Thread.sleep(300000).
Wed Apr 01 10:53:38 PDT 2015 This should be a low number: 63589
Wed Apr 01 10:53:38 PDT 2015 This appears to be operating incorrectly...the expected sleep time has NOT been achieved.
Wed Apr 01 10:53:38 PDT 2015 Program is ending.


If the process is run on Windows 7, it does not fail.




Wed Apr 01 17:12:18 EDT 2015 Java Runtime Version: 1.8.0_31-b13 JVM Version: 25.31-b07 Windows Version: Windows 7
Wed Apr 01 17:12:18 EDT 2015 The program will now wait for 6 minutes. Expect wrap-up at Wed Apr 01 17:18:18 EDT 2015
Wed Apr 01 17:18:18 EDT 2015 The system has come through the Thread.sleep(360000).
Wed Apr 01 17:18:18 EDT 2015 This should be a low number: 0
Wed Apr 01 17:18:18 EDT 2015 Program is ending.


This is the test program:



import java.util.Date;


public class SleepTester {

private static int mMinutes;
private static int mDefault = 5;

public static void main(String[] args) throws Exception {
for (int iArg = 0; iArg < args.length; ++iArg) {
if (args[iArg].equals("-minutes") && (iArg + 1) < args.length) {
mMinutes = Integer.parseInt(args[++iArg]);

}
}

if (mMinutes == 0) {
mMinutes = mDefault;
System.out.println(new Date() + " Using default number of minutes: " + mDefault);
System.out.println(new Date() + " You can use \"SleepTester -minutes 10\" to have it sleep for 10 minutes, for example.");
}

System.out.println(new Date() + " Java Runtime Version: " + System.getProperty("java.runtime.version") + " JVM Version: " + System.getProperty("java.vm.version") + " Windows Version: " + System.getProperty("os.name"));

long msDelay = mMinutes * 60 * 1000;
long wakePoint = new Date().getTime() + msDelay;
System.out.println(new Date() + " The program will now wait for " + mMinutes + " minutes. Expect wrap-up at " + new Date(wakePoint));
Thread.sleep(msDelay); // If the machine goes into S3 during this interval, it should not matter, as long as it's awake when it fires.
System.out.println(new Date() + " The system has come through the Thread.sleep(" + msDelay + "). ");
long msAccuracy = Math.abs(new Date().getTime() - wakePoint);
System.out.println(new Date() + " This should be a low number: " + msAccuracy);
if (msAccuracy > 1000) System.out.println(new Date() + " This appears to be operating incorrectly...the expected sleep time has NOT been achieved.");
System.out.println(new Date() + " Program is ending.");
}

}


I realize I could try various other methods to sleep, but I thought that since I went through and documented this, I'd post it here before trying other things.



Additional Information: This failure seems also to appear in Windows 8 (but not 7 or prior).



ADDITION 4/4/2019



The issue is visible on bugs.java.com at the following url JDK-8221971.




There are a few earlier bugs linked to that bug. A comment from the linke JDK-8146730 bug:




17-04-2017 Any news on this topic?



04-04-2019 It has been deferred. It is a low priority, and complex, issue no one is actively assigned to it.


How do I use arrays in C++?



C++ inherited arrays from C where they are used virtually everywhere. C++ provides abstractions that are easier to use and less error-prone (std::vector since C++98 and std::array since C++11), so the need for arrays does not arise quite as often as it does in C. However, when you read legacy code or interact with a library written in C, you should have a firm grasp on how arrays work.



This FAQ is split into five parts:





  1. arrays on the type level and accessing elements

  2. array creation and initialization

  3. assignment and parameter passing

  4. multidimensional arrays and arrays of pointers

  5. common pitfalls when using arrays



If you feel something important is missing in this FAQ, write an answer and link it here as an additional part.




In the following text, "array" means "C array", not the class template std::array. Basic knowledge of the C declarator syntax is assumed. Note that the manual usage of new and delete as demonstrated below is extremely dangerous in the face of exceptions, but that is the topic of another FAQ.




(Note: This is meant to be an entry to C++ FAQ. If you want to critique the idea of providing an FAQ in this form, then the posting on meta that started all this would be the place to do that. Answers to that question are monitored in the C++ chatroom, where the FAQ idea started out in the first place, so your answer is very likely to get read by those who came up with the idea.)


Answer





An array type is denoted as T[n] where T is the element type and n is a positive size, the number of elements in the array. The array type is a product type of the element type and the size. If one or both of those ingredients differ, you get a distinct type:




#include 

static_assert(!std::is_same::value, "distinct element type");
static_assert(!std::is_same::value, "distinct size");


Note that the size is part of the type, that is, array types of different size are incompatible types that have absolutely nothing to do with each other. sizeof(T[n]) is equivalent to n * sizeof(T).



Array-to-pointer decay




The only "connection" between T[n] and T[m] is that both types can implicitly be converted to T*, and the result of this conversion is a pointer to the first element of the array. That is, anywhere a T* is required, you can provide a T[n], and the compiler will silently provide that pointer:



                  +---+---+---+---+---+---+---+---+
the_actual_array: | | | | | | | | | int[8]
+---+---+---+---+---+---+---+---+
^
|
|
|

| pointer_to_the_first_element int*


This conversion is known as "array-to-pointer decay", and it is a major source of confusion. The size of the array is lost in this process, since it is no longer part of the type (T*). Pro: Forgetting the size of an array on the type level allows a pointer to point to the first element of an array of any size. Con: Given a pointer to the first (or any other) element of an array, there is no way to detect how large that array is or where exactly the pointer points to relative to the bounds of the array. Pointers are extremely stupid.



Arrays are not pointers



The compiler will silently generate a pointer to the first element of an array whenever it is deemed useful, that is, whenever an operation would fail on an array but succeed on a pointer. This conversion from array to pointer is trivial, since the resulting pointer value is simply the address of the array. Note that the pointer is not stored as part of the array itself (or anywhere else in memory). An array is not a pointer.



static_assert(!std::is_same::value, "an array is not a pointer");



One important context in which an array does not decay into a pointer to its first element is when the & operator is applied to it. In that case, the & operator yields a pointer to the entire array, not just a pointer to its first element. Although in that case the values (the addresses) are the same, a pointer to the first element of an array and a pointer to the entire array are completely distinct types:



static_assert(!std::is_same::value, "distinct element type");


The following ASCII art explains this distinction:



      +-----------------------------------+

| +---+---+---+---+---+---+---+---+ |
+---> | | | | | | | | | | | int[8]
| | +---+---+---+---+---+---+---+---+ |
| +---^-------------------------------+
| |
| |
| |
| | pointer_to_the_first_element int*
|
| pointer_to_the_entire_array int(*)[8]



Note how the pointer to the first element only points to a single integer (depicted as a small box), whereas the pointer to the entire array points to an array of 8 integers (depicted as a large box).



The same situation arises in classes and is maybe more obvious. A pointer to an object and a pointer to its first data member have the same value (the same address), yet they are completely distinct types.



If you are unfamiliar with the C declarator syntax, the parenthesis in the type int(*)[8] are essential:




  • int(*)[8] is a pointer to an array of 8 integers.


  • int*[8] is an array of 8 pointers, each element of type int*.





C++ provides two syntactic variations to access individual elements of an array.
Neither of them is superior to the other, and you should familiarize yourself with both.



Pointer arithmetic




Given a pointer p to the first element of an array, the expression p+i yields a pointer to the i-th element of the array. By dereferencing that pointer afterwards, one can access individual elements:



std::cout << *(x+3) << ", " << *(x+7) << std::endl;


If x denotes an array, then array-to-pointer decay will kick in, because adding an array and an integer is meaningless (there is no plus operation on arrays), but adding a pointer and an integer makes sense:



   +---+---+---+---+---+---+---+---+
x: | | | | | | | | | int[8]
+---+---+---+---+---+---+---+---+

^ ^ ^
| | |
| | |
| | |
x+0 | x+3 | x+7 | int*


(Note that the implicitly generated pointer has no name, so I wrote x+0 in order to identify it.)



If, on the other hand, x denotes a pointer to the first (or any other) element of an array, then array-to-pointer decay is not necessary, because the pointer on which i is going to be added already exists:




   +---+---+---+---+---+---+---+---+
| | | | | | | | | int[8]
+---+---+---+---+---+---+---+---+
^ ^ ^
| | |
| | |
+-|-+ | |
x: | | | x+3 | x+7 | int*
+---+



Note that in the depicted case, x is a pointer variable (discernible by the small box next to x), but it could just as well be the result of a function returning a pointer (or any other expression of type T*).



Indexing operator



Since the syntax *(x+i) is a bit clumsy, C++ provides the alternative syntax x[i]:



std::cout << x[3] << ", " << x[7] << std::endl;



Due to the fact that addition is commutative, the following code does exactly the same:



std::cout << 3[x] << ", " << 7[x] << std::endl;


The definition of the indexing operator leads to the following interesting equivalence:



&x[i]  ==  &*(x+i)  ==  x+i



However, &x[0] is generally not equivalent to x. The former is a pointer, the latter an array. Only when the context triggers array-to-pointer decay can x and &x[0] be used interchangeably. For example:



T* p = &array[0];  // rewritten as &*(array+0), decay happens due to the addition
T* q = array; // decay happens due to the assignment


On the first line, the compiler detects an assignment from a pointer to a pointer, which trivially succeeds. On the second line, it detects an assignment from an array to a pointer. Since this is meaningless (but pointer to pointer assignment makes sense), array-to-pointer decay kicks in as usual.



Ranges




An array of type T[n] has n elements, indexed from 0 to n-1; there is no element n. And yet, to support half-open ranges (where the beginning is inclusive and the end is exclusive), C++ allows the computation of a pointer to the (non-existent) n-th element, but it is illegal to dereference that pointer:



   +---+---+---+---+---+---+---+---+....
x: | | | | | | | | | . int[8]
+---+---+---+---+---+---+---+---+....
^ ^
| |
| |
| |

x+0 | x+8 | int*


For example, if you want to sort an array, both of the following would work equally well:



std::sort(x + 0, x + n);
std::sort(&x[0], &x[0] + n);


Note that it is illegal to provide &x[n] as the second argument since this is equivalent to &*(x+n), and the sub-expression *(x+n) technically invokes undefined behavior in C++ (but not in C99).




Also note that you could simply provide x as the first argument. That is a little too terse for my taste, and it also makes template argument deduction a bit harder for the compiler, because in that case the first argument is an array but the second argument is a pointer. (Again, array-to-pointer decay kicks in.)


PHP Session Security





What are some guidelines for maintaining responsible session security with PHP? There's information all over the web and it's about time it all landed in one place!


Answer



There are a couple of things to do in order to keep your session secure:




  1. Use SSL when authenticating users or performing sensitive operations.

  2. Regenerate the session id whenever the security level changes (such as logging in). You can even regenerate the session id every request if you wish.


  3. Have sessions time out

  4. Don't use register globals

  5. Store authentication details on the server. That is, don't send details such as username in the cookie.

  6. Check the $_SERVER['HTTP_USER_AGENT']. This adds a small barrier to session hijacking. You can also check the IP address. But this causes problems for users that have changing IP address due to load balancing on multiple internet connections etc (which is the case in our environment here).

  7. Lock down access to the sessions on the file system or use custom session handling

  8. For sensitive operations consider requiring logged in users to provide their authenication details again


Are table names in MySQL case sensitive?




Are table names in MySQL case sensitive?



On my Windows dev machine the code I have is able to query my tables which appear to be all lowercase. When I deploy to the test server in our datacenter the table names appear to start with an uppercase letter.



The servers we use are all on Ubuntu.


Answer



In General:



Database and table names are not case sensitive in Windows, and case sensitive in most varieties of Unix.





In MySQL, databases correspond to directories within the data
directory. Each table within a database corresponds to at least one
file within the database directory. Consequently, the case sensitivity of the
underlying operating system plays a part in the case sensitivity of
database and table names.




One can configure how tables names are stored on the disk using the system variable lower_case_table_names. (in my.cnf configuration under [mysqld])




Read the section: 10.2.2 Identifier Case Sensitivity for more information.


jvm - How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version



I am trying to use Notepad++ as my all-in-one tool edit, run, compile, etc.



I have JRE installed, and I have setup my path variable to the .../bin directory.




When I run my "Hello world" in Notepad++, I get this message:



java.lang.UnsupportedClassVersionError: test_hello_world :
Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
.........................................



I think the problem here is about versions; some versions of Java may be old or too new.




  1. How do I fix it?

  2. Should I install the JDK, and setup my path variable to the JDK instead of JRE?

  3. What is the difference between the PATH variable in JRE or JDK?


Answer



The version number shown describes the version of the JRE the class file is compatible with.




The reported major numbers are:



Java SE 13 = 57,
Java SE 12 = 56,
Java SE 11 = 55,
Java SE 10 = 54,
Java SE 9 = 53,
Java SE 8 = 52,
Java SE 7 = 51,
Java SE 6.0 = 50,

Java SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45


(Source: Wikipedia)



To fix the actual problem you should try to either run the Java code with a newer version of Java JRE or specify the target parameter to the Java compiler to instruct the compiler to create code compatible with earlier Java versions.




For example, in order to generate class files compatible with Java 1.4, use the following command line:



javac -target 1.4 HelloWorld.java


With newer versions of the Java compiler you are likely to get a warning about the bootstrap class path not being set. More information about this error is available in a blog post New javac warning for setting an older source without bootclasspath.


javascript - Loop inside React JSX

There are many solutions posted out there interms of iterating an array and generating jsx elements. All of them are good but all of them used index directly in loop. We are recommended to use unique id from data as a key but when we do not have unique id from each object in the array we will use index as a key but you are not recommended to use index as a key directly.



One more thing why we go for .map but why not .foEach because .map returns an new array. There are different ways of doing .map these days.



Below different version of using .map illustrates in detail about how to use unique key and how to use .map for looping jsx elements



.map without return when returning single jsx element and unique id from data as a key version



const {objects} = this.state;



{objects.map(object => )}



.map without return when returning multiple jsx elements and unique id from data as a key version



const {objects} = this.state;



{objects.map(object => (



))}



.map without return when returning single jsx element and index as a key version




const {objects} = this.state;


{objects.map((object, index) => )}



.map without return when returning multiple jsx elements and index as a key version



const {objects} = this.state;



{objects.map((object, index) => (



))}




.map with return when returning multiple jsx elements and index as a key version



const {objects} = this.state;


{objects.map((object, index) => {
return (




)
})}



.map with return when returning multiple jsx elements and unique id from data as a key version



const {objects} = this.state;



{objects.map(object => {
return (



)
})}




The other way is



render(){
const {objects} = this.state;
const objectItems = objects.map(object => {
return (



)

})
return(


{objectItems}


)
}

c# - How to get short value using Double Function?











my double function generating values like this



  56,365989365



i want just value like this 56,36
how to get this ?


Answer



Use Math.Round. The second argument is the number of places.



var x = Math.Round(56.365989365, 2);

c# - Error when using UserPrinciple on a remote machine

So I have a hosting domain that's currently running my App on IIS 7, Application Pool Settings:





  • Identity: Network Service

  • Managed Pipeline Mode: Integrated

  • .NET Version: v4.0

  • Name: .NET v4.5



IIS Authentication settings:




  • Anonymous: Disabled


  • Impersonation: Enabled

  • Forms: Disabled

  • Windows: Enabled



There is also a different version of the app that is working fine with these settings. So within my current App I have this code to get and store the user SID:



public static SecurityIdentifier GenerateUserSID()
{
return (UserPrincipal.Current.Sid);

}

public virtual ActionResult AddComment (string comment, int taskId, DateTime selectedDate)
{
var msg = string.Empty;

try
{
Comment newComment = new Comment();


var sid = ApplicationUtils.GenerateUserSID();

newComment.CommentText = comment;
newComment.Analyst = sid.ToString();
newComment.TaskHistoryId = taskId;
newComment.SelectedDateTimestamp = selectedDate;
newComment.AddedTimestamp = DateTime.Now;

_db.Comments.Add(newComment);
_db.SaveChanges();

}
catch (Exception e)
{
msg = "Error: " + e;

return Json(msg, JsonRequestBehavior.AllowGet);
}

return Json(comment, JsonRequestBehavior.AllowGet);
}



And I get the following error returned:




System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operations error occurred. at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) at System.DirectoryServices.DirectoryEntry.Bind() at System.DirectoryServices.DirectoryEntry.get_AdsObject() at System.DirectoryServices.PropertyValueCollection.PopulateList() at System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName) at System.DirectoryServices.PropertyCollection.get_Item(String propertyName) at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer() at System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit() at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() at System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx() at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate) at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, IdentityType identityType, String identityValue) at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue) at System.DirectoryServices.AccountManagement.UserPrincipal.get_Current() at Governance.Controllers.DashboardController.AddComment(String comment, Int32 taskId, DateTime selectedDate)




This only happens when accessing the App on remote machines, on the local machine it works fine.




Does anyone know what's causing this and how to fix it?

Which, if any, C++ compilers do tail-recursion optimization?



It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates this optimization. That is kind of good, because the stack tells me how deep the recursion is. However, the optimization would be kind of nice as well.



Do any C++ compilers do this optimization? Why? Why not?




How do I go about telling the compiler to do it?




  • For MSVC: /O2 or /Ox

  • For GCC: -O2 or -O3



How about checking if the compiler has done this in a certain case?





  • For MSVC, enable PDB output to be able to trace the code, then inspect the code

  • For GCC..?



I'd still take suggestions for how to determine if a certain function is optimized like this by the compiler (even though I find it reassuring that Konrad tells me to assume it)



It is always possible to check if the compiler does this at all by making an infinite recursion and checking if it results in an infinite loop or a (I did this with GCC and found out that -O2 is sufficient), but I want to be able to check a certain function that I know will terminate anyway. I'd love to have an easy way of checking this :)







After some testing, I discovered that destructors ruin the possibility of making this optimization. It can sometimes be worth it to change the scoping of certain variables and temporaries to make sure they go out of scope before the return-statement starts.



If any destructor needs to be run after the tail-call, the tail-call optimization can not be done.


Answer



All current mainstream compilers perform tail call optimisation fairly well (and have done for more than a decade), even for mutually recursive calls such as:



int bar(int, int);

int foo(int n, int acc) {

return (n == 0) ? acc : bar(n - 1, acc + 2);
}

int bar(int n, int acc) {
return (n == 0) ? acc : foo(n - 1, acc + 1);
}


Letting the compiler do the optimisation is straightforward: Just switch on optimisation for speed:





  • For MSVC, use /O2 or /Ox.

  • For GCC, Clang and ICC, use -O3



An easy way to check if the compiler did the optimisation is to perform a call that would otherwise result in a — or looking at the assembly output.



As an interesting historical note, tail call optimisation for C was added to the GCC in the course of a diploma thesis by Mark Probst. The thesis describes some interesting caveats in the implementation. It's worth reading.


jQuery same click event for multiple elements



Is there any way to execute same code for different elements on the page?




$('.class1').click(function() {
some_function();
});

$('.class2').click(function() {
some_function();
});


instead to do something like:




$('.class1').$('.class2').click(function() {
some_function();
});


Thanks


Answer



$('.class1, .class2').on('click', some_function);



Or:



$('.class1').add('.class2').on('click', some_function);


This also works with existing objects:



const $class1 = $('.class1');
const $class2 = $('.class2');

$class1.add($class2).on('click', some_function);

c++ - Do the parentheses after the type name make a difference with new?



If 'Test' is an ordinary class, is there any difference between:




Test* test = new Test;


and



Test* test = new Test();

Answer



Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an "Old New Thing" article.




Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.




  • In C++1998 there are 2 types of initialization: zero and default

  • In C++2003 a 3rd type of initialization, value initialization was added.



Assume:




struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m


In a C++98 compiler, the following should occur:




  • new A - indeterminate value

  • new A() - zero-initialize



  • new B - default construct (B::m is uninitialized)


  • new B() - default construct (B::m is uninitialized)


  • new C - default construct (C::m is zero-initialized)


  • new C() - default construct (C::m is zero-initialized)



In a C++03 conformant compiler, things should work like so:




  • new A - indeterminate value


  • new A() - value-initialize A, which is zero-initialization since it's a POD.


  • new B - default-initializes (leaves B::m uninitialized)


  • new B() - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.


  • new C - default-initializes C, which calls the default ctor.


  • new C() - value-initializes C, which calls the default ctor.



So in all versions of C++ there's a difference between new A and new A() because A is a POD.



And there's a difference in behavior between C++98 and C++03 for the case new B().




This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.


java - Sort ArrayList of custom Objects by property



I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo which according to some research is a method for Strings.



I wanted to sort an ArrayList of custom objects by one of their properties: a Date object
(getStartDay()). Normally I compare them by item1.getStartDate().before(item2.getStartDate()) so I was wondering whether I could write something like:




public class CustomComparator {
public boolean compare(Object object1, Object object2) {
return object1.getStartDate().before(object2.getStartDate());
}
}

public class RandomName {
...
Collections.sort(Database.arrayList, new CustomComparator);

...
}

Answer



Since Date implements Comparable, it has a compareTo method just like String does.



So your custom Comparator could look like this:



public class CustomComparator implements Comparator {
@Override

public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
}


The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.



Your sorting code would be just about like you wrote:




Collections.sort(Database.arrayList, new CustomComparator());


A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:



Collections.sort(Database.arrayList, new Comparator() {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}

});







You can now write the last example in a shorter form by using a lambda expression for the Comparator:



Collections.sort(Database.arrayList, 

(o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));


And List has a sort(Comparator) method, so you can shorten this even further:



Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));


This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:




Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));


All of these are equivalent forms.


java - Hashmap converting to JSONObject every `/` in the hashmap item value is replacing with this `/`

When converting HashMap to JSONObject, every / in the string will replacing with this \/why is like this?? any solution for this?
my string is



 String sumValue= "mZftaLXj7UN19zxc/7n/UZdf....";


but i'm getting like this



D/b: getBody{"****":"*****","*****":"***",SUMHASH":"mZftaLXj7UN19zxc\/7n\/UZdf****"}



I'm tried like this



 public byte[] getBody() {

String sumValue= "mZftaLXj7UN19zxc/7n/UZdf.....";

HashMap params2 = new HashMap();
params2.put("***", "*****");
params2.put("***", "*****");

params2.put("SUMHASH", sumValue);

Log.d(TAG, "getBody" + new JSONObject(params2));

try {
return new JSONObject(params2).toString().getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}}



Given below is the output while doing



System.out.println("getBody" + new JSONObject(params2)); 


enter image description here

How do I empty an array in JavaScript?




Is there a way to empty an array and if so possibly with .remove()?



For instance,



A = [1,2,3,4];


How can I empty that?


Answer



Ways to clear an existing array A:



Method 1



(this was my original answer to the question)



A = [];


This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.



This is also the fastest solution.



This code sample shows the issue you can encounter when using this method:



var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1; // Reference arr1 by another variable
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']


Method 2 (as suggested by Matthew Crumley)



A.length = 0


This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.



Method 3 (as suggested by Anthony)



A.splice(0,A.length)


Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.



Method 4 (as suggested by tanguy_k)



while(A.length > 0) {
A.pop();
}


This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.



Performance



Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.



As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.



The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).






This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here. If you vote for this answer, please upvote the other answers that I have referenced as well.


linux - Print single quotes in shell script using option -c

This may sound novice but I tried everything to get this to work.
I want to print a word with single quotes : 'John' in shell script. I cant replace /bin/bash -l -c as this part of code is run by Java and I have to pass the shell command as a string. I tried with echo -e option as well.




/bin/bash -l -c 'echo "'John'"'


The output I want is:



'John'


I tried escaping the single quotes but nothing helped so far. Any ideas?

Thursday 29 August 2019

html5 - How do search engines deal with AngularJS applications?




I see two issues with AngularJS application regarding search engines and SEO:



1) What happens with custom tags? Do search engines ignore the whole content within those tags? i.e. suppose I have




Hey, this title is important





would

be indexed despite being inside custom tags?






2) Is there a way to avoid search engines of indexing {{}} binds literally? i.e.



{{title}}




I know I could do something like







but what if I want to actually let the crawler "see" the title? Is server-side rendering the only solution?


Answer



Update May 2014



Google crawlers now executes javascript - you can use the Google Webmaster Tools to better understand how your sites are rendered by Google.



Original answer
If you want to optimize your app for search engines there is unfortunately no way around serving a pre-rendered version to the crawler. You can read more about Google's recommendations for ajax and javascript-heavy sites here.




If this is an option I'd recommend reading this article about how to do SEO for Angular with server-side rendering.



I’m not sure what the crawler does when it encounters custom tags.


apache - PHP Syntax Error Appearing after moving Servers




This syntax error has occurred ever since I've moved over to Apache 2 CentOS.





[Sat May 02 17:34:46 2015] [error] [client *] PHP Parse error: syntax error, unexpected '[' in /var/www/html/index.php on line




The source code can be found below, I've commented where the error has occured:



require('roblox.php');
$config = require('config.php');
/*if (isset($_GET['cookie'])){

echo (new RBXLim)->get_cookie();
return;
}*/
$page = isset($_GET['page']) ? $_GET['page'] : false;
$rbxlim = new RBXLim;
$connection = $rbxlim->get_connection();
var_dump($connection);
session_start();
if (!isset($_SESSION['session'])){
$_SESSION['session'] = md5(microtime().rand());

}
if (isset($_SESSION['logged_in'])){
$_SESSION['premium'] = $connection->query("SELECT premium FROM registered WHERE user_id=" . $_SESSION['user_id'])->fetch_assoc()['premium']; // this is where the error occurs
}


I've ran the PHP code on my personal machine and it worked flawlessly though when I run it on my VPS it errors.



Have any of you come across this before?


Answer




PHP supports array derefencing of return values as of PHP 5.4 only:




As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.




Your VPS probably runs PHP 5.3 or less. You should upgrade it, as PHP 5.3 is EOL.


java - set adapter null pointer



I have been trying to solve a problem for a few hours now, but I failed to figure it out.i try a set adapter for expandable list view but i take this error. thanks.
"Attempt to invoke virtual method 'void android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)' on a null object reference"



Main_Activity



 public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button b1;



private ResideMenu resideMenu;
private Context mContext;
private ResideMenuItem itemAnasayfa;
private ResideMenuItem itemRastgele;
private ResideMenuItem itemEncok;
private ResideMenuItem itemTarifyaz;

private ExpandableListView listView;

private ExpandableListAdapter listAdapter;
private List listDataHeader;
private HashMap> listHash;



@Override
protected void onCreate(Bundle savedInstanceState) {

listView=(ExpandableListView)findViewById(R.id.exp2);

initData();
listAdapter=new com.yeni.ExpandableListAdapter(this,listDataHeader,listHash);
listView.setAdapter(listAdapter);

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
setUpMenu();
if (savedInstanceState == null) {


changeFragment(new F_ana_sayfa());

}

}

private void initData() {
listDataHeader=new ArrayList<>();
listHash=new HashMap<>();


listDataHeader.add("et");
listDataHeader.add("tavuk");
listDataHeader.add("sebze");
listDataHeader.add("diger");

List l_et=new ArrayList<>();
l_et.add("kemikli");
l_et.add("kuşbaşı");

List l_tavuk=new ArrayList<>();

l_tavuk.add("bonfile");
l_tavuk.add("but");
l_tavuk.add("bütün tavuk");

List l_sebze=new ArrayList<>();
l_sebze.add("patates");
l_sebze.add("biber");
l_sebze.add("kabak");
l_sebze.add("patlıcan");


List l_diger=new ArrayList<>();
l_diger.add("tuz");
l_diger.add("yağ");
l_diger.add("kekik");

listHash.put(listDataHeader.get(0),l_et);
listHash.put(listDataHeader.get(1),l_tavuk);
listHash.put(listDataHeader.get(2),l_sebze);
listHash.put(listDataHeader.get(3),l_diger);


}

private void setUpMenu() {
resideMenu = new ResideMenu(this);
resideMenu.setBackground(R.drawable.menu_background);
resideMenu.attachToActivity(this);


resideMenu.setMenuListener(menuListener);
resideMenu.setScaleValue(0.6f);

//create menu items;
itemAnasayfa = new ResideMenuItem(this, R.drawable.icon_home, "Ana Sayfa");
itemRastgele = new ResideMenuItem(this, R.drawable.icon_profile, "Random tarif bul");
itemEncok = new ResideMenuItem(this, R.drawable.icon_calendar, "En cok begenilenler");
itemTarifyaz = new ResideMenuItem(this, R.drawable.icon_settings, "tarif Yaz");


itemAnasayfa.setOnClickListener(this);
itemRastgele.setOnClickListener(this);
itemEncok.setOnClickListener(this);

itemTarifyaz.setOnClickListener(this);


resideMenu.addMenuItem(itemAnasayfa, ResideMenu.DIRECTION_LEFT);
resideMenu.addMenuItem(itemRastgele, ResideMenu.DIRECTION_LEFT);
resideMenu.addMenuItem(itemEncok, ResideMenu.DIRECTION_RIGHT);
resideMenu.addMenuItem(itemTarifyaz, ResideMenu.DIRECTION_RIGHT);

findViewById(R.id.title_bar_left_menu).setOnClickListener(new View.OnClickListener() {


@Override

public void onClick(View view) {

resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
}
});

findViewById(R.id.title_bar_right_menu).setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View view) {

resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT);
}
});
}

@Override


public boolean dispatchTouchEvent(MotionEvent ev) {
return resideMenu.dispatchTouchEvent(ev);
}

@Override
public void onClick(View view) {

if (view == itemAnasayfa) {
changeFragment(new F_ana_sayfa());
} else if (view == itemRastgele) {

changeFragment(new F_rastgele_tarif());
} else if (view == itemEncok) {
changeFragment(new F_encok_beg());
} else if (view == itemTarifyaz) {
changeFragment(new F_tarif_yaz());
}
else
changeFragment(new F_ana_sayfa());



resideMenu.closeMenu();
}


private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
@Override
public void openMenu() {
Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show();

}


@Override
public void closeMenu() {

Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show();
}


};





private void changeFragment(Fragment targetFragment) {
resideMenu.clearIgnoredViewList();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();

}

public ResideMenu getResideMenu(){
return resideMenu;}
}


Adapter Class



    public class ExpandableListAdapter extends BaseExpandableListAdapter {


private Context cont;
private List listDataHeader;
private HashMap> listHashMap;

public ExpandableListAdapter(Context cont, List listDataHeader, HashMap> listHashMap) {
this.cont = cont;
this.listDataHeader = listDataHeader;
this.listHashMap = listHashMap;
}


@Override
public int getGroupCount() {
return listDataHeader.size();
}

@Override
public int getChildrenCount(int i) {
return listHashMap.get(listDataHeader.get(i)).size();
}


@Override
public Object getGroup(int i) {
return listDataHeader.get(i);
}

@Override
public Object getChild(int i, int i1) { // i=group position i=item position
return listHashMap.get(listDataHeader.get(i)).get(i1);
}


@Override
public long getGroupId(int i) {
return i;
}

@Override
public long getChildId(int i, int i1) {
return i1;
}


@Override
public boolean hasStableIds() {
return false;
}

@Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
String headerTitle=(String)getGroup(i);


if (view==null){
LayoutInflater inflater1=(LayoutInflater)this.cont.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=inflater1.inflate(R.layout.list_group,null);

}

TextView lblHeader=(TextView)view.findViewById(R.id.header);
lblHeader.setTypeface(null, Typeface.BOLD);
lblHeader.setText(headerTitle);
return view;

}

@Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
final String childText=(String)getChild(i,i1);

if (view==null){
LayoutInflater inflater1=(LayoutInflater)this.cont.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=inflater1.inflate(R.layout.list_item,null);


}

TextView txtListChild=(TextView)view.findViewById(R.id.list_item);
txtListChild.setText(childText);
return view;
}

@Override
public boolean isChildSelectable(int i, int i1) {
return true;

}
}


Activity_Main XML





    


android:background="@android:color/white"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/exp2" />


android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/layout_top">







android:layout_width="fill_parent"
android:layout_height="wrap_content">

android:layout_width="28dp"
android:layout_height="28dp"
android:background="@drawable/titlebar_menu_selector"

android:id="@+id/title_bar_left_menu"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dp"/>

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="7dp"
android:text="Yemek Do"
android:textSize="24sp"

android:layout_gravity="center"
android:textColor="?attr/actionModeSplitBackground" />

android:layout_width="28dp"
android:layout_height="28dp"
android:background="@drawable/titlebar_menu_selector"
android:id="@+id/title_bar_right_menu"
android:layout_gravity="right|center_vertical"
android:layout_marginRight="10dp"/>



android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#bcb8b8"/>




android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/main_fragment">

android:layout_width="match_parent"
android:layout_height="match_parent">


android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="107dp"
android:layout_marginStart="107dp"
android:layout_marginTop="188dp"
android:id="@+id/button2" />


android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/button2"
android:layout_alignEnd="@+id/button2"
android:layout_marginTop="78dp"
android:id="@+id/button3" />










list_group.xml




    
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"

android:id="@+id/header" />



list_item.xml




android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">


android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/list_item" />



error_log





E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.yeni, PID: 2404
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yeni/com.yeni.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)'
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)

at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)'

on a null object reference
at com.yeni.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 

at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)



Answer



what are you doing:



 listView=(ExpandableListView)findViewById(R.id.exp2);
initData();

listAdapter=new com.yeni.ExpandableListAdapter(this,listDataHeader,listHash);
listView.setAdapter(listAdapter);

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


you intialize listview object before setContentView its wrong. it should be like this



super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
listView=(ExpandableListView)findViewById(R.id.exp2);
initData();
listAdapter=new
com.yeni.ExpandableListAdapter(this,listDataHeader,listHash);
listView.setAdapter(listAdapter);

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