Monday, December 31, 2018

How do I send a file as an email attachment using Linux command line?



I've created a script that runs every night on my Linux server that uses mysqldump to back up each of my MySQL databases to .sql files and packages them together as a compressed .tar file. The next step I want to accomplish is to send that tar file through email to a remote email server for safekeeping. I've been able to send the raw script in the body an email by piping the backup text file to mailx like so:



$ cat mysqldbbackup.sql | mailx backup@email.com



cat echoes the backup file's text which is piped into the mailx program with the recipient's email address passed as an argument.



While this accomplishes what I need, I think it could be one step better, Is there any way, using shell scripts or otherwise, to send the compressed .tar file to an outgoing email message as an attachment? This would beat having to deal with very long email messages which contain header data and often have word-wrapping issues etc.


Answer



None of the mutt ones worked for me. It was thinking the email address was part of the attachemnt. Had to do:



echo "This is the message body" | mutt -a "/path/to/file.to.attach" -s "subject of message" -- recipient@domain.com


php - Use of undefined constant j - assumed 'j'

Im creating a scrapping code that scrap each Address in a specific suburbs. but im stuck in this problem; " Use of undefined constant j - assumed 'j'" and it identified in $target_url can anyone help me this problem?



$arr = array("Illawong 2232",
"Strathfield 2135",
"Croydon 2132",
"Croydon Park 2133",
"Burwood 2134",

"Parramatta 2150",
"Hurtsville 2220",
"Seven Hills 2153",
"Blacktown 2148",
"Toongabie 2146",
"Winston Hills 2153",
"Bondi Beach 2026",
"Bondi Junction 2022",
"Coogee 2034",
"Pymble 2073",

"Miranda 2228",
"Caringbah 2229",
"Sylvania 2224",
"Drummoyne 2047",
"Concord 2137"
);
$counter = count($arr);
for($j=0;$j<$counter; $j++)
{


$arr2 = array("list-1", "list-2", "list-3","list-4", "list-5");
$count = count($arr2);

for($i=0;$count>$i;$i++)
{

//scrapping starts here
$target_url = "http://www.xxxxxxxxx.com.au/buy/".$arr[j]."/".$arr2[i]."?includeSurrounding=false";
$html = new simple_html_dom();




$html->load_file($target_url);

foreach($html->find('a[class=name]') as $vcard)
{
echo $vcard. "
"
}
}
}

php - Regex match the double quote in BBCode attribute



I have text stored in my forum database with some incompatible such as the following:




Some text with [COLOR="red"]colored text[/COLOR] and [SIZE="7"]Big fonts[/SIZE] while "This double quote" is not matched


What I want is a regex that match any double quotes " " with any string inside them while those double quotes are inside the square bracket [ ] of the bbcode.



I need this to be able to fix those bbcodes by stripping the double quotes. The regex implementation is going to be using PHP.


Answer



You may be looking for something like this:



$code= 'Some text with [COLOR="red"]colored text[/COLOR] and [SIZE="7"]Big fonts[/SIZE] while "This double quote" is not matched';


preg_match_all('/\[.*?="(\w+)"\]/', $code, $matches, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($matches[1]); $i++) {
echo $matches[1][$i]."\n";
}


DEMO:
https://ideone.com/LEZHgx


What regex will match every character except comma ',' or semi-colon ';'?



Is it possible to define a regex which will match every character except a certain defined character or set of characters?



Basically, I wanted to split a string by either comma (,) or semi-colon (;). So I was thinking of doing it with a regex which would match everything until it encountered a comma or a semi-colon.


Answer




[^,;]+         


You haven't specified the regex implementation you are using. Most of them have a Split method that takes delimiters and split by them. You might want to use that one with a "normal" (without ^) character class:



[,;]+

javascript closure - how come I refer to an undeclared variable





Try to get my head around javascript closures as they are new to me.
I have a tutorial that indicates to use:



function warningMaker( obstacle ){
function doAlert (obs) {
alert("Beware! There have been "+obs+" sightings in the Cove today!");
};

return doAlert;
}


But I am confused about "obs". Does the parameter 'obstacle' automatically get passed to obs ?



A better example perhaps might be:



function warningMaker( obstacle ){
return function (number,location) {

alert("Beware! There have been " +
obstacle +
" sightings in the Cove today!\n" +
number + " " + obstacle +
"(s) spotted at the " +
location + "!"
);
};
}


Answer



Either the example you've got is missing some lines or it isn't a proper example for closure. A better example (with simplified code) would be



function warningMaker(obstacle){
return function() {
alert("Look!" + obstacle);
}
}



What the above does is, when the function is getting returned, the reference to the obstacle in the function body creates a closure so it will be in memory and will be used whenever called and it will be



warningMaker("Messi")(); // "Look! Messi"
warningMaker("CR7")(); // "Look! CR7"


Note that in the above, the function returned is being called. (I mean, the empty parentheses)


php - One MySQL Database & Multiple Table



How to connect to a certain table in MySQL database?



I have tried :



mysql_select_db("baybeestore",$connection);


but it gives me an error :-




"Error : Table 'baybeestore.form' doesn't exist"


But I've created a table named as order. Are there any PHP codes to connect to my table order in the same database that have multiple databases?



Is it wise enough to create multiple database & one table for one website
or multiple table with one database?



FULL CODE :




$connection = mysql_connect("localhost","user","1234");
if(!$connection)
{
die('Failed to connect to MySQL :' . mysql_error());
}
mysql_select_db("baybeestore",$connection)
$sql = "INSERT INTO
form(name, address, email, handphone, item, payment)

VALUES

('$strname', '$straddress', '$stremail', '$strhandphone', '$stritem', '$strpayment')";

if(!mysql_query($sql, $connection))
{
die('Error : ' . mysql_error());
}
echo "Data have been saved.";
mysql_close($connection);

Answer



As per your edit/added code. Your originally posted code




You're using two different tables for your queries. Result: ERROR



You have SELECT * FROM order and INSERT INTO form 2 different animals altogether.



If anything, that should be INSERT INTO order or SELECT * FROM form yet... ORDER is a reserved word and should be enclosed with backticks.



I.e.:



INSERT INTO `order`




excel - Parse CSV, ignoring commas inside string literals in VBA?



I have a VBA application that runs every day. It checks a folder where CSVs are downloaded automatically, and adds their contents to a database. When parsing them, I realized that certain values had commas as a part of their name. These values were contained in string literals.



So I'm trying to figure out how to parse this CSV and ignore commas that are contained in string literals. For example...



1,2,3,"This should,be one part",5,6,7 Should return 

1

2
3
"This should,be one part"
5
6
7


I have been using VBA's split() function, because I don't wanna reinvent the wheel, but if I have to I guess I'll do something else.




Any suggestions would be appreciated.


Answer



A simple regex for parsing a CSV line, assuming no quotes inside quoted fields, is:



"[^"]*"|[^,]*


Each match will return a field.


html - Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?





function myJsFunc() {
alert("myJsFunc");
}

Run JavaScript Code





or





function myJsFunc() {
alert("myJsFunc");
}

 Run JavaScript Code


mad men - How accurate are the smoking and drinking habits of the characters on Mad Men?

Though the stories and characters have become the focal point for analysis as Mad Men has evolved, early in its existence there was a great deal of discussion regarding the amount of smoking and drinking the characters do. (See this New York Times article from 2007 for one example).


