Wednesday 31 October 2018

c++ - Prefix/Postfix increment operators



I'm wanting to make sure I understand pass-by-value vs pass-by-reference properly. In particular, I'm looking at the prefix/postfix versions of the increment ++ operator for an object.



Let's suppose we have the following class X:




class X{
private:
int i;
public:
X(){i=0;}
X& operator ++ (){ ++i; return *this; } //prefix increment

X operator ++ (int unused){ //postfix increment
X ret(*this);
i++;

return ret;
}

operator int(){ return i; } //int cast
};


First of all, have I implemented the prefix/postfix increment operators properly?



Second, how memory-efficient is the postfix operator, compared to the prefix operator? Specifically how many X object copies are created when each version of the operator is used?




An explanation of exactly what happens with return-by-reference vs return-by-value might help me understand.






Edit: For example, with the following code...



X a;
X b=a++;



...are a and b now aliases?


Answer



This is a correct implementation. It is typical that a postfix operator will be worse on performance because you have to create another copy before doing the increment (and this is why I've gotten in the habit of always using prefix unless I need something else).



With return-by-reference, you're returning an l-value reference to the current object. The compiler would typically implement this by returning the address of the current object. This means that returning the object is as simple as returning a number.



However, with return-by-value, a copy must be done. This means there's more information to copy over during the return (instead of just an address) as well as a copy constructor to call. This is where your performance hit comes in.



The efficiency of your implementation looks on-par with typical implementations.




EDIT:
With regards to your addendum, no, they are not aliases. You have created two separate objects. When you return by value (and when you created a new object from within the postfix increment operator) this new object is placed in a distinct memory location.



However, in the following code, a and b are aliases:



 int a = 0;
int& b = ++a;



b is an address which references a.


Regex for string not ending with given suffix



I have not been able to find a proper regex to match any string not ending with some condition. For example, I don't want to match anything ending with an a.




This matches



b
ab
1


This doesn't match



a

ba


I know the regex should be ending with $ to mark the end, though I don't know what should preceed it.



Edit: The original question doesn't seem to be a legit example for my case. So: how to handle more than one character? Say anything not ending with ab?



I've been able to fix this, using this thread:



.*(?:(?!ab).).$



Though the downside with this is, it doesn't match a string of one character.


Answer



You don't give us the language, but if your regex flavour support look behind assertion, this is what you need:



.*(?


(? is a negated lookbehind assertion that ensures, that before the end of the string (or row with m modifier), there is not the character "a".




See it here on Regexr



You can also easily extend this with other characters, since this checking for the string and isn't a character class.



.*(?


This would match anything that does not end with "ab", see it on Regexr


php - Call to a member function execute() on boolean in




My html :



 


Email :
Message :




My rent.php file :



 require_once 'login.php';

$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) {
die($conn->connect_error);
}
$query = "SET NAMES utf8";
$result = $conn->query($query);
if (!$result) {
die($conn->error);
}


$req = $conn->prepare('INSET INTO renter (email, msg_text) VALUES(?, ?)');
$req->execute(array($_POST['email'], $_POST['msg_text']));

header('Location: menu.php');


My error when I try to submit, is : Fatal error: Call to a member function execute() on boolean in C:...\rent.php on line 18



email, msg_text are in varchar type


Answer




mysqli->prepare can also return FALSE (check http://php.net/manual/en/mysqli.prepare.php) if an error occurred. Your problem is that you have INSET instead of INSERT.


SQL Server join results as comma separated list




I have a company, industry, and company_industry_map many-to-many table.



company_id | company_name
1 Goldman Sachs
2 Microsoft

industry_id | industry
4 Technology
5 Finance

6 Banking

company_id | industry_id
1 5
1 6
2 4


I'd like to write a query that joins all of the industries into a comma separated list like this:




company_id | industries
1 Finance, Banking
2 Technology


Here's my general query that I'm trying to write:



SELECT company_id, 
xxx AS industries
FROM company c,

company_industry_map m
WHERE c.company_id = m.company_id

Answer



You can use something like this in SQL Server



select co.CompanyID, AllIndustries = 
(select (cast(industry as varchar(200))+',') as [text()]
FROM company c,
company_industry_map m

WHERE c.company_id = m.company_id and c.company_id = co.company_id
order by industry_id for XML PATH(''))
from Companies co

objective c - Location Services not working in iOS 8




My app that worked fine on iOS 7 doesn't work with the iOS 8 SDK.



CLLocationManager doesn't return a location, and I don't see my app under Settings -> Location Services either. I did a Google search on the issue, but nothing came up. What could be wrong?


Answer



I ended up solving my own problem.



Apparently in iOS 8 SDK, requestAlwaysAuthorization (for background location) or requestWhenInUseAuthorization (location only when foreground) call on CLLocationManager is needed before starting location updates.



There also needs to be NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key in Info.plist with a message to be displayed in the prompt. Adding these solved my problem.




enter image description here



Hope it helps someone else.



EDIT: For more extensive information, have a look at: Core-Location-Manager-Changes-in-ios-8


jquery - JSON Javascript, parse URL

I'm new to JavaScript, and trying to get a JSON object to post on my website. However, I can't get a success response. Since I don't have a proper debugger, I don't see error messages.



This is my code so far, I've read that it could be a security problem and I should look for JSONP, but I haven't found any proper examples to understand it.



Test0






So my question is, why don't I get a response?

javascript - What are the options for (keyup) in Angular2?

The following works great when the enter key is released. What other options are available for the keyup in addition to keyup.enter?




node.js - NodeJS callback and return statement

I'm writing a Server-side application based on NodeJS.
The application listen on some TCP and UDP ports for incoming messages, when the messages arrive they are parsed and the relevant data are stored into a MySQL database. The whole thing works fine and NodeJS capability to handle parallel concurrent requests is amazing.
However reading around the feedback about NodeJS dangers I've found something that brings confusion to me: the question is about callbacks.
Imagine the code below:



function ParseMessage(payload,callback_ko,callback_ok) {
// here we evaluate the parsed_message content, err is set if parsing errors occurs
....
if(!err) {
// if there are no errors invoke the callback_ok to let the flow continue passing the parsed content
if(typeof callback_ok == 'function') {
callback_ok(parsed_message);
}
else {
// if error occurs invoke the callback_ko passing the payload to let the flow continue in another path, maybe attempt another parsing
if(typeof callback_ko =='function') {
callback_ko(payload);
}
}
return; // <---- Ensure the functions ends
}


The code if(typeof callback == 'function') is placed to avoid to call arguments passed to ParseMessage function that is not a function (in that case the ParseMessage simply must exit returning anything as result).
My doubt is about the return; statement:
I know the return statement MUST always be present (correct me if I'm wrong with that) in order to allow the async function ends properly. As we're not returning anything here (we're invoking callbacks here) we simply don't return anything on it, but I don't know if the place where return statement is written is the right one. In other words, should I place the return statement at the end of the function or should I have something like this, instead:



function ParseMessage(payload,callback_ko,callback_ok) {
// here we evaluate the parsed_message content, err is set if parsing errors occurs
....
if(!err) {
// if there are no errors invoke the callback_ok to let the flow continue passing the parsed content
if(typeof callback_ok == 'function') {
callback_ok(parsed_message);
}
return; // <---- Ensure the functions ends
else {
// if error occurs invoke the callback_ko passing the payload to let the flow continue in another path, maybe attempt another parsing
if(typeof callback_ko =='function') {
callback_ko(payload);
}
return; // <---- Ensure the functions ends
}
}


I've found that someone also suggest to write something like return callback(payload);. What's the most correct strategy?

namespaces - C++ "using std::" vs calling std:: every time








Let's say I'm using #include in C++ and I'm making a print statement. I can choose either to:



using namespace std;
[...]
cout << "Hello" << endl;


or




using std::cout;
using std::endl;
[...]
cout << "Hello" << endl;


or



std::cout << "Hello" << std::endl;



I'm led to believe, and perhaps this is incorrect, that the first one is somewhat to be avoided, as it can add a lot of unnecessary bloat to your program. However, I don't know if there's any difference between the second and third styles in terms of performance. The majority of code that I see that uses libraries tends to use the third style; however for me if there's no tradeoff in using the second one, it seems like the cleanest and most readable method, especially if you're making a lot of calls to the functions or objects in question.



Can anyone enlighten me?

php - direct double quoted text can be inserted into sql database, but single quote to double quote converted string is inserted as empty into the database?



I have a textbox where i can type double quoted words like: hello i am "steve" and i can successfully insert the string into my database after mysqli_real_escape_string







php below:



$text_data = $_POST['description']; // hello my name is "steve" 
$final_text = mysqli_real_escape_string($this->conn,$text_data);

// the above without removing double quotes can be inserted into the db


but if it is single quotes and I convert to double quotes then it cannot be inserted.

$text_data = $_POST['description']; // hello my name is 'steve'
$final_text = str_replace("'",'"',$text_data);
$final_text = mysqli_real_escape_string($this->conn,$text_data);


so my questions are:





  1. how come it works with double quotes? doesn't it needs to be removed or replaced with "/ something?


  2. if the first case: double quotes work fine, then how come the second case when converted from single to double quotes cannot be inserted into the db?




Thanks a lot in advance


Answer



A couple things..



First I would do some reading on the differences between the single quote and the double quote's behaviors. Just so going forward you have a basis for the differences between the two.




Secondly lets look at the logic of your code:



If I replace the single quotes in your code like your code suggest your statement will look like this:



"hello my name is "steve""


No lets look closly at what happens between " and steve.



"hello my name is "  steve ""



The reason your query is failing, I believe is because steve is not quoted anymore.



Using prepared statement is really your best solution to the problem.



Hope that helps



UPDATED:




$text_data = "hello my name is 'steve'"; 
$final_text = str_replace("'",'\"',$text_data);

How do I parse XML with attribute in python?




I have an xml which has many number of rows. For a particular given attribute id, the element name and price value should be queried. For instance, my tree looks like:





Pesto Chicken Sandwich
$7.50



Chipotle Chicken Pizza
$12.00


Burrito
$6.20





How can I get the name and price value of an particular id(1 or 2 or 3)?



I tried minidom for parsing. My code is:



from xml.dom import minidom
xmldoc = minidom.parse('D:/test.xml')
nodes = xmldoc.getElementsByTagName('food')
for node in nodes:
if node.attributes['id'].value == '1':

????????????????????


And am unable to retrieve the name and price tag value. I checked lot of examples and none satisfied.



It Worked. Code is as follows:



import xml.etree.ElementTree as ET
tree = ET.parse('D:/test.xml')
root = tree.getroot()

for child in root:
testing = child.get('id')
if testing == '3':
print child.tag, child.attrib
print child.find('name').text
print child.find('price').text

Answer



Check out the standard etree library. It allows you to parse an xml file into a Python object called an ElementTree. You can then call various methods on this object, such as .findall("./food/name").




This might get you started:



import xml.etree.ElementTree as ET
tree = ET.parse('D:/test.xml')
root = tree.getroot()

def get_info(food_id):
for child in root.findall("*[@id='{0}']//".format(food_id)):
print(child.text)


get_info(1)


output:



Pesto Chicken Sandwich
$7.50

javascript - Developing an AngularJS app with dynamic set of modules



I have an application with a complex layout where the user could put (drag/drop) widgets (by choosing from a predefined set of 100+ widgets) where every widget is a custom implementation that displays a set of data (fetched using REST call) in a specific way. I've read tons of blog posts, stackoverflow questions and the official AngularJS docs but I cannot figure out how should I design my application to handle there requirements. Looking at demo apps, there is a single module (ng-app) and when constructing it in the .js file the dependent modules are declared as its dependencies, however i have a big set of widgets and somehow it's not advisable to describe them all there. I need suggession for the following questions:




  • How should I design my app and widgets - should i have a separate AngularJS module or each widget should be a directive to the main module?

  • If I design my widget as directives, is there a way to define dependency within a directive. I.e. to say that my directive uses ng-calender in its implementation?

  • If I design each widget as a separate module, is there a way to dynamically add the widget module as a dependency to the main module?

  • How should I design the controllers - one controller per widget probably?

  • How should i separate the state (scope) if i have multiple widgets from the same type in the view?

  • Are there bestpractices for designing reusable widgets with AngularJS?



EDIT



Useful references:




Answer



These are just general advices.




How should I design my app and widgets - should i have a separate AngularJS module or each widget should be a directive to the main module?




You're talking hundres of widgets, it seems natural to split them into several modules. Some widgets might have more in common than other widgets. Some might be very general and fit in other projects, others are more specific.




If I design my widget as directives, is there a way to define dependency within a directive. I.e. to say that my directive uses ng-calender in its implementation?




Dependencies to other modules are done on a module level, but there is no problem if module A depends on module B and both A and B depends on module C. Directives are a natural choice for creating widgets in Angular. If a directive depends on another directive you either define them in the same module, or create the dependency on a modular level.




If I design each widget as a separate module, is there a way to dynamically add the widget module as a dependency to the main module?




I'm not sure why you would want to do this, and I'm not sure how to do it. Directives and services are not initialized before they get used in Angular. If you have a huge library of directives (widgets) and know that you'll probably use some of them, but not all of them - but you don't know which ones will get used when the application gets initialized you can actually "lazy load" your directives after your module has been loaded. I've created an example here



The benefit is that you can get your application to load fast even if you have lots of code, because you don't have to load the scripts before you need them. The disadvantage is that there can be a considerably delay the first time a new directive is loaded.




How should I design the controllers - one controller per widget probably?




A widget will probably need its own controller. Controllers should generally be small, if they get big you can consider if there's any functionality that would fit better in a service.




How should i separate the state (scope) if i have multiple widgets from the same type in the view?




Widgets that need scope variables should without doubt have their own isolated scopes (scope:{ ... } in the directive configuration).




Are there bestpractices for designing reusable widgets with AngularJS?




Isolate the scope, keep the dependencies to a necessary minimum.See Misko's video about best practices in Angular



Brian Ford has also written an article about writing a huge application in Angular


javascript - Deep copy an array in Angular 2 + TypeScript



I have an array of objects that is an input. Lets call it content.



When trying to deep copy it, it still has a reference to the previous array.



I need to duplicate that input array, and change one property of the duplicated part.



So long I've tried different methods that weren't successful.




ES6 way:



public duplicateArray() {
arr = [...this.content]
arr.map((x) => {x.status = DEFAULT});
return this.content.concat(arr);
}



The slice way:



public duplicateArray() {
arr = this.content.slice(0);
arr.map((x) => {x.status = DEFAULT});
return this.content.concat(arr);
}


In both of them all the objects inside the array have status: 'Default'.




What's the best approach to deep copy the array in Angular 2?


Answer



Check this:



  let cloned = source.map(x => Object.assign({}, x));

Static and dynamic memory allocation in C++

Why the following guess is wrong ? (a software engineering company manager told me that it's almost correct but I don't understand why and I can't search for the answer in the Internet..)




int* ptr = new int;      // Sorry I mistyped before


My claim :




  1. left part (ptr) is of static memory allocation.

  2. right part (new int) is of dynamic memory allocation.




// new edited : 1 Jan 2015 17:39 (UTC +08:00)
what I am thinking is,
It moves the pointer of stack down(or up?) to free a space for ptr.
And find a empty space for a new int.
And then store the address of this new int to ptr.

c++ - Can a local variable's memory be accessed outside its scope?



I have the following code.



#include 


int * foo()
{
int a = 5;
return &a;
}

int main()
{
int* p = foo();
std::cout << *p;

*p = 8;
std::cout << *p;
}


And the code is just running with no runtime exceptions!



The output was 58



How can it be? Isn't the memory of a local variable inaccessible outside its function?



Answer




How can it be? Isn't the memory of a local variable inaccessible outside its function?




You rent a hotel room. You put a book in the top drawer of the bedside table and go to sleep. You check out the next morning, but "forget" to give back your key. You steal the key!



A week later, you return to the hotel, do not check in, sneak into your old room with your stolen key, and look in the drawer. Your book is still there. Astonishing!



How can that be? Aren't the contents of a hotel room drawer inaccessible if you haven't rented the room?




Well, obviously that scenario can happen in the real world no problem. There is no mysterious force that causes your book to disappear when you are no longer authorized to be in the room. Nor is there a mysterious force that prevents you from entering a room with a stolen key.



The hotel management is not required to remove your book. You didn't make a contract with them that said that if you leave stuff behind, they'll shred it for you. If you illegally re-enter your room with a stolen key to get it back, the hotel security staff is not required to catch you sneaking in. You didn't make a contract with them that said "if I try to sneak back into my room later, you are required to stop me." Rather, you signed a contract with them that said "I promise not to sneak back into my room later", a contract which you broke.



In this situation anything can happen. The book can be there -- you got lucky. Someone else's book can be there and yours could be in the hotel's furnace. Someone could be there right when you come in, tearing your book to pieces. The hotel could have removed the table and book entirely and replaced it with a wardrobe. The entire hotel could be just about to be torn down and replaced with a football stadium, and you are going to die in an explosion while you are sneaking around.



You don't know what is going to happen; when you checked out of the hotel and stole a key to illegally use later, you gave up the right to live in a predictable, safe world because you chose to break the rules of the system.



C++ is not a safe language. It will cheerfully allow you to break the rules of the system. If you try to do something illegal and foolish like going back into a room you're not authorized to be in and rummaging through a desk that might not even be there anymore, C++ is not going to stop you. Safer languages than C++ solve this problem by restricting your power -- by having much stricter control over keys, for example.




UPDATE



Holy goodness, this answer is getting a lot of attention. (I'm not sure why -- I considered it to be just a "fun" little analogy, but whatever.)



I thought it might be germane to update this a bit with a few more technical thoughts.



Compilers are in the business of generating code which manages the storage of the data manipulated by that program. There are lots of different ways of generating code to manage memory, but over time two basic techniques have become entrenched.



The first is to have some sort of "long lived" storage area where the "lifetime" of each byte in the storage -- that is, the period of time when it is validly associated with some program variable -- cannot be easily predicted ahead of time. The compiler generates calls into a "heap manager" that knows how to dynamically allocate storage when it is needed and reclaim it when it is no longer needed.




The second method is to have a “short-lived” storage area where the lifetime of each byte is well known. Here, the lifetimes follow a “nesting” pattern. The longest-lived of these short-lived variables will be allocated before any other short-lived variables, and will be freed last. Shorter-lived variables will be allocated after the longest-lived ones, and will be freed before them. The lifetime of these shorter-lived variables is “nested” within the lifetime of longer-lived ones.



Local variables follow the latter pattern; when a method is entered, its local variables come alive. When that method calls another method, the new method's local variables come alive. They'll be dead before the first method's local variables are dead. The relative order of the beginnings and endings of lifetimes of storages associated with local variables can be worked out ahead of time.



For this reason, local variables are usually generated as storage on a "stack" data structure, because a stack has the property that the first thing pushed on it is going to be the last thing popped off.



It's like the hotel decides to only rent out rooms sequentially, and you can't check out until everyone with a room number higher than you has checked out.



So let's think about the stack. In many operating systems you get one stack per thread and the stack is allocated to be a certain fixed size. When you call a method, stuff is pushed onto the stack. If you then pass a pointer to the stack back out of your method, as the original poster does here, that's just a pointer to the middle of some entirely valid million-byte memory block. In our analogy, you check out of the hotel; when you do, you just checked out of the highest-numbered occupied room. If no one else checks in after you, and you go back to your room illegally, all your stuff is guaranteed to still be there in this particular hotel.




We use stacks for temporary stores because they are really cheap and easy. An implementation of C++ is not required to use a stack for storage of locals; it could use the heap. It doesn't, because that would make the program slower.



An implementation of C++ is not required to leave the garbage you left on the stack untouched so that you can come back for it later illegally; it is perfectly legal for the compiler to generate code that turns back to zero everything in the "room" that you just vacated. It doesn't because again, that would be expensive.



An implementation of C++ is not required to ensure that when the stack logically shrinks, the addresses that used to be valid are still mapped into memory. The implementation is allowed to tell the operating system "we're done using this page of stack now. Until I say otherwise, issue an exception that destroys the process if anyone touches the previously-valid stack page". Again, implementations do not actually do that because it is slow and unnecessary.



Instead, implementations let you make mistakes and get away with it. Most of the time. Until one day something truly awful goes wrong and the process explodes.



This is problematic. There are a lot of rules and it is very easy to break them accidentally. I certainly have many times. And worse, the problem often only surfaces when memory is detected to be corrupt billions of nanoseconds after the corruption happened, when it is very hard to figure out who messed it up.




More memory-safe languages solve this problem by restricting your power. In "normal" C# there simply is no way to take the address of a local and return it or store it for later. You can take the address of a local, but the language is cleverly designed so that it is impossible to use it after the lifetime of the local ends. In order to take the address of a local and pass it back, you have to put the compiler in a special "unsafe" mode, and put the word "unsafe" in your program, to call attention to the fact that you are probably doing something dangerous that could be breaking the rules.



For further reading:




Tuesday 30 October 2018

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV



In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This particular scene was quite strange and confused me pretty badly, because she's a mammoth, why did she hang on the tree like that?



Further, I've only watched the Ice Age3 and Ice Age4. Did I miss anything? Did they show any scene towards Peaches' mom's strange behavior in the previous parts?



Answer



In Ice Age 2, when Elle was first introduced, she thought she was a possum, thus hanging upside down in a tree to sleep. Some of her habits were taught to Peaches, thus the girl sleeping upside down.



In Ice Age 4, there was a line of dialogue from Peaches about being half possum. this came from the idea that Elle still believes herself to be a possum, but that Peaches' dad is a mammoth.


marvel - Why are "Batman" and "Superman" both one word but "Spider-Man" is hyphenated? - Science Fiction & Fantasy



Batman and Superman are always spelt as all one word but Spider-Man is separated into two words.



Is there any reason behind or is it just the way it is?


Answer



Stan Lee has claimed (e.g., in the set of Twitter posts quoted here) that the hyphen is to stop people from confusing Spider-Man with Superman:





Spidey's official name has a hyphen: "Spider-Man." Know why? When I dreamed him up, I didn't want anyone confusing him with Superman!



how i met your mother - Why is Bob Saget the future voice for Ted Mosby'?


Well for one thing Ted is already an adult in his 30's and also isn't he telling the story to his kids in 2030 (which is only 18 years from now), so someone's voice does not change that much in 18 years! (Ted's voice hasn't changed that much in the 8 years the show has been on!)


Whats the deal with that?


php - Fatal error: Maximum execution time of 30 seconds exceeded



I am downloading a JSON file from an online source and and when it runs through the loop I am getting this error:





Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\temp\fetch.php on line 24



Answer



Your loop might be endless. If it is not, you could extend the maximum execution time like this:



ini_set('max_execution_time', 300); //300 seconds = 5 minutes


and



set_time_limit(300);



can be used to temporarily extend the time limit.


php - "Warning: Cannot modify header information - headers already sent by" error










i keep receiving this error each time i try to submit the a form deletion form.





Warning: Cannot modify header
information - headers already sent by
(output started at
C:\xampp\htdocs\speedycms\deleteclient.php:47)
in
C:\xampp\htdocs\speedycms\deleteclient.php
on line 106





is there something wrong with my code? what do i need to change to make it work?



if (!isset($_SESSION)) {
session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page

function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;

// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);

$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
}
// Or, you may restrict access to only certain users based on their username.
if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
}
if (($strUsers == "") && true) {
$isValid = true;

}
}
return $isValid;
}

$MM_restrictGoTo = "login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {
$MM_qsChar = "?";
$MM_referrer = $_SERVER['PHP_SELF'];
if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";

if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0)
$MM_referrer .= "?" . $QUERY_STRING;
$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
header("Location: ". $MM_restrictGoTo);
exit;
}
?>

require_once('Connections/speedycms.php');


$client_id = mysql_real_escape_string($_GET['id']);

$con = mysql_connect($hostname_speedycms, $username_speedycms, $password_speedycms);

if (!$con)
{
die('Could not connect: ' . mysql_error());
}


mysql_select_db("speedycms") or die(mysql_error());
?>

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}


$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";

break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;

}
return $theValue;
}
}

if ((isset($_GET['id'])) && ($_GET['id'] != "") && (isset($_POST['deleteForm']))) {
$deleteSQL = sprintf("DELETE FROM tbl_accident WHERE id=%s",
GetSQLValueString($_GET['id'], "int"));

mysql_select_db($database_speedycms, $speedycms);

$Result1 = mysql_query($deleteSQL, $speedycms) or die(mysql_error());

$deleteGoTo = "progress.php";
if (isset($_SERVER['QUERY_STRING'])) {
$deleteGoTo .= (strpos($deleteGoTo, '?')) ? "&" : "?";
$deleteGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $deleteGoTo));
}


