Saturday, August 31, 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)


Unlocking bitlocker from my hard drive

I was using my hard drive to copy some movies from a friend's laptop. When I inserted the hard drive in my laptop, a prompt message will say that the device is bitlocker protected. I have no idea what bitlocker was. I don't even know why it prompted. I did not even purchase bitlocker.



My problem now is how to unlock it. I have the key as it is shown in that prompt message but I do not know where to get my password. Its not even in my control panel system.




How can I remove the bitlocker from my hard drive? I cannot access my files. All my back up files are there. I hope someone can help me on this. I'm not exactly technology savvy especially when it comes to this kind of software. I hope someone can enlighten me on this one.

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


How to prevent an SSD from disappearing from BIOS

I've only recently upgraded my old machine to a new one with a brand new 60gb SSD as my boot drive and a 1TB main drive.



Paranoid about completely breaking my SSD, I read up on a lot of issues that I needed to watch out for, including making sure AHCI was turned on and trim enabled.



PC has been working fine for a few weeks now, until today. My wife was watching some TV on the machine when it started to act strange and eventually blue screened.



She rebooted and the boot mgr was missing. When I got home from work I checked the BIOS and the drive had disappeared. I panicked and looked up some possible fixes, and I discovered a large amount of people having problems with the drive firmware, especially on OCZ Vertex and Agility drives, and my drive is an Agility 3 drive.




The problems included blue screens followed by missing drives, and a solution was to reset the CMOS and try again. This worked, and now everything seems to be working fine.



My question is, is there any way to prevent this from happening? Am I missing a setting for my SSD? All of the posts I found were from early to mid-2011 nothing for the end of 2011 to 2012. So I am wondering if I've missed anything.



EDIT: Checked my drives firmware and it is 2.15, which has had issues reported by users.

windows 8.1 - Can dism /restorehealth be used to restore from a mounted 8.1 ISO?


On my x64 Lenovo z580 laptop with Windows 8.1 x64, I was trying to install KB2919355 when I encountered the error 80073712 which translates to component store corruption.


Since then, I have run the following commands copied here with results:




  1. sfc /scannow - result: no integrity violation

  2. dism /online /cleanup-image /checkhealth - component store is repairable

  3. dism /online /cleanup-image /scanhealth - component store is repairable

  4. dism /online /cleanup-image /analyzecomponentstore component store cleanup recommended: Yes

  5. dism /online /cleanup-image /restorehealth dism failed to perform any operation. Either the source is invalid or componentstore is not
    repairable Error code: 800f081f



Previously, I had upgraded to 8.1 using Windows Update. Now, I have downloaded the 8.1 ISO from here


Question: If I mount the 8.1 ISO to drive H:, Can I use the dism /online /cleanup-image /restorehealth /source:H:\sources\sxs /LimitAccess to repair my componentstore?


Answer



That error message is due to an issue with Windows Update. The DISM /online command uses Windows Update for it's file source. The article for KB 957310 should help you to resolve that error message, and then the DISM /online command should work fine once again.


Hope this helps,


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

linux - grep with regex containing pipe character



I am trying to grep with regex that contains pipe character |. However, It doesn't work as expected. The regex does not match the | inclusively as seen in the attach image below.



enter image description here




this is my bash command



cat data | grep "{{flag\|[a-z|A-Z\s]+}}"



the sample data are the following