enter image description here


How accurate is this presentation? Is that what the advertising world was like in the 1960s? What about other businesses?


Essentially: is the portrayal of business professional smoking and drinking in excess while at work presented in Mad Men accurate?


Answer


Via Jerry Della Femina, the veteran ad exec widely regarded as one of Madison Avenue's biggest personalities, most creative thinkers and an over-the-top publicity-seeker:



Q: Did ad agency executives really drink that often — and that much — in the 1960s?


A: If anything, it's underplayed. There was a tremendous amount of drinking. Three-martini lunches were the norm.


Q: But the show makes it look like everyone kept a bottle or two in their desk drawer. And it wasn't Geritol.


A: Bottles in desk drawers were not the exception but the rule. I had an open bar at the agency in which I kept 10 to 15 bottles of booze. Anyone at the agency could walk in and get it. Invariably, one or two guys would come in at 9 a.m., pour a shot and slug it down. It was a business of drinking. The way we lived really would make the characters in Mad Men all look like Rebecca of Sunnybrook Farm. We drank and screwed around.


Q: Did agency executives really smoke that much?


A: I smoked three to four packs a day. Everybody smoked at all times in all meetings. Once, when I was sitting in a meeting for the Contac account, I had a (lit) cigarette in my hand and another in the ashtray. When I put down the cigarette to do a chalk talk, I tried to light the piece of chalk.



Source


Sunday, December 30, 2018

mod rewrite - apache mod_rewrite is not working or not enabled



I have installed rewrite_module and modified php.ini on Apache.



I create rewrite.php and .htaccess files, but it's not working.






/var/www/html
/var/www/html/test
/var/www/html/test/.htaccess
/var/www/html/test/rewrite.php




$ cat /var/www/html/test/.htaccess 


RewriteEngine On
RewriteRule ^link([^/]*).html$ rewrite.php?link=$1 [L]




$ cat /var/www/html/test/rewrite.php 




// mod_rewrite Test Page
// Copyright 2006 Webune.com
if($_GET['link']==1){echo"You are not using mod_rewrite";}
elseif($_GET['link']==2){echo"Congratulations!! You are using Apache mod_rewrite";}
else{echo"Linux Apache mod_rewrte Test Tutorial";}
?>






How To Test mod_rewrite in Apache Linux Server


by Webune


LINK1 = rewrite.php?link=1


LINK2 = link2.html


How this works: both links are for this same page, except they both are different. link one is without the mod_rewrite and link2 is using mod_rewrite. Link1 show the php file, with with mod_rewrite we are mascarading the php file into a html file. you can use whatever type of extension you want, you can change it to .htm or .shtml etc... all you have to do is to make sure you also chang it in the .htaccess file


<< Go back to webune forums.









$ ls -l mod_rewrite.so
-rwxr-xr-x 1 root root 59256 Sep 20 23:34 mod_rewrite.so





$ cat /etc/httpd/conf/httpd.conf | grep mod_rewrite.so
LoadModule rewrite_module modules/mod_rewrite.so




$ cat /etc/httpd/conf/httpd.conf

Options Indexes FollowSymLinks


AllowOverride None

Order allow,deny
Allow from all


Answer



Try setting: "AllowOverride All".


excel - Copy and paste to another sheet first empty row, pastes over the previous row if first cell is empty

I'm copying a range from one sheet (B14:I14) and pasting the values to another sheet in the first empty row. This works fine if the range has data in the first cell (B14).


When there is data in some of the cells but not B14, the next time it pastes over the same row as the last time I executed the macro.


The range will vary from having all cells containing data or just two. I need it to check that target row is empty, not just the first cell.


Here is my macro:


Sub Save7()
Dim NextRow As Range
With Sheets("Sheet3")
Set NextRow = .Cells(.Rows.Count, 2).End(xlUp).Offset(1, 0)
End With
Sheet1.Range("B14:I14").Copy
NextRow.PasteSpecial Paste:=xlValues, Transpose:=False
Application.CutCopyMode = False
Set NextRow = Nothing
End Sub

Is there a better way to do optional function parameters in JavaScript?





I've always handled optional parameters in JavaScript like this:



function myFunc(requiredArg, optionalArg){
optionalArg = optionalArg || 'defaultValue';

// Do stuff
}


Is there a better way to do it?




Are there any cases where using || like that is going to fail?


Answer



Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative



if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }


Or an alternative idiom:




optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;


Use whichever idiom communicates the intent best to you!


ios - XCode 6 Playground Measuring Code Performance




Is there any quick way of evaluating the performance / runtime of a certain code part written in the new XCode 6 playground?
I want to start learning Swift by comparing different coding styles for certain solutions and their impact on the code performance.


Answer




We strongly discourage using playgrounds to measure performance, at least using time as your measure of performance. By far the majority of the time taken during a playground is the logging of results to display in the sidebar; the actual time your code takes doesn't contribute as much. So the runtime of your code in a playground will mostly depend on how many lines of code are run / results are logged.



If you want to do performance measurements, check out the XCTest framework. You can create a test bundle for your swift code.



One thing you can measure in a playground is the number of times your lines of code are run. So if, for example, you're trying to measure the algorithmic complexity of some code, you could do that based on how many times it needs to run lines of code to e.g. complete a sort, or whatever it is you're trying to do. Lines of code that are run more than once displays the number of times they are run in the results sidebar.


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

matlab - How to add text in a box with a leader to a plot?

I know how to write text in a plot, but this is a bit more complicated. Below is a rough illustration of how I want my text to be (I did it in plain paint).



Fig:



The desired result




I want to have a little long arrow and a box around the text.

c - How do I apply a structure offset?



I have a structure



typedef struct foo {
int lengthOfArray1;
int lengthOfArray2;
int* array1;
int* array2;

} foo;


I need to allocate enough memory for the entire structure and its array's contents. So assuming each array had a length of 5...



foo* bar = (foo*)malloc(sizeof(foo) + (sizeof(int) * 5) + (sizeof(int) * 5));


I now have to point array1 and array2 to the correct location in that allocated buffer:




bar->array1 = (int*)(&bar->lengthOfArray2 + sizeof(int));
bar->array2 = (int*)(bar->array1 + lengthOfArray2);


Is this correct?



Edit #1



Just to clear up any confusion: I am trying to keep the memory in one block, and not three.




Edit #2