mysql_select_db($database_speedycms, $speedycms);
$query_delete = "SELECT * FROM tbl_accident WHERE id=$client_id";
$delete = mysql_query($query_delete, $speedycms) or die(mysql_error());
$row_delete = mysql_fetch_assoc($delete);
$totalRows_delete = mysql_num_rows($delete);
?>

Are you sure you wish to delete the record for ?











thanking you in advance!


Answer



Lines 45-47:




?>



That's sending a couple of newlines as output, so the headers are already dispatched. Just remove those 3 lines (it's all one big PHP block after all, no need to end PHP parsing and then start it again), as well as the similar block on lines 60-62, and it'll work.



Notice that the error message you got actually gives you a lot of information to help you find this yourself:





Warning: Cannot modify header
information - headers already sent by
(output started at
C:\xampp\htdocs\speedycms\deleteclient.php:47
)
in
C:\xampp\htdocs\speedycms\deleteclient.php
on line 106




The two bolded sections tell you where the item is that sent output before the headers (line 47) and where the item is that was trying to send a header after output (line 106).



class - java: Why must I write super() in the first line of the constructor



Possible Duplicate:
Why does this() and super() have to be the first statement in a constructor?






I just learned that at school, but the teacher doesn't know why.



I can think of some good reasons, but I think there are cases when the initializing can be done later in the constructor- before you use the variables form the mother class, for example. OK, the variables should be initialized from the start, but that's not always necessary.