| 155||NA||{{flag|Central African Republic}}||2.693||NA||0.000||0.000||0.019||0.271||0.281||0.057||2.066
|{{flagicon|Kosovo}} ''[[Kosovo]]'' {{Kosovo-note}}
|{{flagicon|Somaliland}} [[Somaliland|Somaliland region]]
|{{flagicon|Palestine}} ''[[Palestinian Territories]]''{{refn|See the following on statehood criteria:



the expected output is



| 155||NA||{{flag|Central African Republic}}||2.693||NA||0.000||0.000||0.019||0.271||0.281||0.057||2.066


However, having tested it with Regex101.com, the result came out as expected.


Answer



It appears that grep accepts \| as a separator between alternative search expressions (like | in egrep, where \| matches a literal |).




Apart from that, your expression has other problems:-




  • + is supported in egrep (or grep -E) only.

  • \s is not supported within a [] character group.

  • I don't see the need for | in the character group.



So the following works for grep:-




grep "{{flag|[a-zA-Z ][a-zA-Z ]*}}" 


Or (thanks to Glenn Jackman's input):-



grep "{{flag|[a-zA-Z ]\+}}" 


In egrep the {} characters have special significance, so they need to be escaped:-




egrep "\{\{flag\|[a-zA-Z ]+\}\}" 


Note that I have removed the unnecessary use of cat.


linux - Maxiumum recovery of data from old floppy discs with padded bad sectors and multiple passes


I've a collection of old 3.5" floppy disks that I'm looking to recover as much data as possible from.


The issue is due to the structure of some of the files, I need the length of all the files to be maintained meaning any bad sectors should be padded (the tl;dr reason why is some files are Acorn ADFS files where data and code are combined. The code references the data as an offset from the start of the file. Reading ADFS format isn't an issue in linux, the padding of bad sectors is).


The discs haven't been read in 25 years so I'm expecting unpredictable reading, regular bad sectors and potentially rendering the disks unreadable - which I don't mind as long as data recovery is maximised.


To do this I'm expecting multiple passes to be needed to read as much as possible.


dd


I looked at dd, with this command promising for a first run:


dd if=/dev/fd0 of=adfs.img conv=noerror,sync

Followed by subsequent calls of


dd if=/dev/fd0 of=adfs.img conv=noerror,notrunc

Where:


noerror means errors are ignored


sync means bad sectors are padded with the null character


notrunc means the (already existing) output file is not truncated when dd is called.


However, as I read the man page and this explanation of notrunc, despite notrunc being set, dd overwrites the output each time resulting in output that still only represents what was read with the last pass. Any sectors previously read correctly but now bad eg due to degrading old floppy disk, will be overwritten with null.


So dd doesn't look suitable.


ddrescue


ddrescue looks promising in that it can be used with multiple passes as long as a logfile is used to record what was successfully written and then referred to when the next pass is done.


The first pass to only read non-error blocks


ddrescue -d -p --no-split /dev/fd0 output.img log/output.logfile

for the first pass and subsequent passes of to fill in the errors


ddrescue -d -r3 /dev/fd0 output.img log/output.logfile

Where


-d direct disk access. Ignore system cache


--no-split or -n do not try to split or retry failed blocks ie only read good blocks. This is to only get good data in the first run to avoid the disk failing while trying to recover bad blocks.


-p preallocate preallocates disk space before recovery ie the output file will be the same size as input file/device


-r3 retry bad sectors 3 times (used on 2nd pass onward)


but the gotcha is ddrescue seems not to pad bad sectors as they occur. With -p set, it seems to result in all the padding at the end of the file, not maintaining the offsets of data from the start of the file as required.


This seems to be the case as ddrescue is written to try hard to save disk space so bad sectors are truncated, then added to if the bad sectors are successfully read in subsequent passes. Setting -p just creates an output file the same size as the input file to save the space, not to pad the data. The contents of the output with -p set or unset will therefore be identical ie not padded until the end of the file.


Question


So my question is a three parter


1) is it correct that ddrescue does NOT pad the recovered file even with -p set?


2) Is there any way to get it to pad? In my internet searching, I read a comment (will find it again and add) that the log file created by ddrescue could be used by a script to pad the relevant places. Any idea how?


and


3) do you know any better command / program / script to do what I'm trying to do - maximum data recovery via multiple passes of reading a corrupt disk with padding of bad sectors?


I'm using Ubuntu 18.04, dd version is (coreutils) 8.28 and GNU ddrescue version is 1.22, both from the Ubuntu repositories.


Thanks as always for any help


Answer



GNU ddrescue is the right tool for the recovery you are attempting.





1) is it correct that ddrescue does NOT pad the recovered file even with -p set?



This presumption is incorrect. You might be confused by the manual saying this:



Ddrescue does not write zeros to the output when it finds bad sectors in the input, and does not truncate the output file if not asked to.



It just means that zeros aren't written in place of bad sectors. Whatever should be at those bad sectors just isn't filled in. If you're writing to a blank disk or a file, the unwritten areas at the destination will read back as zeros (null bytes).


Also, the -p/--preallocate option does not have anything to do with "padding". It means "preallocate". On supported file systems, the option ensures that you have enough disk space on the destination to store the source disk.





2) Is there any way to get it to pad?



The file output by GNU ddrescue is logically the same layout as the source disk. A block read from the source goes in the same position in the destination. You could even reverse the whole recovery (-R/--reverse) and the blocks will be filled in backwards, still in the right places.





3) do you know any better command / program / script to do what I'm trying to do - maximum data recovery via multiple passes of reading a corrupt disk with padding of bad sectors?



GNU ddrescue does exactly what you want. It can do multiple passes (-r/--retry-passes=n), and the desired "padding" of bad sectors is the default behavior of GNU ddrescue. From the manual:



If the output file is a regular file created by ddrescue, the areas marked as bad-sector will contain zeros.



To be perfectly clear and to address your concern that a successful read followed by a bad read would become "padded" with null, ddrescue will not try to re-read a successful read―there is no need to because the data has already been recovered. The mapfile is how ddrescue knows what it already recovered and failed to recover.


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?

worksheet function - Excel Convert the correct Date type


I'm currently following the date type dd/mm/yyyy i need to have another row showing the month in mmm type. E.g. From 13/09/2014 to SEP