I cannot use C99 as the MSVC 2010 compiler does not support it (http://stackoverflow.com/questions/6688895/does-microsoft-visual-studio-2010-supports-c99).


Answer



Following the OP's approach this should do the job:



/* Defining these types allows to change the types without having the need to modify the code. */
typedef int Foo_ArrayElement1_t;
typedef int Foo_ArrayElement2_t;


typedef struct Foo_s {
size_t lengthOfArray1; /* 'size_t' is the type of choice for array/memory dimensions. */
size_t lengthOfArray2;
Foo_ArrayElement1_t * array1;
Foo_ArrayElement2_t * array2;
} Foo_t;

/*
* Allocates memory to hold a structure of type Foo_t including size for
* 's1' elements referenced by 'array1' and 's2' elements by 'array2'.

* The arrays' elements are set to 0.
*
* Returns a pointer to the freshly allocated memory or NULL if the memory could not
* be allocated.
*/
Foo_t * Foo_CreateAndInit(size_t s1, size_t s2)
{
/* At once allocate all 'Foo_t' (including the memory Foo_t's array pointers shall point to). */
Foo_t * pfoo = calloc(1,
sizeof(*pfoo) +

s1 * sizeof(*(pfoo->array1) +
s2 * sizeof(*(pfoo->array2)));
if (pfoo)
{
pfoo->lengthOfArray1 = s1;
pfoo->lengthOfArray2 = s2;

/* The first array starts right after foo. */
pfoo->array1 = (Foo_ArrayElement1_t *) (pfoo + 1);


/* The second array starts right after s1 elements of where the first array starts. */
pfoo->array2 = (Foo_ArrayElement2_t *) (pfoo->array1 + s1); /* That casting here is not
necessaryas long as 'Foo_t.array1' and 'Foo_t.array2' point to the same type but makes
the code work even if those types were changed to be different. */
}

return pfoo;
}

...


Foo_t * foo = Foo_CreateAndInit(5, 5);

realism - Why didn't the bomb cause a tsunami in Dark Knight Rises? - Movies & TV




As far as I know, even smaller earthquakes measuring 4.2 on the Richter scale in Japan have triggered tsunamis. Was the atom bomb used in The Dark Knight Rises not this powerful?



Answer



First it was 4.2 on Richter scale. 4.2 MW is just unit of energy.



I don't think the bomb would have caused a tsunami though - it may have caused huge waves but they wouldn't have reached Gotham.



The Bomb was capable of destroying 6 mile radius area. So assuming that bomb was dropped 6 miles away from Gotham in the ocean, the water would have absorbed much energy and say the effect would have been reduced by an additional 1 or 2 miles. (The energy is constant, the effect of exploding in water doesn't make a difference)



Also I would like to quote from this article from Geology in Motion:





This means that the power of the tsunami along that shoreline was about 1.3 *10^12, or 1.3 petawatts.




(1 petawatt is 109 MW or (1000000000 MW), easily many times the bombs dropped in Hisroshima and Nagasaki combined.)



And this was the energy of the waves at the coastline in Japan, Just imagine the energy at the point where it was created.



Although I accept the effect of nuclear explosion under water would have been very serious as it would have caused the entire water to get contaminated by nuclear radiation. All marine life would have died in many mile radii and still thousands of people would have been affected.


php - Postfix screwing up email headers!



I've set up a local dev environment on snow leopard, and have set postfix up to send email via my isp mail server.



I eventually got postfix to work after much frustration, but now when my emails send the header information is bunged up!




I'm using the following php code:




$email = "me@mydomain";
$subject = "Email tester";
$body = "Simple test";
$header = "From: me@mydomain \r\n";
$header .= "MIME-VERSION: 1.0\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$phpversion = phpversion();
$header .= "X-Mailer: PHP v$phpversion\r\n";
mail($email,$subject,$body,$header);

echo "message sent!";


The To: and Subject: headers display as they should, in the header!, but the rest display in the email body. This makes the email look like the from field in email client is empty.



I've tried a variety of php scripts, some very simple, but its the same thing, headers always displaying in the email body.




I'm thinking it could be a postfix problem, but not sure, anyone encountered this type of problem before?


Answer



Use PHP_EOL instead of \r\n in *additional_headers*, i.e. $header in your example. PHP_EOL will substitute the newline correspondingly to the OS you are running on.



Also, message should contain LN only i.e. \n. This is accordingly to PHP documentation.
Each line should be separated with a LF (\n). Lines should not be larger than 70 characters.



Make sure you meet both of criterias in your script - I've tried to achieve it and finally got it working with the default configuration of Postfix.


Equivalent of C extern declaration in JavaScript



Writing some JS and would love to enumerate specifically what I'm importing from other files in the main body of my JS script. Is there an equivalent to C's extern declaration for JS?



Thanks!


Answer




Variables declared outside of function scope are global in JavaScript. For example, if you have two JS files and declare a variable 'myObject' in the first file, it will be in scope for the second file, and declared for use if the first file is loaded into the browser already.



If you need access to objects between JS files, it's good practice to expose one object to the global namespace and declare fields and methods on that object.



File 1:



var myObject;
myObject.myField = "Field!";



File 2:



myObject.prototype.myFunction = function () {
return this.myField;
};


Hope this helps, happy to hear other suggestions and open to corrections :D


Jquery success function is not called after executing the rest url

Looking at https://api.jquery.com/trigger, I don't think you can pass a function as the second parameter to the "trigger" method. That argument should be an object or array containing some extra options which are then passed to the event handler function (which should be declared elsewhere). The anonymous function you've defined there runs. Therefore, the normal postback behaviour of the form carries on regardless, and there's no ajax call. That's why you appear to see a response, but don't get the "success" or "error" callbacks triggered - there's never an ajax call in the first place.


What you've done is not the correct way to define an event on an element. The "trigger" method is intended to trigger an event which has already been defined previously. It can't be used to define the event handler itself.


This should work - it creates an event handler for the "submit" event of the form, which suppresses the default postback behaviour and runs the ajax call instead:


$(document).ready(function() {
$("#CreateAttachmentForm").submit(function(event) {
event.preventDefault(); //stop default postback behaviour.
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/uploadFile',
type: 'POST',
data: formData,
success: function (data) {
alert("test");
alert(JSON.stringify(data));
},
error: function(jqXHR, errorThrown, textStatus) {
alert("Ajax error: " + jqXHR.status + " - " + jqXHR.statusText);
console.log(jqXHR.responseText);
},
contentType: false,
processData: false
});
});
});

You can then remove the createAttachmentRequest() function and all references to it.


N.B. This will work as long as whatever is renders an or

javascript - How do I write the result from res.json to a proper json file using node.js?

This is the code snippet. The query returns in json form but how do I write these values in a JSON file?



app.get('/users', function(req, res) {
User.find({}, function(err, docs) {

res.json(docs);

console.error(err);
})
});

shell - Difference between single and double quotes in Bash



In Bash, what are the differences between single quotes ('') and double quotes ("")?


Answer



Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \ escapes, etc.



Example:



$ echo "$(echo "upg")"
upg

$ echo '$(echo "upg")'
$(echo "upg")


The Bash manual has this to say:




3.1.2.2 Single Quotes



Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.




3.1.2.3 Double Quotes



Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.



The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).



Saturday, December 29, 2018

html - Android monospace space ( ) width is different than character width

I'm developing a little webapp.
I tried displaying some output in an sort of ascii art way, using boxdrawing characters.
However, I noticed that on Android the space ( ) isn't equal width with the other characters, leading to ugly output.



I've put the font as monospace and even tried the monospace,monospace CSS setting.



To see what I'm talking about:
Please open https://tpgnow.herokuapp.com/CERN on Android and on a desktop browser.



Expected Output (desktop browser):
enter image description here




Actual Output (android browser):
enter image description here



I've tried different browsers and platforms and devices.
It seems to work on Win, Mac, Chrome and Firefox, also on iOS, but not on Android (neither Chrome nor Firefox).



Does anybody have a solution for this problem?

arrays - Accessing number object in php





I got an object's value in foreach loop which is a number



> array(12) { [0]=> object(stdClass)#34 (22) {
[201609]=> string(6) "130000"
} }



When I try to access $query->201609 getting error




Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$'




I try to access by using $query->{201609} it gives me 0 value instead of 130000




How can I get that attribute?



This question is not duplicate. I've tried the other question's it doesn't help for me because it is in a loop.