I"m guessing there are a more reasons for that why must super() be placed in the first line of the constructor.




So, why must I write super() in the first line of the constructor, when I'm inheriting a class?

How do you check if a variable is an array in JavaScript?




I would like to check whether a variable is either an array or a single value in JavaScript.



I have found a possible solution...



if (variable.constructor == Array)...


Is this the best way this can be done?


Answer




There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.



variable.constructor === Array


This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.



If you are having issues with finding out if an objects property is an array, you must first check if the property is there.



variable.prop && variable.prop.constructor === Array



Some other ways are:



Array.isArray(variable)


Update May 23, 2019 using Chrome 75, shout out to @AnduAndrici for having me revisit this with his question
This last one is, in my opinion the ugliest, and it is one of the slowest fastest. Running about 1/5 the speed as the first example. This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray




variable instanceof Array


This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number always returns false. Update: instanceof now goes 2/3 the speed!



So yet another update



Object.prototype.toString.call(variable) === '[object Array]';



This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.



Also, I ran some test: http://jsperf.com/instanceof-array-vs-array-isarray/35 So have some fun and check it out.



Note: @EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.


analysis - Is Ferris Bueller's Day Off intentionally inspired by Blues Brothers?

I saw Blues Brothers (1980) for the first time last night and I couldn't help but see many parallels between it and Ferris Bueller's Day Off (1986).