My formula is =Text(A2, "mmm") which is the correct formula,


However it reads the text as mm/dd/yyyy thus having an error. How do I tell the excel to read it in dd/mm/yyyy format.


The format of the dd/mm/yyyy field is General - No specific format


Answer



If you want it to apply for just this Excel formula, Overmind's answer covers how. If you want it to apply always to everything, you have to change the system's date format.


Note that this will change every date displayed that uses system settings as well as changing how you must type in dates. For instance, if you change the system short date format to d/M/yyyy and then type 9/13 into Excel, it'll assume you meant September 1, 2013, because 13 doesn't make sense as a month so it must be a year and that means that 9 must be the month.


Here are the screenshots showing how to change the system's time format on Windows 7.


Right-click on the time in the system tray and click Adjust date/time


Screenshot 1


Click on Change date and time...


Screenshot 2


Click on Change calendar settings


Screenshot 3


Change the format as desired and click OK


Screenshot 4


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

macos - Root directory permissions on Mac OS X 10.6?


I was wondering if it's normal that the root directory / should be owned by “root”.
I get asked for my password every time I want to do something there (e.g. save a file, create a directory) and I don't remember this happening before (though this may just be my faulty memory).
Here's the relevant terminal output:


MacBook:~ ago$ ls -lah /
total 37311
drwxr-xr-x@ 35 root staff 1,2K 22 Mar 12:34 .
drwxr-xr-x@ 35 root staff 1,2K 22 Mar 12:34 ..
-rw-rw-r--@ 1 root admin 21K 22 Mar 10:21 .DS_Store
drwx------ 3 root admin 102B 28 Feb 2008 .Spotlight-V100
d-wx-wx-wt 2 root admin 68B 31 Ago 2009 .Trashes
-rw-r--r--@ 1 ago 501 45K 23 Gen 2008 .VolumeIcon.icns
srwxrwxrwx 1 root staff 0B 22 Mar 12:34 .dbfseventsd
---------- 1 root admin 0B 23 Giu 2009 .file
drwx------ 27 root admin 918B 22 Mar 10:55 .fseventsd
-rw-r--r--@ 1 ago admin 59B 30 Ott 2007 .hidden
-rw------- 1 root wheel 320K 30 Nov 11:42 .hotfiles.btree
drwxr-xr-x@ 2 root wheel 68B 18 Mag 2009 .vol
drwxrwxr-x+ 276 root admin 9,2K 19 Mar 18:28 Applications
drwxrwxr-x@ 21 root admin 714B 14 Nov 12:01 Developer
drwxrwxr-t+ 74 root admin 2,5K 18 Dic 22:14 Library
drwxr-xr-x@ 2 root wheel 68B 23 Giu 2009 Network
drwxr-xr-x 4 root wheel 136B 13 Nov 17:49 System
drwxr-xr-x 6 root admin 204B 31 Ago 2009 Users
drwxrwxrwt@ 4 root admin 136B 22 Mar 12:35 Volumes
drwxr-xr-x@ 39 root wheel 1,3K 13 Nov 17:44 bin
drwxrwxr-t@ 2 root admin 68B 23 Giu 2009 cores
dr-xr-xr-x 3 root wheel 5,1K 17 Mar 11:29 dev
lrwxr-xr-x@ 1 root wheel 11B 31 Ago 2009 etc -> private/etc
dr-xr-xr-x 2 root wheel 1B 17 Mar 11:30 home
drwxrwxrwt@ 3 root wheel 102B 31 Ago 2009 lost+found
-rw-r--r--@ 1 root wheel 18M 3 Nov 19:40 mach_kernel
dr-xr-xr-x 2 root wheel 1B 17 Mar 11:30 net
drwxr-xr-x@ 3 root admin 102B 24 Nov 2007 opt
drwxr-xr-x@ 6 root wheel 204B 31 Ago 2009 private
drwxr-xr-x@ 64 root wheel 2,1K 13 Nov 17:44 sbin
lrwxr-xr-x@ 1 root wheel 11B 31 Ago 2009 tmp -> private/tmp
drwxr-xr-x@ 17 root wheel 578B 12 Set 2009 usr
lrwxr-xr-x@ 1 root wheel 11B 31 Ago 2009 var -> private/var

Are these ownerships / permissions ok? Should I chmod/chown something?


Answer



I just checked a couple of relatively clean OS X 10.6 Macs, and while / is owned by root, its group and permissions are different from what you have: it's assigned to the admin group, and has group write and the sticky bit set, and doesn't have an extended attributes (i.e. drwxrwxr-t 29 root admin). Disk Utility's permissions repair feature doesn't seem to reset this (I just tried), but you can fix it by hand:


sudo chgrp admin /
sudo chmod 1775 /
xattr -l /

The last command will display the extended attributes attached to the root; depending on what they are, you may want to remove them (use sudo xattr -d attrname /).


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, August 30, 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);