Answer



This works in Php 7.2.4 (likely older versions as well):



$property = 201609;
var_dump($query->$property);



Tested like this:



$x = new stdClass();
$p = 123;
$x->$p = 456;
var_dump($x);


Output:




object(stdClass)#3 (1) {
["123"]=>
int(456)
}


Assuming "$query" is an array, not the object in question:



$property = 201609;
var_dump($query[0]->$property);


python - How to fix "Attempted relative import in non-package" even with __init__.py

It depends on how you want to launch your script.



If you want to launch your UnitTest from the command line in a classic way, that is:



python tests/core_test.py


Then, since in this case 'components' and 'tests' are siblings folders, you can import the relative module either using the insert or the append method of the sys.path module.

Something like:



import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from components.core import GameLoopEvents


Otherwise, you can launch your script with the '-m' argument (note that in this case, we are talking about a package, and thus you must not give the '.py' extension), that is:




python -m pkg.tests.core_test


In such a case, you can simply use the relative import as you were doing:



from ..components.core import GameLoopEvents


You can finally mix the two approaches, so that your script will work no matter how it is called.
For example:




if __name__ == '__main__':
if __package__ is None:
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from components.core import GameLoopEvents
else:
from ..components.core import GameLoopEvents

What are the differences between a pointer variable and a reference variable in C++?

I know references are syntactic sugar, so code is easier to read and write.




But what are the differences?

c# - (De-)Serialize Known Types similar to Microsoft

Up to now I've used Microsoft's DataContractJsonSerializer to serialize and deserialize my business objects into data transfer objects (DTO) formatted as JSON.
The DTOs are marked with the DataContract attribute. A small example:



[DataContract(Name = "Geometry", Namespace = "myContract.com/dto")]
[KnownType(typeof(Point))]
[KnownType(typeof(Line))]
public class Geometry
{

}

[DataContract(Name = "Point", Namespace = "myContract.com/dto")]
public class Point : Geometry
{
[DataMember(Name = "x")]
public double X { get; set; }

[DataMember(Name = "y")]
public double Y { get; set; }

}

[DataContract(Name = "Line", Namespace = "myContract.com/dto")]
public class Line: Geometry
{
[DataMember(Name = "start")]
public Point Start { get; set; }

[DataMember(Name = "end")]
public Point End { get; set; }

}


This gets serialized as:



"geometry":{"__type":"Point:myContract.com/dto","x":23133.75569999963,"y":21582.385849999264}


Because of performance issues I switched to Newtonsoft Json.NET. When using this, the JSON strings looks like this:




"geometry":{"$type":"A.B.C.Point, A.B.C","x":23133.75569999963,"y":21582.385849999264}


Is there are possibility to serialize the object with Json.NET into a Microsoft-conform JSON string using "__type" and the contract namespace instead of "$type" and the class-assembly-combination?
I'm using .NET 3.5.



Thanks in advance!

First Steps in Learning C++







I want to be a programmer; and I want to learn the basics of C++. Can anyone give me any pointers on how to start? I'm currently a complete novice and have no programming experience.

c++ - Reading a text document character by character




I am reading a text file character by character using ifstream infile.get() in an infinite while loop.



This sits inside an infinite while loop, and should break out of it once the end of file condition is reached. (EOF). The while loop itself sits within a function of type void.



Here is the pseudo-code:



void function (...) {
while(true) {
...

if ( (ch = infile.get()) == EOF) {return;}
...
}
}


When I "cout" characters on the screen, it goes through all the character and then keeps running outputting what appears as blank space, i.e. it never breaks. I have no idea why. Any ideas?


Answer



In C++, you don't compare the return value with EOF. Instead, you can use a stream function such as good() to check if more data can be read. Something like this:




while (infile.good()) {
ch = infile.get();
// ...
}

css3 - What does the "~" (tilde/squiggle/twiddle) CSS selector mean?




Searching for the ~ character isn't easy. I was looking over some CSS and found this



.check:checked ~ .content {
}


What does it mean?


Answer



The ~ selector is in fact the General sibling combinator (renamed to Subsequent-sibling combinator in selectors Level 4):





The general sibling combinator is made of the "tilde" (U+007E, ~)
character that separates two sequences of simple selectors. The
elements represented by the two sequences share the same parent in the
document tree and the element represented by the first sequence
precedes (not necessarily immediately) the element represented by the
second one.




Consider the following example:






.a ~ .b {
background-color: powderblue;
}


  • 1st

  • 2nd

  • 3rd


  • 4th

  • 5th






.a ~ .b matches the 4th and 5th list item because they:





  • Are .b elements

  • Are siblings of .a

  • Appear after .a in HTML source order.



Likewise, .check:checked ~ .content matches all .content elements that are siblings of .check:checked and appear after it.


html - How do I vertically center text?




I've been working on getting the text in my content div centered vertically and I'm stumped. The container includes 1 div with a title and 1 div with content.



I've tried elements such as:



vertical-align: middle;



and also playing with the displays/positioning, but I'm not having any luck.



The current CSS is the following:



.content-wrapper {
height: 100vh;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;

-ms-flex-pack: center;
justify-content: left;
text-align: left;
-ms-flex-flow: column nowrap;
flex-flow: column nowrap;
color: #000;
font-family: Montserrat;
text-transform: none;
-webkit-transform: translateY(40vh);
transform: translateY(40vh);

will-change: transform;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-transition: all 1.7s cubic-bezier(0.22, 0.44, 0, 1);
transition: all 1.7s cubic-bezier(0.22, 0.44, 0, 1);
padding-top: 10%;
padding-right: 25px;
padding-left: 30px;
float: right;
width: 35%;

background-color: #f0f7fc;
}

Answer





Flexbox allows you to vertically align the text without having a div with a fixed height. It is now supported by all the modern browsers.



Check my other answer to see all the problems and workarounds for Flexbox. The majority are for Internet Explorer.




display: flex;
align-items: center;




div {
width: 50px;
height: 100px;
display: flex;

align-items: center;
border: 1px solid black;
}


Test








If you know the height of the external div, you can use line-height.



height: 100px;
line-height: 100px; /* same value as height */





div {
width: 50px;
height: 100px;
line-height: 100px;
border: 1px solid black;
}


Test








display: table-cell is another good alternative which allows you to vertically align without knowing the height of the div. It works in older browsers too (except Internet Explorer 7).



display: table-cell;
vertical-align: middle;





div {
width: 50px;
height: 100px;
display: table-cell;
vertical-align: middle;
border: 1px solid black;
}



Test




How to interact from python script to .C or .O file?

I want to call a .C or .O file from my python script and execute any of the C program function.
How can I write my script to call a function in C?

php - Setting Up ChromePhp For Wordpress Using Xampp



I found ChromePhp to help with my PHP debugging woahs and installed the related Chrome plugin but I can't seem to get it to work. I originally put it in a folder in my redirected htdocs and added that to my PHP path in php.ini of xampp using:



; Windows: "\path1;\path2"
include_path = ".;C:\xampp\php\PEAR;D:\htdocs\includes"


That didn't seem to work I kept getting errors like the one below whenever I tried to include the file and output a ChromePhp::log("message")





Warning: Cannot modify header information - headers already sent by (output started at D:\htdocs\ask.ca\wp-admin\menu-header.php:91) in D:\htdocs\ask.ca\wp-includes\ChromePhp.php on line 385