Both plots feature an adventure in the city of Chicago. There are some similar scenes such as the scene at the French restaurant and over-the-top musical numbers. The two movies had a very similar feel in many places and I can't help but compare them.


Were the creators of Ferris Bueller's Day Off inspired by Blues Brothers? Were specific parallels drawn intentionally?


What is the best practice to create a custom helper function in php Laravel 5?





the default created_at date keep printing out as an MySQL format : 2015-06-12 09:01:26. I wanted to print it as my own way like 12/2/2017, and other formats in the future.









a file called DataHelper.php and store it at /app/Helpers/DateHelper.php - and it looks like this




namespace App\Helpers;


class DateHelper {

public static function dateFormat1($date) {
if ($date) {
$dt = new DateTime($date);

return $dt->format("m/d/y"); // 10/27/2014
}
}

}







to be able to called it in my blade view like



DateHelper::dateFormat1($user->created_at)



I'm not sure what to do next.



What is the best practice to create a custom helper function in php Laravel 5?


Answer




  1. Within your app/Http directory, create a helpers.php file and add your functions.

  2. Within composer.json, in the autoload block, add "files": ["app/Http/helpers.php"].

  3. Run composer dump-autoload




That should do it. :)


json - How to convert time format utc to ist zone in android

I am getting time String like this from jsonAPI "2017-03-16T17:23:44.860Z",