hard drive - How is a Usb Y cable designed?


Ok,
Recently I have purchased this USB Y cable from Amazon.


Storite USB 2.0 Type A Male to Dual USB A Male Y Splitter Cable Cord Black -50cm


y-cable


I purchased it so I can use it with external hard disk to my 10 year old PC which wasn't able to provide enough USB power to the disk. After getting the cable, I connected it to PC and found it didn't provide enough USB power still.


Then I tried to check the cable with laptop. This laptop is a newer one and one USB port is always enough to run the disk as always (Generally I use USB male to male cable type A to connect this disk to laptop and it works fine).


So, to check the cable..



  1. First, I connected two male plug ends to laptop and third male plug to disk, it works fine.

  2. Second, I connected one usb plug to laptop (the one continuous with thick cable in pic) and other end to disk and it runs fine.

  3. Third, I connected the alternate usb plug to laptop (the one with thin wire in pic) and other end to disk, and now neither the disk rotates nor usb is detected, but disk shows led on which means power connection is active I guess..


From the second test, it is clear that the two male plugs (attached with thick cable in pic) carry both power supply and usb data. Whereas from the third test, it shows the male plug attached to thin cable doesn't carry enough power or usb data, or atleast this part of my cable is damaged I guess..



  • So, I would like to know how are they designed?

  • Are all the three plugs meant to be connected to USB power and data?

  • Is there any way to check if the Y-cable is faulty? I only wanted to check if that cable is faulty so I can replace it if it is..


Answer



How is a USB-Y cable designed?


It is designed for devices which require more power than is available from a single USB port.



Whereas from the third test, it shows the male plug attached to thin cable doesn't carry enough power or usb data



This extra connector does not have any data lines (D-, D+); it only has the power lines (GND, VBUS).




Are all the three plugs meant to be connected to USB power and data?


Yes. The two connectors on the Y end should be connected to the PC/Laptop and the other end to your USB device.




I want to check if the cable is faulty.



First, I connected two male plug ends to laptop and third male plug to disk, it works fine.




  • That is how the cable should be used so it is not faulty


  • The other tests are using the cable in a way it is not meant to be used so the tests are meaningless.





What are the 2 different kinds of Y-Cable?




  • One male connector, two female connectors


    There are two types of the one male two female cables. One is a basic charging cable, splitting one port's
    power across two devices. The other is a specialised cable that
    somehow splits the data lines - and it's only used in very specific
    applications.


  • Two male connectors, one male or one female connector


    What happens is you have your USB cable, one side for the host and
    one for the device, but with an extra connector attached. This extra
    connector does not have any data lines (D-, D+); it only has the power
    lines (GND, VBUS). It's attached in parallel to the existing cable. In
    other words, VBUS is connected to VBUS and GND is connected to GND.




Source Can I safely connect the power-only-end of a USB-Y cable to an other power source? answer by Bob)




Power requirements



Some devices, such as high-speed external disk drives, require more
than 500 mA of current[89] and therefore may have power issues if
powered from just one USB 2.0 port: erratic function, failure to
function, or overloading/damaging the port.


Such devices may come with
an external power source or a Y-shaped cable that has two USB
connectors (one for power and data, the other for power only) to plug
into a computer. With such a cable, a device can draw power from two
USB ports simultaneously.However, USB compliance specification
states that "use of a 'Y' cable (a cable with two A-plugs) is
prohibited on any USB peripheral", meaning that "if a USB peripheral
requires more power than allowed by the USB specification to which it
is designed, then it must be self-powered."



Source USB


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


windows 7 - Does my processor support PAE?


I currently have the following system specifications:


Windows 7 64-Bit


Athlon 64 X2 (W) 4600+ 2.4 GHz


8GB of RAM


500 GB HD


I'm planning on installing Xubuntu as a dual partition along side my current windows installation. On the official Xubuntu page it says:



Your processor needs to support PAE in order to run Xubuntu.



From the microsoft website:



PAE gives 32-bit processors the ability to use more than 4 GB of
physical memory on capable versions of Windows, and is a prerequisite
for NX.



Just for clarification seeing as I have 8GB of RAM and running Windows 7 64-Bit, PAE shouldn't be an issue, correct?


Answer



Every 64-bit x86 CPU supports PAE. There is no 64-bit x86 without NX and there is no NX without PAE.


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.


multiple monitors - ATI HD5700 with HDMI, DVA and VGA & 3 displays

I have a ATI HD5700 graphics card with HDMI (could be DisplayPort too?), DVI and VGA outputs and I want to use three monitors. Currently I have one monitor working with HDMI and other one working with DVI but if I plug the third monitor to VGA, it does not work without first disabling one of the two other monitors in the ATI Catalyst Center.


How can I get the three monitors working together?

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.


hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...