So then I tried a similar approach in my windows path, with the same result.



Finally I went completely local and tried to include the ChromePhp.php file into my plugin using:



include( dirname(__FILE__) . '/php/ChromePhp.php' );

ChromePhp::log("Hello World");


But I still get the same error??? Can anyone explain the ABC's of getting ChromePhp to work? I say ABC's since apparently even though I read ChromePhp's website instructions (and couple other peoples in order to get this to work) which are very short and I thought simple, I still need a more Sesame Street explanation.


Answer



I'm the developer of ChromePHP. You are seeing this problem because output has already started on the page. As soon as you echo something out you can no longer set headers.



See this related ticket:
https://github.com/ccampbell/chromephp/issues/15



I'm not sure about the internal workings of Wordpress, but basically you have to either log the information before any output has been sent to the page, or you have to use output buffering to prevent output from being sent and then flush the buffer after you are done logging.




Also:
http://wordpress.org/support/topic/error-cannot-modify-header-information-2


php - Sending Boolean with FormData Javascript - Vuejs + Laravel app

I am trying to submit a FormData javascript Object trough the Axios library and I can't make it work because there a boolean field (is_active) who must go to my api as boolean and the FormData object is converting it to string!



I have tried to make it without FormData and then it goes perfectly!



Any body knows the best way to make it work? Actually I've made a really bad job on my Laravel Request to fix the field... I don't think it's the best idea but it works for now!




Anybody has a good solution for it?



There is my current working code but I would like to make it better!



My controller and my request:



PS: I have made that IF on the $rules function to fixes the boolean issue... If I let it go as string I would have problem with my database where the field must be boolean and I also had to remove my boolean validate on that field



class PostRequest extends FormRequest
{

public function rules()
{
if (in_array($this->get('active'), ['true', 'false'])) {
$this->offsetSet('active', $this->get('active') == 'true');
}

$rules = [
'title' => 'required|string',
'slug' => 'required|alpha_dash|unique:posts,slug',
'photo' => 'required|image',

'publish_date' => 'required|date_format:d/m/Y',
'summary' => 'required',
'content' => 'required',
'author_id' => 'required|exists:authors,id',
'category_id' => 'required|exists:categories,id,flag,posts',
// 'active' => 'boolean',
];

return $rules;
}

}

class PostsController {
public function store(PostRequest $request)
{
try {
$model = new Post($request->all());
$model = $model->save();
} catch (\Exception $e) {
return response()->json($e->getMessage(), 422);

}
return $model;
}
}




There is now my javascript code




PS: I am working with services so my createPost trigger my axios client who makes the request



let data = new FormData()
let record = _.cloneDeep(this.record)

for (var key in record) {
if (record[key] === 'true' || record[key] === 'false')
data.append(key, record[key] === 'true')
else
data.append(key, record[key])

}

return _.isNil(this.record.id) ? createPost(data) : updatePost(data.id, data)

Why can I type alias functions and use them without casting?



In Go, if you define a new type e.g.:



type MyInt int


You can't then pass a MyInt to a function expecting an int, or vice versa:




func test(i MyInt) {
//do something with i
}

func main() {
anInt := 0
test(anInt) //doesn't work, int is not of type MyInt
}



Fine. But why is it then that the same does not apply to functions? e.g.:



type MyFunc func(i int)
func (m MyFunc) Run(i int) {
m(i)
}

func run(f MyFunc, i int) {
f.Run(i)

}

func main() {
var newfunc func(int) //explicit declaration
newfunc = func(i int) {
fmt.Println(i)
}
run(newfunc, 10) //works just fine, even though types seem to differ
}



Now, I'm not complaining because it saves me having to explicitly cast newfunc to type MyFunc, as I would have to do in the first example; it just seems inconsistent. I'm sure there is a good reason for it; can anyone enlighten me?



The reason I ask is mainly because I would like to shorten some of my rather long function types in this way, but I want to make sure it's expected and acceptable to do this :)


Answer



Turns out, this is a misunderstanding that I had about how Go dealt with types, which can be resolved by reading the relevant part of the spec:



http://golang.org/ref/spec#Type_identity



The relevant distinction that I was unaware of was that of named and unnamed types.




Named types are types with a name, such as int, int64, float, string, bool. In addition, any type you create using 'type' is a named type.



Unnamed types are those such as []string, map[string]string, [4]int. They have no name, simply a description corresponding to how they are to be structured.



If you compare two named types, the names must match in order for them to be interchangeable. If you compare a named and an unnamed type, then as long as the underlying representation matches, you're good to go!



e.g. given the following types:



type MyInt int

type MyMap map[int]int
type MySlice []int
type MyFunc func(int)


the following is invalid:



var i int = 2
var i2 MyInt = 4
i = i2 //both named (int and MyInt) and names don't match, so invalid



the following is fine:



is := make([]int)
m := make(map[int]int)
f := func(i int){}

//OK: comparing named and unnamed type, and underlying representation
//is the same:

func doSlice(input MySlice){...}
doSlice(is)

func doMap(input MyMap){...}
doMap(m)

func doFunc(input MyFunc){...}
doFunc(f)



I'm a bit gutted I didn't know that sooner, so I hope that clarifies the type lark a little for someone else! And means much less casting than I at first thought :)


When to use LinkedList over ArrayList in Java?



I've always been one to simply use:



List names = new ArrayList<>();



I use the interface as the type name for portability, so that when I ask questions such as these I can rework my code.



When should LinkedList be used over ArrayList and vice-versa?


Answer



Summary ArrayList with ArrayDeque are preferable in many more use-cases than LinkedList. If you're not sure — just start with ArrayList.






LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically re-sizing array.




As with standard linked list and array operations, the various methods will have different algorithmic runtimes.



For LinkedList




  • get(int index) is O(n) (with n/4 steps on average)

  • add(E element) is O(1)

  • add(int index, E element) is O(n) (with n/4 steps on average),
    but O(1) when index = 0 <--- main benefit of LinkedList

  • remove(int index) is O(n) (with n/4 steps on average)


  • Iterator.remove() is O(1). <--- main benefit of LinkedList

  • ListIterator.add(E element) is O(1) This is one of the main benefits of LinkedList



Note: Many of the operations need n/4 steps on average, constant number of steps in the best case (e.g. index = 0), and n/2 steps in worst case (middle of list)



For ArrayList




  • get(int index) is O(1) <--- main benefit of ArrayList


  • add(E element) is O(1) amortized, but O(n) worst-case since the array must be resized and copied

  • add(int index, E element) is O(n) (with n/2 steps on average)

  • remove(int index) is O(n) (with n/2 steps on average)

  • Iterator.remove() is O(n) (with n/2 steps on average)

  • ListIterator.add(E element) is O(n) (with n/2 steps on average)



Note: Many of the operations need n/2 steps on average, constant number of steps in the best case (end of list), n steps in the worst case (start of list)



LinkedList allows for constant-time insertions or removals using iterators, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but finding a position in the list takes time proportional to the size of the list. Javadoc says "operations that index into the list will traverse the list from the beginning or the end, whichever is closer", so those methods are O(n) (n/4 steps) on average, though O(1) for index = 0.




ArrayList, on the other hand, allow fast random read access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap. Also, if you add more elements than the capacity of the underlying array, a new array (1.5 times the size) is allocated, and the old array is copied to the new one, so adding to an ArrayList is O(n) in the worst case but constant on average.