And i want to convert INDIAN STANDARD TIME ZONE format Like this 3/16/2017 10:53:44 PM.
And finally textview.setText("3/16/2017 10:53:44 PM")

php - Syntax error on return statement




I'm doing this simple website, and I have run into this error:



My function:



function user_exists($username)
{

$username = sanitize($username);
$query = mysqli_query($connect, "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
return (mysqli_result($query, === 0) 1) ? true : false;
}
?>


My php error log:



PHP Parse error:  

syntax error, unexpected '===' (T_IS_IDENTICAL) in function on line 6


Line 6 is the return line.



I understand what a syntax error means, but I'm quite sure that the '===' is not the problem.


Answer



Edit : I was only talking about the ternary condition and this answer is false because the mysqli_result() function doesn't exist.



I guess you are trying to do this :




return mysqli_result($query) === 0 ? false : true;


And as Marcel Korpel said, use prepared statements to avoid security flaws.


sql server - SQL update query using joins




I have to update a field with a value which is returned by a join of 3 tables.



Example:



select
im.itemid
,im.sku as iSku
,gm.SKU as GSKU
,mm.ManufacturerId as ManuId

,mm.ManufacturerName
,im.mf_item_number
,mm.ManufacturerID
from
item_master im, group_master gm, Manufacturer_Master mm
where
im.mf_item_number like 'STA%'
and im.sku=gm.sku
and gm.ManufacturerID = mm.ManufacturerID
and gm.manufacturerID=34



I want to update the mf_item_number field values of table item_master with some other value which is joined in the above condition.



How can I do this in MS SQL Server?


Answer



UPDATE im
SET mf_item_number = gm.SKU --etc
FROM item_master im
JOIN group_master gm

ON im.sku = gm.sku
JOIN Manufacturer_Master mm
ON gm.ManufacturerID = mm.ManufacturerID
WHERE im.mf_item_number like 'STA%' AND
gm.manufacturerID = 34


To make it clear... The UPDATE clause can refer to an table alias specified in the FROM clause. So im in this case is valid



Generic example




UPDATE A
SET foo = B.bar
FROM TableA A
JOIN TableB B
ON A.col1 = B.colx
WHERE ...

c++ - Using std Namespace

There seem to be different views on using 'using' with respect to the std namespace.



Some say use ' using namespace std', other say don't but rather prefix std functions that are to be used with ' std::' whilst others say use something like this:



using std::string;
using std::cout;
using std::cin;
using std::endl;
using std::vector;


for all the std functions that are to be used.



What are the pros and cons of each?

mysql - PHP error when trying to select row from multiple tables




I am trying to use a SELECT * statement in PHP but from two tables. The query I make is the following:



$query2="SELECT * FROM london, manchester WHERE user = '$row[user]'";

$result = mysqli_query($con,$query2);


If I try it with just one table, say london, the query works fine. However, when trying to query two tables I get the following error:



mysqli_fetch_array() expects parameter 1 to be mysqli_result,


Here is how I call the result...




while($row = mysqli_fetch_array($result)) {
results....
}


Upon looking into the exact reason the error message occurs i am being told that "Column 'user' in where clause is ambiguous".


Answer



For something simple like that statement, try using a MySQL UNION.



Select * from london where user = '$row[user]' 

UNION Select * from manchester
where user = '$row[user]'


Or with PDO...



Select * from london where user = :user UNION Select * from manchester where user = :user


...and then bind :user with your variable.



java - How to compare two strings are equal in value, what is the best method?

You can either use the == operator or the Object.equals(Object) method.


The == operator checks whether the two subjects are the same object, whereas the equals method checks for equal contents (length and characters).


if(objectA == objectB) {
// objects are the same instance. i.e. compare two memory addresses against each other.
}
if(objectA.equals(objectB)) {
// objects have the same contents. i.e. compare all characters to each other
}

Which you choose depends on your logic - use == if you can and equals if you do not care about performance, it is quite fast anyhow.


String.intern() If you have two strings, you can internate them, i.e. make the JVM create a String pool and returning to you the instance equal to the pool instance (by calling String.intern()). This means that if you have two Strings, you can call String.intern() on both and then use the == operator. String.intern() is however expensive, and should only be used as an optimalization - it only pays off for multiple comparisons.


All in-code Strings are however already internated, so if you are not creating new Strings, you are free to use the == operator. In general, you are pretty safe (and fast) with


if(objectA == objectB || objectA.equals(objectB)) {
}

if you have a mix of the two scenarios. The inline


if(objectA == null ? objectB == null : objectA.equals(objectB)) {
}

can also be quite useful, it also handles null values since String.equals(..) checks for null.

php - How to embed if statement inside echo




I'm gettin' a headache on that. I need to put if statement inside an echo (this echo is in a function, it's for a form submit actually)



Here is an example on a partial of my code. In this situation, how can I put theses if statement inside my echo??



   

'
; ?>

Answer



Everything is php so need to use more than the first Finish each echo before checking with if. Like this:



  echo ' 


EDIT: The following code was helpful with chaining. However, (in Internet Explorer) .val('whatever') did not select the option that was added. (I did use the same 'value' in both .append and .val.)




$('#mySelect').find('option').remove().end()
.append('').val('whatever');


EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. .focus() was closer, but the option did not appear selected like it does with .selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery.



var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");

mySelect.options[0].selected="true";


EDIT: selected answer was close to what I needed. This worked for me:



$('#mySelect').children().remove().end()
.append('') ;


But both answers led me to my final solution..



Answer



$('#mySelect')
.find('option')
.remove()
.end()
.append('')
.val('whatever')
;

php - Where is the mysqli prepared statement query error?



I'm trying to create a mysqli prepared statement where I import tables from an odbc connected database into a mysql database, I'm getting this error with 106-column wide table query.




You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use

near '? (ID, column1, column2, column3, column4, ' at line 1"




When I echo out the query here it is...




INSERT INTO ? (ID, column1, column2, column3, column4, ...106 total columns... ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,

?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?)




$sql = "SELECT * FROM $table WHERE $key = '$acct'";
$link = getODBCConnection();
$result = odbc_do($link, $sql);
$data = array();
while ($row = odbc_fetch_array($result)) {
//store all query rows as array

array_push($data, $row);
}
//insert into mysql table of the same name
//get column count from first row
$columns = count($data[0]);
$params = str_repeat(" ?,",$columns);
$params = rtrim($params,',');
$types = str_repeat("s",$columns+1);
$fields = implode(", ", array_keys($data[0]));
$sql = "INSERT INTO ? ($fields) VALUES ($params) ON DUPLICATE KEY UPDATE";

echo $sql."
";
$link = getSalesConnection();
$stmt = $link->prepare($sql);
var_dump($link->error);
foreach ($data as $row) {
$stmt->bind_param($types, $table, implode(", ",array_values($row)));
$stmt->execute();
}



I've tried this using standard bind_param and also using the call_user_func_array() method. I've tried quoting my parameter strings and the column names, without effect. If there was an error with my bind_param types I should not have an error on the prepare statement should I? But there is some problem with the SQL going to the prepare command that I can't pinpoint. Please help!


Answer



Query parameters can be used in place of scalar values only. You can't parameterize table names, column names, SQL expressions, keywords, lists of values, etc.




  • WRONG: SELECT ?, b, c FROM t WHERE a = 1 ORDER BY b ASC
    The parameter value will be a literal value, not the name of a column.


  • WRONG: SELECT a, b, c FROM ? WHERE a = 1 ORDER BY b ASC
    Syntax error.


  • WRONG: SELECT a, b, c FROM t WHERE ? = 1 ORDER BY b ASC
    The parameter value will be a literal value, not the name of a column.


  • WRONG: SELECT a, b, c FROM t WHERE a IN (?) ORDER BY b ASC
    The parameter value will be a single literal value, not a list of values, even if you pass a string of comma-separated values.


  • WRONG: SELECT a, b, c FROM t WHERE a = 1 ORDER BY ? ASC
    The parameter value will be a literal value, not the name of a column.



  • WRONG: SELECT a, b, c FROM t WHERE a = 1 ORDER BY b ?
    Syntax error.




Basically if you could write a string literal, date literal, or numeric literal in place of the query parameter, it should be okay. Otherwise you have to interpolate the dynamic content into the SQL string before you prepare() it.


php - jquery ajax post doesn't work

I read many posts on this issue but I can not solve the problem.

It seems that ajax() works fine, but the .php file fails to update the SQL database and returns no results to the ajax() function.



This is my code:




var datastring=JSON.stringify(utnew)

$.ajax({
type: "POST",
url: "myulr-php",

data: datastring,
dataType: "json",
success: function(resto){
if (resto=="success"){
$("#pop-confermadatiuser").html("OK");
}else{
$("#pop-confermadatiuser").html("KO");
};
}


});




The php code work, i have try.
this is the code:






header("Access-Control-Allow-Origin: *");
$con = mysqli_connect("sql","xxx","xxx","xxx") or die ("could not connect database");

$ck=1 ;
if(isset($_POST['id']))
{
$id=$_POST['id'];
$nome=$_POST['nome'];
$cognome=$_POST['cognome'];
$matricola=$_POST['matricola'];

$mail=$_POST['mail'];
$password=$_POST['password'];
$ck=2
$qry="UPDATE user SET nome='".$nome."', cognome='".$cognome."', mail='".$mail."', password='".$password."' where id=".$id." and matricola=".$matricola;

$q=mysqli_query($con,$qry);
if($q) {
echo "success";
} else {
echo "error";

};
mysqli_close($con);
};

if(ck==1){
echo "error2";
};




javascript - Delaying AngularJS route change until model loaded to prevent flicker

I am wondering if there is a way (similar to Gmail) for AngularJS to delay showing a new route until after each model and its data has been fetched using its respective services.




For example, if there were a ProjectsController that listed all Projects and project_index.html which was the template that showed these Projects, Project.query() would be fetched completely before showing the new page.



Until then, the old page would still continue to show (for example, if I were browsing another page and then decided to see this Project index).

In Java, when should I create a checked exception, and when should it be a runtime exception?










When should I create a checked exception, and when should I make a runtime exception?



For example, suppose I created the following class:



public class Account {
private float balance;

/* ... constructor, getter, and other fields and methods */

public void transferTo(Account other, float amount) {
if (amount > balance)
throw new NotEnoughBalanceException();
/* ... */
}
}


How should I create my NotEnoughBalanceException? Should it extend Exception or RuntimeException? Or should I just use IllegalArgumentException instead?


Answer



There's a LOT of disagreement on this topic. At my last job, we ran into some real issues with Runtime exceptions being forgotten until they showed up in production (on agedwards.com), so we resolved to use checked exceptions exclusively.



At my current job, I find that there are many who are for Runtime exceptions in many or all cases.



Here's what I think: Using CheckedExceptions, I am forced at compile time to at least acknowledge the exception in the caller. With Runtime exceptions, I am not forced to by the compiler, but can write a unit test that makes me deal with it. Since I still believe that the earlier a bug is caught the cheaper it is to fix it, I prefer CheckedExceptions for this reason.



From a philosophical point of view, a method call is a contract to some degree between the caller and the called. Since the compiler enforces the types of parameters that are passed in, it seems symmetrical to let it enforce the types on the way out. That is, return values or exceptions.



My experience tells me that I get higher quality, that is, code that JUST WORKS, when I'm using checked exceptions. Checked exceptions may clutter code, but there are techniques to deal with this. I like to translate exceptions when passing a layer boundary. For example, if I'm passing up from my persistence layer, I would like to convert an SQL exception to a persistence exception, since the next layer up shouldn't care that I'm persisting to a SQL database, but will want to know if something could not be persisted. Another technique I use is to create a simple hierarchy of exceptions. This lets me write cleaner code one layer up, since I can catch the superclass, and only deal with the individual subclasses when it really matters.


Python: References, dictionaries and lists



I've just started writing with Python and still getting used with references and where they are and aren't used.



I've written the following code:



dummyList = self.getSprayLocation(heading, "left")
self.points['leftLeft'][0] = self.armLocations['leftX'] - self.mmToCoor(dummyList[0])

self.points['leftLeft'][1] = self.armLocations['leftY'] - self.mmToCoor(dummyList[1])
self.points['rightLeft'][0] = self.armLocations['leftX'] + self.mmToCoor(dummyList[0])
self.points['rightLeft'][1] = self.armLocations['leftY'] + self.mmToCoor(dummyList[1])
dummyList = self.getSprayLocation(heading, "mid")
print(self.points['leftLeft'][1])

self.points['leftMid'][0] = self.armLocations['midX'] - self.mmToCoor(dummyList[0])
self.points['leftMid'][1] = self.armLocations['midY'] - self.mmToCoor(dummyList[1])
self.points['rightMid'][0] = self.armLocations['midX'] + self.mmToCoor(dummyList[0])
self.points['rightMid'][1] = self.armLocations['midY'] + self.mmToCoor(dummyList[1])

print(self.points['leftLeft'][1])

dummyList = self.getSprayLocation(heading, "right")
self.points['leftRight'][0] = self.armLocations['rightX'] - self.mmToCoor(dummyList[0])
self.points['leftRight'][1] = self.armLocations['rightY'] - self.mmToCoor(dummyList[1])
self.points['rightRight'][0] = self.armLocations['rightX'] + self.mmToCoor(dummyList[0])
self.points['rightRight'][1] = self.armLocations['rightY'] + self.mmToCoor(dummyList[1])
print(self.points['leftLeft'][1])



It's in a Class, where 'points' is a dictionary containing a list:



coordinate = [0, 0]
points = {'leftLeft':coordinate, 'rightLeft':coordinate, 'leftMid':coordinate, 'rightMid':coordinate, 'leftRight':coordinate, 'rightRight':coordinate}


Note that after every block of code I print the ['leftLeft'][0] value. I expect this value not to change when I don't write to this key in the dictionary.



But when I run this code, this is the output




51.861101789
51.8611355556
51.8611192766


Which means the value is changed. In fact, all 'leftX' entries are the same and all 'rightX' entries are the same.



Now I think it has something to do with the references, but I haven't come up with a solution for this yet.



Thanks for your help!







Edit:
Thanks to JoshuaF I found that the reference was in the



coordinate = [0, 0]
points = {'leftLeft':coordinate, 'rightLeft':coordinate, 'leftMid':coordinate, 'rightMid':coordinate, 'leftRight':coordinate, 'rightRight':coordinate}



Block. 'coordinate' was the same 'coordinate' everywhere. The following fixes this:



coordinate = [0, 0]
points = {'leftLeft':coordinate[:], 'rightLeft':coordinate[:], 'leftMid':coordinate[:], 'rightMid':coordinate[:], 'leftRight':coordinate[:], 'rightRight':coordinate[:]}


I know the [:] has got something to do with references and lists. But what?







meaning of [:] in python



Python copy manual


Answer



As written, every entry in points points to the same object, coordinate. Changing any of them will change coordinate and therefore all the others.


regex - From within Java, how can I create a list of all possible numbers from a specific regular expression?




I have a strange problem, at least one I've never come across. I have a precondition where customers have simple regular expressions associated with labels. The labels are all they care about. What I would like to do is create a list of all possible numbers that would match each of these regular expressions. I would have logic that would warn me when the list is beyond a certain threshold.



Here is an example of the regular expression: 34.25.14.(227|228|229|230|243|244|245|246)



Lets say that these ip(s) are associated with ACME. Behind the scenes when the user selects ACME (in our UI), I'm filling out a filter object that contains all of those possible numbers and submitting them as an OR query to a highly specialized Vertica database.



I just can't determine an elegant way of creating a list of numbers from said regular expressions.



The others aspect of this, is that the java code within another portion of the product is using those regular expressions to show ACME by using a java Pattern.compile(), which means the customer 'could' create a complex regular expression. I've only seen them, so far, use something simple as shown above.




Is there a method that will generate a list based on regular expression?



Thanks for your time.


Answer



Related:



A library that generates data matching a regular expression (with limitations):
http://code.google.com/p/xeger/



Several solutions, such as conversing a regex into a grammar:

Using Regex to generate Strings rather than match them






EDIT: Actually, you can make it work!!! The only thing to address is to impose some domain-specific constraints to preclude combinatorial explosion like a+.



If you add to the Xeger class something like this:



public void enumerate() {
System.out.println("enumerate: \"" + regex + "\"");

int level = 0;
String accumulated = "";
enumerate(level, accumulated, automaton.getInitialState());
}

private void enumerate(int level, String accumulated, State state) {
List transitions = state.getSortedTransitions(true);
if (state.isAccept()) {
System.out.println(accumulated);
return;

}
if (transitions.size() == 0) {
assert state.isAccept();
return;
}
int nroptions = state.isAccept() ? transitions.size() : transitions.size() - 1;
for (int option = 0; option <= nroptions; option++) {
// Moving on to next transition
Transition transition = transitions.get(option - (state.isAccept() ? 1 : 0));
for (char choice = transition.getMin(); choice <= transition.getMax(); choice++) {

enumerate(level + 1, accumulated + choice, transition.getDest());
}
}
}


... and something like this to XegerTest:



@Test
public void enumerateAllVariants() {

//String regex = "[ab]{4,6}c";
String regex = "34\\.25\\.14\\.(227|228|229|230|243|244|245|246)";
Xeger generator = new Xeger(regex);
generator.enumerate();
}


... you will get this:



-------------------------------------------------------

T E S T S
-------------------------------------------------------
Running nl.flotsam.xeger.XegerTest
enumerate: "34\.25\.14\.(227|228|229|230|243|244|245|246)"
34.25.14.227
34.25.14.228
34.25.14.229
34.25.14.243
34.25.14.244
34.25.14.245

34.25.14.246
34.25.14.230
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.114 sec


... and, guess what. For "[ab]{4,6}c" it correctly produces 112 variants.



It's really a quick and dirty experiment, but it seems to work ;).


php - what is meaning of clustered index in mysql

I have confusion in clustered index in database concept.
I completely read about indexing. So i understood the indexing.
But i don't know what is the proper meaning of clustered index.
Can any one help what is clustered index?

java - Is null check needed before calling instanceof?




Will null instanceof SomeClass return false or throw a NullPointerException?


Answer



No, a null check is not needed before using instanceof.



The expression x instanceof SomeClass is false if x is null.



From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof":





"At run time, the result of the
instanceof operator is true if the
value of the RelationalExpression is
not null
and the reference could be
cast to the ReferenceType
without raising a ClassCastException.
Otherwise the result is false."




So if the operand is null, the result is false.



Sunday 28 October 2018

php - return single array from json by passing a value





I have a json that I need to filter a specific key and value from



the following json




{
"5": {
"Owner": "94EAC",
"Record":"0121ln"
},
"15": {
"Owner": "009AC",
"Record":"0120Pc"
},

"1": {
"Owner": "00G11A",
"Record":"000lPcn"
},
"199": {
"Owner": "00G1y9",
"Record":"01211cn"
},
"33": {
"Owner": "001AC",

"Record":"0121n"
}


}



I would like to be able to pass the first int and get back array for that number.
For example if I pass 15 I get



 {

"Owner": "009AC",
"Record":"0120Pc"
}


I tried foreach loop but cannot set specific value for the first int



If I assign $data = json



then $date[15] didn't work
$data->15 also didn't work



I did also use the json decode and was able to print an array but wasn't able to get a single value
Any help would be great, I did spend all day and still cannot get an answer.
Thank you


Answer



Using Array:
$arr = json_decode($json, true);
print_r( $arr['15']);


Using Object:
$obj = json_decode($json);
print_r( $obj['15']);


Reference: json_decode


Short way to write or in python

I have this code:



table is a list.




if 'ping' in table or 'pong' in table:
# Do something here


Is there a shorter way to write this?
I don't want to have table duplicated in the if statement.

java - What is more advisable to create a thread by extending a Thread class or implementing Runnable?

I like to know which is more preferable to create a thread by extending thread class or by implementing Runnable interface.And Why ?



Thanks..

How can I transition height: 0; to height: auto; using CSS?



I am trying to make a

    slide down using CSS transitions.



    The

      starts off at height: 0;. On hover, the height is set to height:auto;. However, this is causing it to simply appear, not transition,



      If I do it from height: 40px; to height: auto;, then it will slide up to height: 0;, and then suddenly jump to the correct height.




      How else could I do this without using JavaScript?





      #child0 {
      height: 0;
      overflow: hidden;
      background-color: #dedede;
      -moz-transition: height 1s ease;

      -webkit-transition: height 1s ease;
      -o-transition: height 1s ease;
      transition: height 1s ease;
      }
      #parent0:hover #child0 {
      height: auto;
      }
      #child40 {
      height: 40px;
      overflow: hidden;

      background-color: #dedede;
      -moz-transition: height 1s ease;
      -webkit-transition: height 1s ease;
      -o-transition: height 1s ease;
      transition: height 1s ease;
      }
      #parent40:hover #child40 {
      height: auto;
      }
      h1 {

      font-weight: bold;
      }

      The only difference between the two snippets of CSS is one has height: 0, the other height: 40.



      Hover me (height: 0)


      Some content

      Some content

      Some content

      Some content


      Some content

      Some content






      Hover me (height: 40)


      Some content

      Some content


      Some content

      Some content

      Some content

      Some content







Answer



Use max-height in the transition and not height. And set a value on max-height to something bigger than your box will ever get.



See JSFiddle demo provided by Chris Jordan in another answer here.





#menu #list {
max-height: 0;
transition: max-height 0.15s ease-out;

overflow: hidden;
background: #d5d5d5;
}

#menu:hover #list {
max-height: 500px;
transition: max-height 0.25s ease-in;
}






Did Neil Marshall deliberately reference The Matrix in Dog Soldiers?

In the film Dog Soldiers by Neil Marshall, the following dialogue occurs between two characters:



Where is Spoon?


There is no Spoon



The Spoon referenced in the dialogue was one of the characters in the film who was eaten by werewolves.


Was this a deliberate reference to The Matrix?


Answer


According to the Wikipedia page for the movie, the director, cast and crew commentary on the DVD confirms that:



The film contains homages to H.G. Wells, the films The Evil Dead,
Zulu, Aliens, The Matrix and Star Trek: The Wrath of Khan.



That means that the dialogue mention by you is directly referring to The Matrix.


java - Unsupported major.minor version 52.0 in my app



I'm trying to compile my Android project and I'm getting this error



[INFO] Exception in thread "main" java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0
[INFO] at java.lang.ClassLoader.defineClass1(Native Method)
[INFO] at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
[INFO] at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
[INFO] at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)

[INFO] at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
[INFO] at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
[INFO] at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
[INFO] at java.security.AccessController.doPrivileged(Native Method)
[INFO] at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
[INFO] at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
[INFO] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
[INFO] at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
[INFO] at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)
[INFO] ------------------------------------------------------------------------

[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------


I've been reading in other post that try to compile with Java 8 might cause that error but not my case, I have the following Java version:



java version "1.7.0_79"
OpenJDK Runtime Environment (IcedTea 2.5.5) (7u79-2.5.5-0ubuntu0.14.04.2)
OpenJDK 64-Bit Server VM (build 24.79-b02, mixed mode)



OS: Linux Mint
(I'm not have Java 8 installed.)
Build: MAVEN



Can anyone help me with this?


Answer



I face this problem too when making new project from android studio.



I've been able to resolve this by downgrading buildToolsVersion in app gradle setting:

change {module-name}/build.gradle line




buildToolsVersion "24.0.0 rc1"




to




buildToolsVersion "23.0.3"






@Edit:
In Android Studio 2.1 Go to File-> Project Structure->App -> Build Tool Version. Change it to 23.0.3



Do the method above, only when you are using java version 7 and for some reason do not want to upgrade to java 8 yet.



Hope this helps


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