So depending on the operations you intend to do, you should choose the implementations accordingly. Iterating over either kind of List is practically equally cheap. (Iterating over an ArrayList is technically faster, but unless you're doing something really performance-sensitive, you shouldn't worry about this -- they're both constants.)



The main benefits of using a LinkedList arise when you re-use existing iterators to insert and remove elements. These operations can then be done in O(1) by changing the list locally only. In an array list, the remainder of the array needs to be moved (i.e. copied). On the other side, seeking in a LinkedList means following the links in O(n) (n/2 steps) for worst case, whereas in an ArrayList the desired position can be computed mathematically and accessed in O(1).



Another benefit of using a LinkedList arise when you add or remove from the head of the list, since those operations are O(1), while they are O(n) for ArrayList. Note that ArrayDeque may be a good alternative to LinkedList for adding and removing from the head, but it is not a List.



Also, if you have large lists, keep in mind that memory usage is also different. Each element of a LinkedList has more overhead since pointers to the next and previous elements are also stored. ArrayLists don't have this overhead. However, ArrayLists take up as much memory as is allocated for the capacity, regardless of whether elements have actually been added.




The default initial capacity of an ArrayList is pretty small (10 from Java 1.4 - 1.8). But since the underlying implementation is an array, the array must be resized if you add a lot of elements. To avoid the high cost of resizing when you know you're going to add a lot of elements, construct the ArrayList with a higher initial capacity.


html - CSS Sibling Selector w/ Hover




So here's what I'm trying to do:



I have two icons side by side, and underneath I have two spans that are hidden. When I mouse-over an icon I want the corresponding span to appear.



------------ HTML Part -----------------




  • one

  • two










  • --------------CSS Part --------------



    span.popups span.one,span.popups span.two{opacity:0;


    span.icons:first-child:hover + span.popups span.one{opacity:1}
    span.icons:last-child:hover + span.popups span.two{opacity:1}


    Now obviously this doesn't quite work, how would I go about this using only CSS?



    http://jsfiddle.net/RLhKK/


    Answer



    Let me explain your selector first which is




    span.icons:first-child:hover + span.popups span.one{opacity:1}


    Well, you are trying to select the first-child nested under span.icons and on hover of that you select span.one which is nested inside span.popups but you are going wrong here, you are selecting adjacent span element having .popups which is not adjacent to the span which is nested inside .icons, but in general, your selector is wrong, CSS cannot select the parent, inshort, CSS cannot go back once it enters an element, it cannot move up the hierarchy.



    So you cannot do that way, either you need to alter your DOM, and bring all the span elements at the same level, or your hidden span should be at the child level.



    And another way to achieve this is by using position, which I won't suggest here.




    Also, your markup is invalid, you need to have ul element around li.






    Lets alter the DOM and see how we can select





    • one
      Show Me

    • two
      Show me as well





    .icons li > span {
    opacity: 0;
    }

    .icons li:hover > span {
    opacity: 1;
    }



    Demo






    How would I've achieved this?



    Demo 2





    Hover Me
    First

    Hover Me
    Second



    .icons > div[id] {
    opacity: 0;
    height: 100px;

    width: 100px;
    background: red;
    }

    .icons > span {
    display: block;
    }

    .icons > span:hover + div {
    opacity: 1;

    }





    You can use display or visibilty property as well, if you do not want to use opacity as they are well suited when you want to transit an element using transition.



    Demo 3 (Using transition if you are going for opacity method)


    php - Parse error: syntax error, unexpected 'text' (T_STRING), expecting ',' or ';'




    I am having trouble getting this to work. I have been able to call data from a dropdown menu and place it into a table and have it actively update without reloading the page. I am now trying to get the database information that is called to appear within a text input field or another drop down menu.



    So basically I have a drop down menu that will call up user information, I am trying to get that information that is called to appear within another form so I can update it. Here is the code I am working with;




    table7.php














    Person info will be listed here.







    getuser2.php



    $q = intval($_GET['q']);
    $con=mysqli_connect("localhost","user","password","database");

    // Check connection
    if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }


    $sql="SELECT * FROM users WHERE id = '".$q."'";
    $result1 = mysqli_query($con,$sql);



    echo "




    ";

    echo "";

    while($row1 = mysqli_fetch_array($result1)) {

    echo "";
    echo "";
    echo "";
    echo "";
    echo "";
    }

    echo "";

    echo "
    UsernameE-MailInfo 1
    " . $row1['email'] . "" . $row1['info1'] . "
    ";


    mysqli_close($con);
    ?>


    Within the getuser2.php code if you strip out the form input section and replace it with a call for uname using the format directly below for email and info it will display the data called from the database in standard text format.



    However, I am encountering this error:





    Parse error: syntax error, unexpected 'text' (T_STRING), expecting ',' or ';' in C:\wamp\www\getuser2.php on line 25



    Answer



    The problem is the following:



    echo "";


    You have double quotes inside a double-quoted string. PHP doesn't know where the string ends.




    An easy fix (since you're not using variables inside the string anyway) is to change the double quotes to single quotes:



    echo '';

    c++ - Reading from text file until EOF repeats last line




    The following C++ code uses a ifstream object to read integers from a text file (which has one number per line) until it hits EOF. Why does it read the integer on the last line twice? How to fix this?




    Code:



    #include 
    #include
    using namespace std;

    int main()
    {
    ifstream iFile("input.txt"); // input.txt has integers, one per line


    while (!iFile.eof())
    {
    int x;
    iFile >> x;
    cerr << x << endl;
    }

    return 0;
    }



    input.txt:



    10  
    20
    30


    Output:




    10  
    20
    30
    30


    Note: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).


    Answer



    Just follow closely the chain of events.





    • Grab 10

    • Grab 20

    • Grab 30

    • Grab EOF



    Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.



    Try this:




    while (true) {
    int x;
    iFile >> x;
    if( iFile.eof() ) break;
    cerr << x << endl;
    }


    By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason.



    realism - Could a fire hose really support the weight of a falling man? - Movies & TV



    In the movie Die Hard, near the end, John McClane ties a fire hose around his waist and jumps off the roof of the Nakotomi plaza building.



    Would a fire hose really be able to support the weight of a man of that build at falling speeds?


    Answer



    I suspect the fire hose would survive, but our poor action hero would not.



    From this article:





    So in the Die Hard fall its unlikely to stretch very much. Lets say in
    Bruce's jump a 10m fire hose stretches 1% i.e. 0.1m. Our force formula
    now becomes F = 7900 / 0.1 = 79000 N ... equivalent to the weight of
    about 100 Bruce Willis!



    So what would happen to our action hero? Talking through all this one
    day with the actor and presenter Robert Llewellyn he quite rightly
    reflected "I think there would be a Bruce and somewhere else a

    Willis!"



    mysql - How to alter a column and change the default value?




    I got the following error while trying to alter a column's data type and setting a new default value:



    ALTER TABLE foobar_data ALTER COLUMN col VARCHAR(255) NOT NULL SET DEFAULT '{}';



    ERROR 1064 (42000): 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 'VARCHAR(255) NOT NULL SET DEFAULT '{}'' at line 1




    Answer



    ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}';


    A second possibility which does the same (thanks to juergen_d):



    ALTER TABLE foobar_data CHANGE COLUMN col col VARCHAR(255) NOT NULL DEFAULT '{}';

    Friday, December 28, 2018

    c# - Collection was modified; enumeration operation may not execute



    I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur. Below is the code.



    This is a WCF server in a Windows service. The method NotifySubscribers is called by the service whenever there is a data event (at random intervals, but not very often - about 800 times per day).




    When a Windows Forms client subscribes, the subscriber ID is added to the subscribers dictionary, and when the client unsubscribes, it is deleted from the dictionary. The error happens when (or after) a client unsubscribes. It appears that the next time the NotifySubscribers() method is called, the foreach() loop fails with the error in the subject line. The method writes the error into the application log as shown in the code below. When a debugger is attached and a client unsubscribes, the code executes fine.



    Do you see a problem with this code? Do I need to make the dictionary thread-safe?



    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class SubscriptionServer : ISubscriptionServer
    {
    private static IDictionary subscribers;

    public SubscriptionServer()

    {
    subscribers = new Dictionary();
    }

    public void NotifySubscribers(DataRecord sr)
    {
    foreach(Subscriber s in subscribers.Values)
    {
    try
    {

    s.Callback.SignalData(sr);
    }
    catch (Exception e)
    {
    DCS.WriteToApplicationLog(e.Message,
    System.Diagnostics.EventLogEntryType.Error);

    UnsubscribeEvent(s.ClientId);
    }
    }

    }


    public Guid SubscribeEvent(string clientDescription)
    {
    Subscriber subscriber = new Subscriber();
    subscriber.Callback = OperationContext.Current.
    GetCallbackChannel();

    subscribers.Add(subscriber.ClientId, subscriber);


    return subscriber.ClientId;
    }


    public void UnsubscribeEvent(Guid clientId)
    {
    try
    {
    subscribers.Remove(clientId);

    }
    catch(Exception e)
    {
    System.Diagnostics.Debug.WriteLine("Unsubscribe Error " +
    e.Message);
    }
    }
    }

    Answer




    What's likely happening is that SignalData is indirectly changing the subscribers dictionary under the hood during the loop and leading to that message. You can verify this by changing



    foreach(Subscriber s in subscribers.Values)


    To



    foreach(Subscriber s in subscribers.Values.ToList())



    If I'm right, the problem will dissapear



    Calling subscribers.Values.ToList() copies the values of subscribers.Values to a separate list at the start of the foreach. Nothing else has access to this list (it doesn't even have a variable name!), so nothing can modify it inside the loop.


    design patterns - What is dependency injection?



    There have been several questions already posted with specific questions about dependency injection, such as when to use it and what frameworks are there for it. However,



    What is dependency injection and when/why should or shouldn't it be used?


    Answer



    Dependency Injection is passing dependency to other objects or framework( dependency injector).




    Dependency injection makes testing easier. The injection can be done through constructor.



    SomeClass() has its constructor as following:





    public SomeClass() {
    myObject = Factory.getObject();
    }



    Problem:
    If myObject involves complex tasks such as disk access or network access, it is hard to do unit test on SomeClass(). Programmers have to mock myObject and might intercept the factory call.



    Alternative solution:




    • Passing myObject in as an argument to the constructor






    public SomeClass (MyClass myObject) {
    this.myObject = myObject;
    }


    myObject can be passed directly which makes testing easier.





    • One common alternative is defining a do-nothing constructor. Dependency injection can be done through setters. (h/t @MikeVella).

    • Martin Fowler documents a third alternative (h/t @MarcDix), where classes explicitly implement an interface for the dependencies programmers wish injected.



    It is harder to isolate components in unit testing without dependency injection.



    In 2013, when I wrote this answer, this was a major theme on the Google Testing Blog. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.


    Pre & post increment operator behavior in C, C++, Java, & C#




    DISCLAIMER: This is not a real-world example. It is just a theoretical question of how these languages work.



    What exactly are the differences between C/C++, C#, and Java when it comes to post & pre increment operators?



    This is what I get with VC++10, Java 1.6, and C# 4




    int a = 2;
    int b = a++ + a++;
    int c = ++a + a++ + a++;

    +-----+------+------+----+
    | C | C++ | Java | C# |
    +-----+-----+------+------+----+
    | a | 7 | 7 | 7 | 7 |
    +-----+-----+------+------+----+

    | b | 4 | 4 | 5 | 5 |
    +-----+-----+------+------+----+
    | c | 15 | 15 | 16 | 16 |
    +-----+-----+------+------+----+

    Answer



    Java and C# evaluate expressions from left to right, and the side-effects are visible immediately.



    In C++, the order of evaluation of subexpressions is unspecified, and modifying the same object twice without an intervening sequence point is undefined behavior.


    exception - Why should I not wrap every block in "try"-"catch"?



    I have always been of the belief that if a method can throw an exception then it is reckless not to protect this call with a meaningful try block.




    I just posted 'You should ALWAYS wrap calls that can throw in try, catch blocks.' to this question and was told that it was 'remarkably bad advice' - I'd like to understand why.


    Answer



    A method should only catch an exception when it can handle it in some sensible way.



    Otherwise, pass it on up, in the hope that a method higher up the call stack can make sense of it.



    As others have noted, it is good practice to have an unhandled exception handler (with logging) at the highest level of the call stack to ensure that any fatal errors are logged.


    How do I send a file as an email attachment using Linux command line?



    I've created a script that runs every night on my Linux server that uses mysqldump to back up each of my MySQL databases to .sql files and packages them together as a compressed .tar file. The next step I want to accomplish is to send that tar file through email to a remote email server for safekeeping. I've been able to send the raw script in the body an email by piping the backup text file to mailx like so:



    $ cat mysqldbbackup.sql | mailx backup@email.com



    cat echoes the backup file's text which is piped into the mailx program with the recipient's email address passed as an argument.



    While this accomplishes what I need, I think it could be one step better, Is there any way, using shell scripts or otherwise, to send the compressed .tar file to an outgoing email message as an attachment? This would beat having to deal with very long email messages which contain header data and often have word-wrapping issues etc.


    Answer



    None of the mutt ones worked for me. It was thinking the email address was part of the attachemnt. Had to do:



    echo "This is the message body" | mutt -a "/path/to/file.to.attach" -s "subject of message" -- recipient@domain.com

    java - Both next() and nextLine() not helping to store name with spacing



    I am currently using a Scanner to record the user input which is a String and print it out. If the user input is a single name such as Alan, it works fine. If I enter a name with spacing such as Alan Smith, it returns an error saying InputMisMatchException.



    I read around similar cases here and they advised to use nextLine() instead of next(). It made sense but that doesn't work for me either. When I use a nextLine(), it immediately skips the step where I enter the name and goes back to the starting of the loop asking me to input choice again. Please advice how I can correct this. Thank you.



    import java.io.IOException;
    import java.util.Scanner;


    public class ScannerTest {
    static String name;
    static Scanner in = new Scanner(System.in);
    static int choice;

    public static void main(String[] args) {
    while(choice != 5){
    System.out.print("\nEnter Choice :> ");
    choice = in.nextInt();


    if(choice == 1){
    try{
    printName();
    }
    catch(IOException e){
    System.out.println("IO Exception");
    }
    }
    }
    }

    private static void printName()throws IOException{
    System.out.print("\nEnter name :> ");
    name = in.next();
    //name = in.nextLine();
    if (name != null){
    System.out.println(name);
    }
    }
    }


    Answer



    Try this instead: add name = in.nextLine(); after choice = in.nextInt();.



    Then try replacing name = in.next(); with name = in.nextLine();



    Explanation: After the scanner calls nextInt() it gets the first value and leaves the rest of the string to the \n. We then consume the rest of the string with nextLine().



    The second nextLine() is then used to get your string parameters.


    java - How to measure time elapsed, immune to system time server automatic updates

    My servers and desktops are configured to automatically adjust their time via network ntp time servers.



    This means that if I use the easy method beginDate.getTime()-new Date().getTime(), there is a chance I'm not getting an accurate number of elapsed milliseconds.




    How can I write code that is immune to system clock updates and leap second adjustments?

    python - Saving utf-8 texts in json.dumps as UTF8, not as u escape sequence



    sample code:



    >>> import json
    >>> json_string = json.dumps("ברי צקלה")
    >>> print json_string

    "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"


    The problem: it's not human readable. My (smart) users want to verify or even edit text files with JSON dumps (and I’d rather not use XML).



    Is there a way to serialize objects into UTF-8 JSON strings (instead of \uXXXX)?


    Answer



    Use the ensure_ascii=False switch to json.dumps(), then encode the value to UTF-8 manually:



    >>> json_string = json.dumps("ברי צקלה", ensure_ascii=False).encode('utf8')

    >>> json_string
    b'"\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94"'
    >>> print(json_string.decode())
    "ברי צקלה"


    If you are writing to a file, just use json.dump() and leave it to the file object to encode:



    with open('filename', 'w', encoding='utf8') as json_file:
    json.dump("ברי צקלה", json_file, ensure_ascii=False)



    Caveats for Python 2



    For Python 2, there are some more caveats to take into account. If you are writing this to a file, you can use io.open() instead of open() to produce a file object that encodes Unicode values for you as you write, then use json.dump() instead to write to that file:



    with io.open('filename', 'w', encoding='utf8') as json_file:
    json.dump(u"ברי צקלה", json_file, ensure_ascii=False)



    Do note that there is a bug in the json module where the ensure_ascii=False flag can produce a mix of unicode and str objects. The workaround for Python 2 then is:



    with io.open('filename', 'w', encoding='utf8') as json_file:
    data = json.dumps(u"ברי צקלה", ensure_ascii=False)
    # unicode(data) auto-decodes data to unicode if str
    json_file.write(unicode(data))


    In Python 2, when using byte strings (type str), encoded to UTF-8, make sure to also set the encoding keyword:




    >>> d={ 1: "ברי צקלה", 2: u"ברי צקלה" }
    >>> d
    {1: '\xd7\x91\xd7\xa8\xd7\x99 \xd7\xa6\xd7\xa7\xd7\x9c\xd7\x94', 2: u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'}

    >>> s=json.dumps(d, ensure_ascii=False, encoding='utf8')
    >>> s
    u'{"1": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4", "2": "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"}'
    >>> json.loads(s)['1']
    u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
    >>> json.loads(s)['2']

    u'\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4'
    >>> print json.loads(s)['1']
    ברי צקלה
    >>> print json.loads(s)['2']
    ברי צקלה

    Regex Group in Perl: how to capture elements into array from regex group that matches unknown number of/multiple/variable occurrences from a string?



    In Perl, how can I use one regex grouping to capture more than one occurrence that matches it, into several array elements?



    For example, for a string:




    var1=100 var2=90 var5=hello var3="a, b, c" var7=test var3=hello


    to process this with code:



    $string = "var1=100 var2=90 var5=hello var3=\"a, b, c\" var7=test var3=hello";

    my @array = $string =~

    for ( my $i = 0; $i < scalar( @array ); $i++ )

    {
    print $i.": ".$array[$i]."\n";
    }


    I would like to see as output:



    0: var1=100
    1: var2=90
    2: var5=hello

    3: var3="a, b, c"
    4: var7=test
    5: var3=hello


    What would I use as a regex?



    The commonality between things I want to match here is an assignment string pattern, so something like:



    my @array = $string =~ m/(\w+=[\w\"\,\s]+)*/;



    Where the * indicates one or more occurrences matching the group.



    (I discounted using a split() as some matches contain spaces within themselves (i.e. var3...) and would therefore not give desired results.)



    With the above regex, I only get:



    0: var1=100 var2



    Is it possible in a regex? Or addition code required?



    Looked at existing answers already, when searching for "perl regex multiple group" but not enough clues:




    Answer



    my $string = "var1=100 var2=90 var5=hello var3=\"a, b, c\" var7=test var3=hello";

    while($string =~ /(?:^|\s+)(\S+)\s*=\s*("[^"]*"|\S*)/g) {

    print "<$1> => <$2>\n";
    }


    Prints:



     => <100>
    => <90>
    =>
    => <"a, b, c">

    =>
    =>


    Explanation:



    Last piece first: the g flag at the end means that you can apply the regex to the string multiple times. The second time it will continue matching where the last match ended in the string.



    Now for the regex: (?:^|\s+) matches either the beginning of the string or a group of one or more spaces. This is needed so when the regex is applied next time, we will skip the spaces between the key/value pairs. The ?: means that the parentheses content won't be captured as group (we don't need the spaces, only key and value). \S+ matches the variable name. Then we skip any amount of spaces and an equal sign in between. Finally, ("[^"]*"|\S*)/ matches either two quotes with any amount of characters in between, or any amount of non-space characters for the value. Note that the quote matching is pretty fragile and won't handle escpaped quotes properly, e.g. "\"quoted\"" would result in "\".




    EDIT:



    Since you really want to get the whole assignment, and not the single keys/values, here's a one-liner that extracts those:



    my @list = $string =~ /(?:^|\s+)((?:\S+)\s*=\s*(?:"[^"]*"|\S*))/g;

    How to sort array by date In JavaScript?




    I have a problem to sort arrays that are in an array object by date.



    I have an array object as below.




    [
    {
    "name": "February",
    "plantingDate": "2018-02-04T17:00:00.000Z",
    },
    {
    "name": "March",
    "plantingDate": "2018-03-04T17:00:00.000Z",
    },

    {
    "name": "January",
    "plantingDate": "2018-01-17T17:00:00.000Z",
    }
    ]


    How to sort the array in the array object from January to December, as below.



    [

    {
    "name": "January",
    "plantingDate": "2018-01-17T17:00:00.000Z",
    },
    {
    "name": "February",
    "plantingDate": "2018-02-04T17:00:00.000Z",
    },
    {
    "name": "March",

    "plantingDate": "2018-03-04T17:00:00.000Z",
    }
    ]


    I beg for help.



    Thank you in advance.


    Answer



    Parse strings to get Date objects, then sort by compare function.






    var a = [
    {
    "name": "February",
    "plantingDate": "2018-02-04T17:00:00.000Z",
    },
    {
    "name": "March",

    "plantingDate": "2018-03-04T17:00:00.000Z",
    },
    {
    "name": "January",
    "plantingDate": "2018-01-17T17:00:00.000Z",
    }
    ]

    a.sort(function(a,b){
    return new Date(a.plantingDate) - new Date(b.plantingDate)

    })

    console.log(a)





    As Barmar commented,



    a.sort(function(a,b){

    return a.plantingDate > b.plantingDate;
    })


    will also gonna work.


    plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; 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 parti...