Programs & Examples On #Acceptance testing

Acceptance testing is a test conducted to determine if the requirements of a specification or contract are met

Difference between acceptance test and functional test?

Acceptance testing is just testing carried out by the client, and includes other kinds of testing:

• Functional testing: "this button doesn't work"

For functional testing vs non-functional testing (their subtypes) - see my answer to this SO question.

How to calculate growth with a positive and negative number?

You could try shifting the number space upward so they both become positive.

To calculate a gain between any two positive or negative numbers, you're going to have to keep one foot in the magnitude-growth world and the other foot in the volume-growth world. You can lean to one side or the other depending on how you want the result gains to appear, and there are consequences to each choice.

Strategy

1. Create a shift equation that generates a positive number relative to the old and new numbers.

2. Add the custom shift to the old and new numbers to get new_shifted and old_shifted.

3. Take the (new_shifted - old_shifted) / old_shifted) calculation to get the gain.

For example:

``````old -> new
-50 -> 30               //Calculate a shift like (2*(50 + 30)) = 160

shifted_old -> shifted_new
110         ->  190

= (new-old)/old
= (190-110)/110 = 72.73%
``````

How to choose a shift function

If your shift function shifts the numbers too far upward, like for example adding 10000 to each number, you always get a tiny growth/decline. But if the shift is just big enough to get both numbers into positive territory, you'll get wild swings in the growth/decline on edge cases. You'll need to dial in the shift function so it makes sense for your particular application. There is no totally correct solution to this problem, you must take the bitter with the sweet.

``````                           shift function
old new  abs_old  abs_new  2*abs(old)+abs(new)   shiftedold  shiftednew    gain
-50  30  50          30          160                110         190        72.73%
-50  40  50          40          180                130         220        69.23%
10   20  10          20          60                 70          80         14.29%
10   30  10          30          80                 90          110        22.22%
1    10  1           10          22                 23          32         39.13%
1    20  1           20          42                 43          62         44.19%
-10  10  10          10          40                 30          50         66.67%
-10  20  10          20          60                 50          80         60.00%
1    100  1          100         202                203         302        48.77%
1    1000 1          1000        2002               2003        3002       49.88%
``````

The gain percentage is affected by the magnitude of the numbers. The numbers above are a bad example and result from a primitive shift function.

You have to ask yourself which critter has the most productive gain:

``````Evaluate the growth of critters A, B, C, and D:
A used to consume 0.01 units of energy and now consumes 10 units.
B used to consume 500 units and now consumes 700 units.
C used to consume -50 units (Producing units!) and now consumes 30 units.
D used to consume -0.01 units (Producing) and now consumes -30 units (producing).
``````

In some ways arguments can be made that each critter is the biggest grower in their own way. Some people say B is best grower, others will say D is a bigger gain. You have to decide for yourself which is better.

The question becomes, can we map this intuitive feel of what we label as growth into a continuous function that tells us what humans tend to regard as "awesome growth" vs "mediocre growth".

Growth a mysterious thing

You then have to take into account that Critter B may have had a far more difficult time than critter D. Critter D may have far more prospects for it in the future than the others. It had an advantage! How do you measure the `opportunity`, `difficulty`, `velocity` and `acceleration` of growth? To be able to predict the future, you need to have an intuitive feel for what constitutes a "major home run" and a "lame advance in productivity".

The first and second derivatives of a function will give you the "velocity of growth" and "acceleration of growth". Learn about those in calculus, they are super important.

Which is growing more? A critter that is accelerating its growth minute by minute, or a critter that is decelerating its growth? What about high and low velocity and high/low rate of change? What about the notion of exhausting opportunities for growth. Cost benefit analysis and ability/inability to capitalize on opportunity. What about adversarial systems (where your success comes from another person's failure) and zero sum games?

There is exponential growth, liner growth. And unsustainable growth. Cost benefit analysis and fitting a curve to the data. The world is far queerer than we can suppose. Plotting a perfect line to the data does not tell you which data point comes next because of the black swan effect. I suggest all humans listen to this lecture on growth, the University of Colorado At Boulder gave a fantastic talk on growth, what it is, what it isn't, and how humans completely misunderstand it. http://www.youtube.com/watch?v=u5iFESMAU58

Fit a line to the temperature of heated water, once you think you've fit a curve, a black swan happens, and the water boils. This effect happens all throughout our universe, and your primitive function (new-old)/old is not going to help you.

Here is Java code that accomplishes most of the above notions in a neat package that suits my needs:

Critter growth - (a critter can be "radio waves", "beetles", "oil temprature", "stock options", anything).

``````public double evaluate_critter_growth_return_a_gain_percentage(
double old_value, double new_value) throws Exception{

double abs_old = Math.abs(old_value);
double abs_new = Math.abs(new_value);

//This is your shift function, fool around with it and see how
//It changes.  Have a full battery of unit tests though before you fiddle.
double biggest_absolute_value = (Math.max(abs_old, abs_new)+1)*2;

if (new_value <= 0 || old_value <= 0){
new_value = new_value + (biggest_absolute_value+1);
old_value = old_value + (biggest_absolute_value+1);
}

if (old_value == 0 || new_value == 0){
old_value+=1;
new_value+=1;
}

if (old_value <= 0)
throw new Exception("This should never happen.");

if (new_value <= 0)
throw new Exception("This should never happen.");

return (new_value - old_value) / old_value;

}
``````

Result

It behaves kind-of sort-of like humans have an instinctual feel for critter growth. When our bank account goes from -9000 to -3000, we say that is better growth than when the account goes from 1000 to 2000.

``````1->2     (1.0)  should be bigger than   1->1 (0.0)
1->2     (1.0)  should be smaller than  1->4 (3.0)
0->1     (0.2)  should be smaller than  1->3 (2.0)
-5-> -3  (0.25) should be smaller than -5->-1 (0.5)
-5->1    (0.75) should be smaller than -5->5 (1.25)
100->200 (1.0)  should be the same as  10->20 (1.0)
-10->1   (0.84) should be smaller than -20->1 (0.91)
-10->10  (1.53) should be smaller than -20->20 (1.73)
-200->200 should not be in outer space (say more than 500%):(1.97)
handle edge case 1-> -4: (-0.41)
1-> -4:  (-0.42) should be bigger than 1-> -9:(-0.45)
``````

If my shift function makes sense for your needs, use it. Be sure to battle test this, if you crash the space shuttle its totally NOT my fault. This method is a heuristic.

Exit from app when click button in android phonegap?

``````if(navigator.app){
navigator.app.exitApp();
}else if(navigator.device){
navigator.device.exitApp();
}
``````

How to select first child with jQuery?

As @Roko mentioned you can do this in multiple ways.

1.Using the jQuery first-child selector - SnoopCode

``````   \$(document).ready(function(){
\$(".alldivs onediv:first-child").css("background-color","yellow");
}
``````
1. `````` \$( "body" ).find( "onediv" ).eq(1).addClass( "red" );
``````
2. ``````   \$(document).ready(function(){
\$("#div1").css("background-color: red;");
});
``````

How can I pretty-print JSON using Go?

I was frustrated by the lack of a fast, high quality way to marshal JSON to a colorized string in Go so I wrote my own Marshaller called ColorJSON.

With it, you can easily produce output like this using very little code:

``````package main

import (
"fmt"
"encoding/json"

"github.com/TylerBrock/colorjson"
)

func main() {
str := `{
"str": "foo",
"num": 100,
"bool": false,
"null": null,
"array": ["foo", "bar", "baz"],
"obj": { "a": 1, "b": 2 }
}`

var obj map[string]interface{}
json.Unmarshal([]byte(str), &obj)

// Make a custom formatter with indent set
f := colorjson.NewFormatter()
f.Indent = 4

// Marshall the Colorized JSON
s, _ := f.Marshal(obj)
fmt.Println(string(s))
}
``````

I'm writing the documentation for it now but I was excited to share my solution.

What does the "\$" sign mean in jQuery or JavaScript?

In jQuery, the \$ sign is just an alias to `jQuery()`, then an alias to a function.

Basic syntax is: \$(selector).action()

• A dollar sign to define jQuery
• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)

Anaconda vs. miniconda

The `2` in `Anaconda2` means that the main version of Python will be 2.x rather than the 3.x installed in `Anaconda3`. The current release has Python 2.7.13.

The `4.4.0.1` is the version number of Anaconda. The current advertised version is `4.4.0` and I assume the `.1` is a minor release or for other similar use. The Windows releases, which I use, just say `4.4.0` in the file name.

Others have now explained the difference between Anaconda and Miniconda, so I'll skip that.

Assigning multiple styles on an HTML element

The way you have used the HTML syntax is problematic.

This is how the syntax should be

``````style="property1:value1;property2:value2"
``````

In your case, this will be the way to do

``````<h2 style="text-align :center; font-family :tahoma" >TITLE</h2>
``````

A further example would be as follows

``````<div class ="row">
<button type="button" style= "margin-top : 20px; border-radius: 15px"
class="btn btn-primary">View Full Profile</button>
</div>
``````

No 'Access-Control-Allow-Origin' header is present on the requested resource error

Try this - set Ajax call by setting up the header as follows:

``````var uri = "http://localhost:50869/odata/mydatafeeds"
\$.ajax({
url: uri,
beforeSend: function (request) {
},
async: true,
success: function (data) {
},
error: function (xhr, textStatus, errorMessage) {
}
});
``````

Then run your code by opening Chrome with the following command line:

``````chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
``````

"Cannot instantiate the type..."

You are trying to instantiate an interface, you need to give the concrete class that you want to use i.e. `Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();`.

Rename a file in C#

Use:

``````int rename(const char * oldname, const char * newname);
``````

The rename() function is defined in the stdio.h header file. It renames a file or directory from oldname to newname. The rename operation is the same as move, hence you can also use this function to move a file.

Print a div content using Jquery

I tried all the non-plugin approaches here, but all caused blank pages to print after the content, or had other problems. Here's my solution:

Html:

``````<body>
<div id="page-content">
<div id="printme">Content To Print</div>
<div>Don't print this.</div>
</div>
<div id="hidden-print-div"></div>
</body>
``````

Jquery:

``````    \$(document).ready(function () {
\$("#hidden-print-div").html(\$("#printme").html());
});
``````

Css:

``````    #hidden-print-div {
display: none;
}

@media print {
#hidden-print-div {
display: block;
}

#page-content {
display: none;
}
}
``````

failed to find target with hash string 'android-22'

Okay you must try this guys it works for me:

1. Open SDK Manager and Install SDK build tools 22.0.1

How do you show animated GIFs on a Windows Form (c#)

I had the same issue and came across different solutions by implementing which I used to face several different issues. Finally, below is what I put some pieces from different posts together which worked for me as expected.

``````private void btnCompare_Click(object sender, EventArgs e)
{
}
``````

Here is the Execution method that also carries invoking the PictureBox control:

``````private void Execution()
{
btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = true; });
Application.DoEvents();

// Your main code comes here . . .

btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = false; });
}
``````

Keep in mind, the PictureBox is invisible from Properties Window or do below:

``````private void ComparerForm_Load(object sender, EventArgs e)
{
pictureBox1.Visible = false;
}
``````

ERROR! MySQL manager or server PID file could not be found! QNAP

I ended up figuring this out on my own.

In searching for my logs I went into

``````cd /usr/local/mysql/var
``````

In there I found the file named [MyNAS].pid (replace [MyNAS] with the name of your NAS.

I then ran the following to remove the file

``````rm -rf /usr/local/mysql/var/[MyNAS].pid
``````

I then restarted mysql

``````[/usr/local/mysql/var] # /etc/init.d/mysqld.sh restart
/mnt/ext/opt/mysql
/mnt/ext/opt/mysql
Try to shutting down MySQL
ERROR! MySQL manager or server PID file could not be found!
/mnt/ext/opt/mysql
Starting MySQL. SUCCESS!
``````

I tested everything and it all works like a charm again!

How can I get javascript to read from a .json file?

Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal; E.g.

_x000D_
_x000D_
``````window.portalData = [_x000D_
{_x000D_
"kpi" : "NDAR",_x000D_
"data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]_x000D_
},_x000D_
{_x000D_
"kpi" : "NTI",_x000D_
"data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]_x000D_
},_x000D_
{_x000D_
"kpi" : "BS",_x000D_
"data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]_x000D_
},_x000D_
{_x000D_
"kpi" : "SISS",_x000D_
"data" :  [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]_x000D_
},_x000D_
{_x000D_
"kpi" : "MID",_x000D_
"data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]_x000D_
}_x000D_
];``````
_x000D_
_x000D_
_x000D_

You can then do the following in your HTML

``````<script src="server_data.js"> </script>

function getServerData(kpiCode)
{
var elem = \$(window.portalData).filter(function(idx){
return window.portalData[idx].kpi == kpiCode;
});

return elem[0].data;
};

var defData = getServerData('NDAR');
``````

Why do we use Base64?

Media that is designed for textual data is of course eventually binary as well, but textual media often use certain binary values for control characters. Also, textual media may reject certain binary values as non-text.

Base64 encoding encodes binary data as values that can only be interpreted as text in textual media, and is free of any special characters and/or control characters, so that the data will be preserved across textual media as well.

Vue.js: Conditional class style binding

Use the object syntax.

``````v-bind:class="{'fa-checkbox-marked': content['cravings'],  'fa-checkbox-blank-outline': !content['cravings']}"
``````

When the object gets more complicated, extract it into a method.

``````v-bind:class="getClass()"

methods:{
getClass(){
return {
'fa-checkbox-marked': this.content['cravings'],
'fa-checkbox-blank-outline': !this.content['cravings']}
}
}
``````

Finally, you could make this work for any content property like this.

``````v-bind:class="getClass('cravings')"

methods:{
getClass(property){
return {
'fa-checkbox-marked': this.content[property],
'fa-checkbox-blank-outline': !this.content[property]
}
}
}
``````

Fastest way to determine if an integer's square root is an integer

This a rework from decimal to binary of the old Marchant calculator algorithm (sorry, I don't have a reference), in Ruby, adapted specifically for this question:

``````def isexactsqrt(v)
value = v.abs
residue = value
root = 0
onebit = 1
onebit <<= 8 while (onebit < residue)
onebit >>= 2 while (onebit > residue)
while (onebit > 0)
x = root + onebit
if (residue >= x) then
residue -= x
root = x + onebit
end
root >>= 1
onebit >>= 2
end
return (residue == 0)
end
``````

Here's a workup of something similar (please don't vote me down for coding style/smells or clunky O/O - it's the algorithm that counts, and C++ is not my home language). In this case, we're looking for residue == 0:

``````#include <iostream>

using namespace std;
typedef unsigned long long int llint;

class ISqrt {           // Integer Square Root
llint value;        // Integer whose square root is required
llint root;         // Result: floor(sqrt(value))
llint residue;      // Result: value-root*root
llint onebit, x;    // Working bit, working value

public:

ISqrt(llint v = 2) {    // Constructor
Root(v);            // Take the root
};

llint Root(llint r) {   // Resets and calculates new square root
value = r;          // Store input
residue = value;    // Initialise for subtracting down
root = 0;           // Clear root accumulator

onebit = 1;                 // Calculate start value of counter
onebit <<= (8*sizeof(llint)-2);         // Set up counter bit as greatest odd power of 2
while (onebit > residue) {onebit >>= 2; };  // Shift down until just < value

while (onebit > 0) {
x = root ^ onebit;          // Will check root+1bit (root bit corresponding to onebit is always zero)
if (residue >= x) {         // Room to subtract?
residue -= x;           // Yes - deduct from residue
root = x + onebit;      // and step root
};
root >>= 1;
onebit >>= 2;
};
return root;
};
llint Residue() {           // Returns residue from last calculation
return residue;
};
};

int main() {
llint big, i, q, r, v, delta;
big = 0; big = (big-1);         // Kludge for "big number"
ISqrt b;                            // Make q sqrt generator
for ( i = big; i > 0 ; i /= 7 ) {   // for several numbers
q = b.Root(i);                  // Get the square root
r = b.Residue();                // Get the residue
v = q*q+r;                      // Recalc original value
delta = v-i;                    // And diff, hopefully 0
cout << i << ": " << q << " ++ " << r << " V: " << v << " Delta: " << delta << "\n";
};
return 0;
};
``````

Example of a strong and weak entity types

Weak Entity Type: An entity whose instances cannot exits without being linked with instances of some other entity is called weak entity type. It cannot exist independently. For example: Our PC is depend on us it will not open or close with its own.

Strong Entity Type: An entity whose linked to the instances of any other entity type is called strong entity type. It can exit independently. For example: A person can do every thing can go everywhere and use ever thing

How can I clear the SQL Server query cache?

``````EXEC sys.sp_configure N'max server memory (MB)', N'2147483646'
GO
RECONFIGURE WITH OVERRIDE
GO
``````

What value you specify for the server memory is not important, as long as it differs from the current one.

Btw, the thing that causes the speedup is not the query cache, but the data cache.

Best way to do multiple constructors in PHP

This is my take on it (build for php 5.6).

It will look at constructor parameter types (array, class name, no description) and compare the given arguments. Constructors must be given with least specificity last. With examples:

``````// demo class
class X {
public \$X;

public function __construct(\$x) {
\$this->X = \$x;
}

public function __toString() {
return 'X'.\$this->X;
}
}

// demo class
class Y {
public \$Y;

public function __construct(\$y) {
\$this->Y = \$y;
}
public function __toString() {
return 'Y'.\$this->Y;
}
}

// here be magic
abstract class MultipleConstructors {
function __construct() {
\$__get_arguments       = func_get_args();
\$__number_of_arguments = func_num_args();

\$__reflect = new ReflectionClass(\$this);
foreach(\$__reflect->getMethods() as \$__reflectmethod) {
\$__method_name = \$__reflectmethod->getName();
if (substr(\$__method_name, 0, strlen('__construct')) === '__construct') {
\$__parms = \$__reflectmethod->getParameters();
if (count(\$__parms) == \$__number_of_arguments) {
\$__argsFit = true;
foreach (\$__parms as \$__argPos => \$__param) {
\$__paramClass= \$__param->getClass();
\$__argVar = func_get_arg(\$__argPos);
\$__argVarType = gettype(\$__argVar);
\$__paramIsArray = \$__param->isArray() == true;
\$__argVarIsArray = \$__argVarType == 'array';
// parameter is array and argument isn't, or the other way around.
if ((\$__paramIsArray && !\$__argVarIsArray) ||
(!\$__paramIsArray && \$__argVarIsArray)) {
\$__argsFit = false;
continue;
}
// class check
if ((!is_null(\$__paramClass) && \$__argVarType != 'object') ||
(is_null(\$__paramClass) && \$__argVarType == 'object')){
\$__argsFit = false;
continue;
}
if (!is_null(\$__paramClass) && \$__argVarType == 'object') {
// class type check
\$__paramClassName = "N/A";
if (\$__paramClass)
\$__paramClassName = \$__paramClass->getName();
if (\$__paramClassName != get_class(\$__argVar)) {
\$__argsFit = false;
}
}
}
if (\$__argsFit) {
call_user_func_array(array(\$this, \$__method_name), \$__get_arguments);
return;
}
}
}
}
throw new Exception("No matching constructors");
}
}

// how to use multiple constructors
class A extends MultipleConstructors {
public \$value;

function __constructB(array \$hey) {
\$this->value = 'Array#'.count(\$hey).'<br/>';
}
function __construct1(X \$first) {
\$this->value = \$first .'<br/>';
}

function __construct2(Y \$second) {
\$this->value = \$second .'<br/>';
}
function __constructA(\$hey) {
\$this->value = \$hey.'<br/>';
}

function __toString() {
return \$this->value;
}
}

\$x = new X("foo");
\$y = new Y("bar");

\$aa = new A(array("one", "two", "three"));
echo \$aa;

\$ar = new A("baz");
echo \$ar;

\$ax = new A(\$x);
echo \$ax;

\$ay = new A(\$y);
echo \$ay;
``````

Result:

``````Array#3
baz
Xfoo
Ybar
``````

Instead of the terminating exception if no constructor is found, it could be remove and allow for "empty" constructor. Or whatever you like.

How to upgrade all Python packages with pip

This is a PowerShell solution for Python 3:

``````pip3 list --outdated --format=legacy | ForEach { pip3 install -U \$_.split(" ")[0] }
``````

And for Python 2:

``````pip2 list --outdated --format=legacy | ForEach { pip2 install -U \$_.split(" ")[0] }
``````

This upgrades the packages one by one. So a

``````pip3 check
pip2 check
``````

afterwards should make sure no dependencies are broken.

How can prepared statements protect from SQL injection attacks?

I read through the answers and still felt the need to stress the key point which illuminates the essence of Prepared Statements. Consider two ways to query one's database where user input is involved:

Naive Approach

One concatenates user input with some partial SQL string to generate a SQL statement. In this case the user can embed malicious SQL commands, which will then be sent to the database for execution.

``````String SQLString = "SELECT * FROM CUSTOMERS WHERE NAME='"+userInput+"'"
``````

For example, malicious user input can lead to `SQLString` being equal to `"SELECT * FROM CUSTOMERS WHERE NAME='James';DROP TABLE CUSTOMERS;'`

Due to the malicious user, `SQLString` contains 2 statements, where the 2nd one (`"DROP TABLE CUSTOMERS"`) will cause harm.

Prepared Statements

In this case, due to the separation of the query & data, the user input is never treated as a SQL statement, and thus is never executed. It is for this reason, that any malicious SQL code injected would cause no harm. So the `"DROP TABLE CUSTOMERS"` would never be executed in the case above.

In a nutshell, with prepared statements malicious code introduced via user input will not be executed!

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command `bg` to resume it in background. For example:

``````sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)
``````

More about job control and `bg` usage in `bash` manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

``````nohup [command] [-args] > [filename] 2>&1 &
``````

e.g.

``````nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &
``````

To just ignore the output (not very wise) change the filename to `/dev/null`

To get the error message set to a different file change the `&1` to a filename.

In addition: You can use the `jobs` command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running `kill %1` or `kill %2` with the number being the index of the process.

Get the difference between two dates both In Months and days in sql

Find out Year - Month- Day between two Days in Orale Sql

``````select
trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12) years ,
trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))
-
(trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12))*12
months,
trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD'))))) days
from dual;
``````

How to use @Nullable and @Nonnull annotations more effectively?

I think this original question indirectly points to a general recommendation that run-time null-pointer check is still needed, even though @NonNull is used. Refer to the following link:

Java 8's new Type Annotations

In the above blog, it is recommended that:

Optional Type Annotations are not a substitute for runtime validation Before Type Annotations, the primary location for describing things like nullability or ranges was in the javadoc. With Type annotations, this communication comes into the bytecode in a way for compile-time verification. Your code should still perform runtime validation.

Generic Interface

Here's another suggestion:

``````public interface Service<T> {
T execute();
}
``````

using this simple interface you can pass arguments via constructor in the concrete service classes:

``````public class FooService implements Service<String> {

private final String input1;
private final int input2;

public FooService(String input1, int input2) {
this.input1 = input1;
this.input2 = input2;
}

@Override
public String execute() {
return String.format("'%s%d'", input1, input2);
}
}
``````

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

I use the following method in my project

``````-(NSArray*)networkErrorCodes
{
static NSArray *codesArray;
if (![codesArray count]){
@synchronized(self){
const int codes[] = {
//kCFURLErrorUnknown,     //-998
//kCFURLErrorCancelled,   //-999
//kCFURLErrorTimedOut,    //-1001
//kCFURLErrorUnsupportedURL, //-1002
//kCFURLErrorCannotFindHost, //-1003
kCFURLErrorCannotConnectToHost,     //-1004
kCFURLErrorNetworkConnectionLost,   //-1005
kCFURLErrorDNSLookupFailed,         //-1006
//kCFURLErrorHTTPTooManyRedirects,    //-1007
kCFURLErrorResourceUnavailable,     //-1008
kCFURLErrorNotConnectedToInternet,  //-1009
//kCFURLErrorRedirectToNonExistentLocation,   //-1010
//kCFURLErrorUserCancelledAuthentication,     //-1012
//kCFURLErrorUserAuthenticationRequired,      //-1013
//kCFURLErrorZeroByteResource,        //-1014
//kCFURLErrorCannotDecodeRawData,     //-1015
//kCFURLErrorCannotDecodeContentData, //-1016
//kCFURLErrorCannotParseResponse,     //-1017
kCFURLErrorInternationalRoamingOff, //-1018
kCFURLErrorCallIsActive,                //-1019
//kCFURLErrorDataNotAllowed,              //-1020
//kCFURLErrorRequestBodyStreamExhausted,  //-1021
kCFURLErrorFileDoesNotExist,            //-1100
//kCFURLErrorFileIsDirectory,             //-1101
//kCFURLErrorDataLengthExceedsMaximum,     //-1103
};
int size = sizeof(codes)/sizeof(int);
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i=0;i<size;++i){
}
codesArray = [array copy];
}
}
return codesArray;
}
``````

Then I just check the error code and show alert if it is in the list

``````if ([[self networkErrorCodes] containsObject:[NSNumber
numberWithInt:[error code]]]){
}
``````

But as you can see I commented out codes that I think does not fit to my definition of NO INTERNET. E.g the code of -1012 (Authentication fail.) You may edit the list as you like.

In my project I use it at username/password entering from user. And in my view (physical) network connection errors could be the only reason to show alert view in your network based app. In any other case (e.g. incorrect username/password pair) I prefer to do some custom user friendly animation, OR just repeat the failed attempt again without any attention of the user. Especially if the user didn't explicitly initiated a network call.

Regards to martinezdelariva for a link to documentation.

Rebasing remote branches in Git

You can disable the check (if you're really sure you know what you're doing) by using the `--force` option to `git push`.

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Python datetimes are a little clunky. Use `arrow`.

``````> str(arrow.utcnow())
'2014-05-17T01:18:47.944126+00:00'
``````

Arrow has essentially the same api as datetime, but with timezones and some extra niceties that should be in the main library.

A format compatible with Javascript can be achieved by:

``````arrow.utcnow().isoformat().replace("+00:00", "Z")
'2018-11-30T02:46:40.714281Z'
``````

Javascript `Date.parse` will quietly drop microseconds from the timestamp.

Display text from .txt file in batch file

Here's a version that doesn't fail if `log.txt` is missing:

``````
@echo off
if not exist log.txt goto firstlogin
type log.txt
goto end

:end
echo %date%, %time%. > log.txt
pause
``````

Python 3 Online Interpreter / Shell

I recently came across Python 3 interpreter at CompileOnline.

Get pixel color from canvas, on mousemove

You can try color-sampler. It's an easy way to pick color in a canvas. See demo.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

The only solution I have found is not to set the index to a previous frame and wait (then OpenCV stops reading frames, anyway), but to initialize the capture one more time. So, it looks like this:

``````cap = cv2.VideoCapture(camera_url)
while True:

if not ret:
cap = cv.VideoCapture(camera_url)
continue

``````

And it works perfectly!

Open a Web Page in a Windows Batch FIle

You can use the `start` command to do much the same thing as `ShellExecute`. For example

`````` start "" http://www.stackoverflow.com
``````

This will launch whatever browser is the default browser, so won't necessarily launch Internet Explorer.

How do I toggle an ng-show in AngularJS based on a boolean?

Basically I solved it by NOT-ing the `isReplyFormOpen` value whenever it is clicked:

``````<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

<!-- Form -->
</div>
``````

React.createElement: type is invalid -- expected a string

``````// @flow

import React from 'react';
import { styleLocal } from './styles';
import {
View,
Text,
TextInput,
Image,
} from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';

export default React.forwardRef((props, ref) => {
const { onSeachClick, onChangeTextSearch , ...otherProps } = props;

return (
<View style={styleLocal.sectionStyle}>
<TouchableOpacity onPress={onSeachClick}>
<Image
source={require('../../assets/imgs/search.png')}
style={styleLocal.imageStyle} />
</TouchableOpacity>
<TextInput
style={{ flex: 1, fontSize: 18 }}
placeholder="Search Here"
underlineColorAndroid="transparent"
onChangeText={(text) => { onChangeTextSearch(text) }}
/>
</View>
);
});
import IGPSSearch from '../../components/IGPSSearch';
<Search onSeachClick={onSeachClick} onChangeTextSearch= {onChangeTextSearch}> </Search>
``````

How to initialize a private static const map in C++?

I often use this pattern and recommend you to use it as well:

``````class MyMap : public std::map<int, int>
{
public:
MyMap()
{
//either
insert(make_pair(1, 2));
insert(make_pair(3, 4));
insert(make_pair(5, 6));
//or
(*this)[1] = 2;
(*this)[3] = 4;
(*this)[5] = 6;
}
} const static my_map;
``````

Sure it is not very readable, but without other libs it is best we can do. Also there won't be any redundant operations like copying from one map to another like in your attempt.

This is even more useful inside of functions: Instead of:

``````void foo()
{
static bool initComplete = false;
static Map map;
if (!initComplete)
{
initComplete = true;
map= ...;
}
}
``````

Use the following:

``````void bar()
{
struct MyMap : Map
{
MyMap()
{
...
}
} static mymap;
}
``````

Not only you don't need here to deal with boolean variable anymore, you won't have hidden global variable that is checked if initializer of static variable inside function was already called.

How can I show figures separately in matplotlib?

As @arpanmangal, the solutions above do not work for me (`matplotlib 3.0.3`, `python 3.5.2`).

It seems that using `.show()` in a figure, e.g., `figure.show()`, is not recommended, because this method does not manage a GUI event loop and therefore the figure is just shown briefly. (See figure.show() documentation). However, I do not find any another way to show only a figure.

In my solution I get to prevent the figure for instantly closing by using click events. We do not have to close the figure — closing the figure deletes it.

I present two options: - `waitforbuttonpress(timeout=-1)` will close the figure window when clicking on the figure, so we cannot use some window functions like zooming. - `ginput(n=-1,show_clicks=False)` will wait until we close the window, but it releases an error :-.

Example:

``````import matplotlib.pyplot as plt

fig1, ax1 = plt.subplots(1) # Creates figure fig1 and add an axes, ax1
fig2, ax2 = plt.subplots(1) # Another figure fig2 and add an axes, ax2

ax1.plot(range(20),c='red') #Add a red straight line to the axes of fig1.
ax2.plot(range(100),c='blue') #Add a blue straight line to the axes of fig2.

#Option1: This command will hold the window of fig2 open until you click on the figure
fig2.waitforbuttonpress(timeout=-1) #Alternatively, use fig1

#Option2: This command will hold the window open until you close the window, but
#it releases an error.
#fig2.ginput(n=-1,show_clicks=False) #Alternatively, use fig1

#We show only fig2
fig2.show() #Alternatively, use fig1
``````

Javascript AES encryption

If you are trying to use javascript to avoid using SSL, think again. There are many half-way measures, but only SSL provides secure communication. Javascript encryption libraries can help against a certain set of attacks, but not a true man-in-the-middle attack.

The following article explains how to attempt to create secure communication with javascript, and how to get it wrong: Use JavaScript encryption module instead of SSL/HTTPS

Note: If you are looking for SSL for google app engine on a custom domain, take a look at wwwizer.com.

How can I add an element after another element?

First of all, `input` element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden ).

Second thing, you need the `after()`, not `append()` function.

How to List All Redis Databases?

There is no command to do it (like you would do it with MySQL for instance). The number of Redis databases is fixed, and set in the configuration file. By default, you have 16 databases. Each database is identified by a number (not a name).

You can use the following command to know the number of databases:

``````CONFIG GET databases
1) "databases"
2) "16"
``````

You can use the following command to list the databases for which some keys are defined:

``````INFO keyspace
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0
``````

Please note that you are supposed to use the "redis-cli" client to run these commands, not telnet. If you want to use telnet, then you need to run these commands formatted using the Redis protocol.

For instance:

``````*2
\$4
INFO
\$8
keyspace

\$79
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0
``````

You can find the description of the Redis protocol here: http://redis.io/topics/protocol

HTML5 video won't play in Chrome only

Have you tried by setting the MIME type of your .m4v to "video/m4v" or "video/x-m4v" ?

Browsers might use the `canPlayType` method internally to check if a `<source>` is candidate to playback.

In Chrome, I have these results:

``````document.createElement("video").canPlayType("video/mp4"); // "maybe"
document.createElement("video").canPlayType("video/m4v"); // ""
document.createElement("video").canPlayType("video/x-m4v"); // "maybe"
``````

Dataframe to Excel sheet

From your above needs, you will need to use both Python (to export pandas data frame) and VBA (to delete existing worksheet content and copy/paste external data).

With Python: use the to_csv or to_excel methods. I recommend the to_csv method which performs better with larger datasets.

``````# DF TO EXCEL
from pandas import ExcelWriter

writer = ExcelWriter('PythonExport.xlsx')
yourdf.to_excel(writer,'Sheet5')
writer.save()

# DF TO CSV
yourdf.to_csv('PythonExport.csv', sep=',')
``````

With VBA: copy and paste source to destination ranges.

Fortunately, in VBA you can call Python scripts using Shell (assuming your OS is Windows).

``````Sub DataFrameImport()
'RUN PYTHON TO EXPORT DATA FRAME
Shell "C:\pathTo\python.exe fullpathOfPythonScript.py", vbNormalFocus

'CLEAR EXISTING CONTENT
ThisWorkbook.Worksheets(5).Cells.Clear

'COPY AND PASTE TO WORKBOOK
Workbooks("PythonExport").Worksheets(1).Cells.Copy
ThisWorkbook.Worksheets(5).Range("A1").Select
ThisWorkbook.Worksheets(5).Paste
End Sub
``````

Alternatively, you can do vice versa: run a macro (ClearExistingContent) with Python. Be sure your Excel file is a macro-enabled (.xlsm) one with a saved macro to delete Sheet 5 content only. Note: macros cannot be saved with csv files.

``````import os
import win32com.client
from pandas import ExcelWriter

if os.path.exists("C:\Full Location\To\excelsheet.xlsm"):
xlApp=win32com.client.Dispatch("Excel.Application")
wb = xlApp.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm")

# MACRO TO CLEAR SHEET 5 CONTENT
xlApp.Run("ClearExistingContent")
wb.Save()
xlApp.Quit()
del xl

# WRITE IN DATA FRAME TO SHEET 5
writer = ExcelWriter('C:\Full Location\To\excelsheet.xlsm')
yourdf.to_excel(writer,'Sheet5')
writer.save()
``````

SQL query to find third highest salary in company

You may use this for all employee with 3rd highest salary:

``````SELECT * FROM `employee` WHERE salary = (
SELECT DISTINCT(`salary`) FROM `employee` ORDER BY `salary` DESC LIMIT 1 OFFSET 2
);
``````

How do I check if string contains substring?

You can also check if the exact word is contained in a string. E.g.:

``````function containsWord(haystack, needle) {
return (" " + haystack + " ").indexOf(" " + needle + " ") !== -1;
}
``````

Usage:

``````containsWord("red green blue", "red"); // true
containsWord("red green blue", "green"); // true
containsWord("red green blue", "blue"); // true
containsWord("red green blue", "yellow"); // false
``````

This is how jQuery does its hasClass method.

How to exit git log or git diff

The `END` comes from the pager used to display the log (your are at that moment still inside it). Type q to exit it.

How exactly does the android:onClick XML attribute differ from setOnClickListener?

With Java 8, you could probably use Method Reference to achieve what you want.

Assume this is your `onClick` event handler for a button.

``````private void onMyButtonClicked(View v) {
if (v.getId() == R.id.myButton) {
// Do something when myButton was clicked
}
}
``````

Then, you pass `onMyButtonClicked` instance method reference in a `setOnClickListener()` call like this.

``````Button myButton = (Button) findViewById(R.id.myButton);
myButton.setOnClickListener(this::onMyButtonClicked);
``````

This will allow you to avoid explicitly defining an anonymous class by yourself. I must however emphasize that Java 8's Method Reference is actually just a syntactic sugar. It actually create an instance of the anonymous class for you (just like lambda expression did) hence similar caution as lambda-expression-style event handler was applied when you come to the unregistering of your event handler. This article explains it really nice.

PS. For those who curious about how can I really use Java 8 language feature in Android, it is a courtesy of retrolambda library.

Format SQL in SQL Server Management Studio

There is a special trick I discovered by accident.

1. Select the query you wish to format.
2. Ctrl+Shift+Q (This will open your query in the query designer)
3. Then just go OK Voila! Query designer will format your query for you. Caveat is that you can only do this for statements and not procedural code, but its better than nothing.

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Completing the solution of Ranadheer, using Server.MapPath to locate the file

``````System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
``````

Stored procedure return into DataSet in C# .Net

You can declare `SqlConnection` and `SqlCommand` instances at global level so that you can use it through out the class. Connection string is in `Web.Config`.

``````SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();
``````

Now you can use the below method to pass values to Stored Procedure and get the `DataSet`.

``````public DataSet GetDataSet(string paramValue)
{
sqlcomm.Connection = sqlConn;
using (sqlConn)
{
try
{
{
// This will be your input parameter and its value

// You can retrieve values of `output` variables
var returnParam = new SqlParameter
{
ParameterName = "@Error",
Direction = ParameterDirection.Output,
Size = 1000
};
// Name of stored procedure
sqlcomm.CommandText = "StoredProcedureName";
da.SelectCommand = sqlcomm;
da.SelectCommand.CommandType = CommandType.StoredProcedure;

DataSet ds = new DataSet();
da.Fill(ds);
}
}
catch (SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
return new DataSet();
}
``````

The following is the sample of connection string in config file

``````<connectionStrings>
providerName="System.Data.SqlClient" />
</connectionStrings>
``````

Using Linq select list inside list

After my previous answer disaster, I'm going to try something else.

``````List<Model> usrList  =
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));
``````

How to Export-CSV of Active Directory Objects?

the first command is correct but change from convert to export to csv, as below,

``````Get-ADUser -Filter * -Properties * `
| Sort-Object -Property Name `
| Export-Csv -path  C:\Users\*\Desktop\file1.csv
``````

Testing if value is a function

What browser are you using?

``````alert(typeof document.getElementById('myform').onsubmit);
``````

This gives me "`function`" in IE7 and FireFox.

How to remove specific element from an array using python

The sane way to do this is to use `zip()` and a List Comprehension / Generator Expression:

``````filtered = (
(email, other)
for email, other in zip(emails, other_list)
if email == '[email protected]')

new_emails, new_other_list = zip(*filtered)
``````

Also, if your'e not using `array.array()` or `numpy.array()`, then most likely you are using `[]` or `list()`, which give you Lists, not Arrays. Not the same thing.

Notice: Undefined variable: _SESSION in "" on line 9

``````session_start();
``````

at the beginning of your page before any HTML

You will have something like :

``````<?php session_start();
<html>
<meta http-equiv="Content-Type" conte...
``````

Don't forget to remove the space you have before

How to retrieve the last autoincremented ID from a SQLite table?

Sample code from @polyglot solution

``````SQLiteCommand sql_cmd;
sql_cmd.CommandText = "select seq from sqlite_sequence where name='myTable'; ";
int newId = Convert.ToInt32( sql_cmd.ExecuteScalar( ) );
``````

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

for Android Studio 3.0.1, you can config GitHub path for following path:

1. File > Setting > Version Control
2. List item
3. Click "+" on the top-right conor to open "Add VCS Directory Mapping"
4. Click "Configure VCS" to open "Version Control Configurations"
5. Click "Git" then you'll see Path to Git executable]
6. Input : C:\Users[you user name]\AppData\Local\GitHub\PortableGit_d7effa1a4a322478cd29c826b52a0c118ad3db11\cmd\git.exe
7. Test it

enter image description here

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

If you have multiple Java versions installed on your Mac, here's a quick way to switch the default version using Terminal. In this example, I am going to switch Java 10 to Java 8.

``````\$ java -version
java version "10.0.1" 2018-04-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)

\$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
10.0.1, x86_64: "Java SE 10.0.1"    /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
1.8.0_171, x86_64:  "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
``````

``````# Java 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home
``````

Now if you try java -version again, you should see the version you want.

``````\$ java -version
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)
``````

Why doesn't list have safe "get" method like dictionary?

This guy worked for me:

``````list_get = lambda l, x: l[x:x+1] and l[x] or 0
``````

lambdas are great for one liner helper functions like this

Why does Maven have such a bad rep?

Because Maven is a device for reducing grown men to sobbing masses of absolute terror.

CSS Disabled scrolling

Try using the following code snippet. This should solve your issue.

``````body, html {
overflow-x: hidden;
overflow-y: auto;
}
``````

PowerShell: Create Local User Account

``````Import-Csv C:\test.csv |
Foreach-Object {
}
``````

:) worked on 2012 R2

Getting DOM element value using pure JavaScript

Yes, most notably! I don't think the second one will work (and if it does, not very portably). The first one should be OK.

``````// HTML:
<input id="theId" value="test" onclick="doSomething(this)" />

// JavaScript:
function(elem){
var value = elem.value;
var id    = elem.id;
...
}
``````

This should also work.

Update: the question was edited. Both of the solutions are now equivalent.

Finding elements not in a list

If you run a loop taking items from z, how do you expect them not to be in z? IMHO it would make more sense comparing items from a different list to z.

Python Pandas iterate over rows and access column names

The item from `iterrows()` is not a Series, but a tuple of (index, Series), so you can unpack the tuple in the for loop like so:

``````for (idx, row) in df.iterrows():
print(row.loc['A'])
print(row.A)
print(row.index)

#0.890618586836
#0.890618586836
#Index(['A', 'B', 'C', 'D'], dtype='object')
``````

You code is ok only except that you can't add same class `test1`.

``````\$('.page-address-edit').addClass('test1').addClass('test2'); //this will add test1 and test2
``````

And you could also do

``````\$('.page-address-edit').addClass('test1 test2');
``````

Associating existing Eclipse project with existing SVN repository

I'm asked this question very frequently, if it's smart to use "Share project..." if a eclipse project has been disconnected from it SVN counterpart in the repository. So, I append my answer to this thread.

The SVN-Team option "Share project ..." is totally fine for projects that exist in SVN and in your Eclipse workspace, even if the Eclipse project is missing the hidden .svn configuration. You can still connect them. Eclipse SVN-implementation (Subclipse/Subversive) will verify if the provided SVN http(s) source is populated. If yes, all existing files will be copied and linked (checked out in SVN terms) to your very personal Eclipse workspace.

Word of caution:

• Do a backup if you depend on you local files. The SVN implementation may vary its behaviour with every release.
• If you have multiple projects encapsulated within each other, make sure you point the SVN path to the correct local path.

regards, Feder

subquery in codeigniter active record

``````\$this->db->where('`id` IN (SELECT `someId` FROM `anotherTable` WHERE `someCondition`='condition')', NULL, FALSE);
``````

Iteration ng-repeat only X times in AngularJs

Answer given by @mpm is not working it gives the error

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}

To avoid this along with

ng-repeat="t in getTimes(4)"

use

track by \$index

like this

<div ng-repeat="t in getTimes(4) track by \$index">TEXT</div>

How to specify a port to run a create-react-app based project?

It would be nice to be able to specify a port other than `3000`, either as a command line parameter or an environment variable.

Right now, the process is pretty involved:

1. Run `npm run eject`
2. Wait for that to finish
3. Edit `scripts/start.js` and find/replace `3000` with whatever port you want to use
4. Edit `config/webpack.config.dev.js` and do the same
5. `npm start`

How do you use the ? : (conditional) operator in JavaScript?

This is probably not exactly the most elegant way to do this. But for someone who is not familiar with ternary operators, this could prove useful. My personal preference is to do 1-liner fallbacks instead of condition-blocks.

``````  // var firstName = 'John'; // Undefined
var lastName = 'Doe';

// if lastName or firstName is undefined, false, null or empty => fallback to empty string
lastName = lastName || '';
firstName = firstName || '';

var displayName = '';

// if lastName (or firstName) is undefined, false, null or empty
// displayName equals 'John' OR 'Doe'

// if lastName and firstName are not empty
// a space is inserted between the names
displayName = (!lastName || !firstName) ? firstName + lastName : firstName + ' ' + lastName;

// if display name is undefined, false, null or empty => fallback to 'Unnamed'
displayName = displayName || 'Unnamed';

console.log(displayName);
``````

Ternary Operator

how to check for special characters php

`preg_match('/'.preg_quote('^\'£\$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', \$string);`

Why is jquery's .ajax() method not sending my session cookie?

Using

``````xhrFields: { withCredentials:true }
``````

as part of my jQuery ajax call was only part of the solution. I also needed to have the headers returned in the OPTIONS response from my resource:

``````Access-Control-Allow-Origin : http://www.wombling.com
Access-Control-Allow-Credentials : true
``````

It was important that only one allowed "origin" was in the response header of the OPTIONS call and not "*". I achieved this by reading the origin from the request and populating it back into the response - probably circumventing the original reason for the restriction, but in my use case the security is not paramount.

I thought it worth explicitly mentioning the requirement for only one origin, as the W3C standard does allow for a space separated list -but Chrome doesn't! http://www.w3.org/TR/cors/#access-control-allow-origin-response-header NB the "in practice" bit.

matplotlib: colorbars and its text labels

``````import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['\$0\$','\$1\$','\$2\$','\$>3\$']):
cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.set_ylabel('# of contacts', rotation=270)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()
``````

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

Can I nest a <button> element inside an <a> using HTML5?

If you're using Bootstrap 3, this works quite well

``````<a href="#" class="btn btn-primary btn-lg active" role="button">Primary link</a>
<a href="#" class="btn btn-default btn-lg active" role="button">Link</a>
``````

Set variable value to array of strings

``````-- create test table "Accounts"
create table Accounts (
c_ID int primary key
,first_name varchar(100)
,last_name varchar(100)
,city varchar(100)
);

insert into Accounts values (101, 'Sebastian', 'Volk', 'Frankfurt' );
insert into Accounts values (102, 'Beate',  'Mueller', 'Hamburg' );
insert into Accounts values (103, 'John',  'Walker', 'Washington' );
insert into Accounts values (104, 'Britney', 'Sears', 'Holywood' );
insert into Accounts values (105, 'Sarah', 'Schmidt', 'Mainz' );
insert into Accounts values (106, 'George', 'Lewis', 'New Jersey' );
insert into Accounts values (107, 'Jian-xin', 'Wang', 'Peking' );
insert into Accounts values (108, 'Katrina', 'Khan', 'Bolywood' );

-- declare table variable
declare @tb_FirstName table(name varchar(100));
insert into  @tb_FirstName values ('John'), ('Sarah'), ('George');

SELECT *
FROM Accounts
WHERE first_name in (select name from @tb_FirstName);

SELECT *
FROM Accounts
WHERE first_name not in (select name from @tb_FirstName);
go

drop table Accounts;
go
``````

What does localhost:8080 mean?

http://localhost:8080/web: localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat. 8080 ( port ) is the address of the port on which the host server is listening for requests.

http://localhost/web: localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat. host server listening to default port 80.

How to create a Restful web service with input parameters?

You can try this... put parameters as :

``````package newpackage;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;

@Path("generic")
public class GenericResource {

@Context
private UriInfo context;

/**
* Creates a new instance of GenericResource
*/
public GenericResource() {
}

/**
* Retrieves representation of an instance of newpackage.GenericResource

* @return an instance of java.lang.String
*/
@GET
@Produces("text/plain")
@Consumes("text/plain")
@Path("getText/")
public String getText(@QueryParam("arg1")
@DefaultValue("") String arg1) {

return  arg1 ;  }

@PUT
@Consumes("text/plain")
public void putText(String content) {

}
}
``````

How to lock orientation of one view controller to portrait mode only in Swift

To set Landscape orientation to all view of your app & allow only one view to All orientations (to be able to add camera roll for example):

In AppDelegate.swift:

``````var adaptOrientation = false
``````

In: didFinishLaunchingWithOptions

``````NSNotificationCenter.defaultCenter().addObserver(self, selector: "adaptOrientationAction:", name:"adaptOrientationAction", object: nil)
``````

Elsewhere in AppDelegate.swift:

``````func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int {
return checkOrientation(self.window?.rootViewController)
}

func checkOrientation(viewController:UIViewController?)-> Int{
}else {
}
}

}else {
}
}
``````

Then in the view that segue to the one you want to be able to have All orientations:

``````override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "YOURSEGUE") {
}
}

override func viewWillAppear(animated: Bool) {
}
}
``````

Last thing is to tick Device orientation: - Portrait - Landscape Left - Landscape Right

How to access static resources when mapping a global front controller servlet on /*

The best way to handle this is using some kind of URL re-writing. In this way, you can have clean restful URLs, and NOT with any extensions i.e abc.com/welcom/register as opposed to abc.com/welcome/resister.html

I use Tuckey URL which is pretty cool.

It's got instructions on how to set up your web app.I have set it up with my Spring MVC web app. Of course, everything was fine until I wanted to use annotations for Spring 3 validations like `@Email` or `@Null` for domain objects.

When I add the Spring mvc directives:

``````< mvc:annotation-driven  />
< mvc:default-servlet-handler />
``````

.. it breaks the good ol Tuckey code. Apparently, `< mvc:default-servlet-handler />` replaces Tuckey, which I'm still trying to solve.

PHP Constants Containing Arrays?

Constants can only contain scalar values, I suggest you store the serialization (or JSON encoded representation) of the array.

Step 1: Installing GLFW 3 on your system with CMAKE

For this install, I was using KUbuntu 13.04, 64bit.

The next step is to extract the archive, and open a terminal. `cd` into the glfw-3.X.X directory and run `cmake -G "Unix Makefiles"` you may need elevated privileges, and you may also need to install build dependencies first. To do this, try `sudo apt-get build-dep glfw` or `sudo apt-get build-dep glfw3` or do it manually, as I did using `sudo apt-get install cmake xorg-dev libglu1-mesa-dev`... There may be other libs you require such as the pthread libraries... Apparently I had them already. (See the -l options given to the g++ linker stage, below.)

Now you can type `make` and then `make install`, which will probably require you to `sudo` first.

Okay, you should get some verbose output on the last three CMake stages, telling you what has been built or where it has been placed. (In `/usr/include`, for example.)

Step 2: Create a test program and compile

The next step is to fire up vim ("what?! vim?!" you say) or your preferred IDE / text editor... I didn't use vim, I used Kate, because I am on KUbuntu 13.04... Anyway, download or copy the test program from here (at the bottom of the page) and save, exit.

Now compile using `g++ -std=c++11 -c main.cpp` - not sure if c++11 is required but I used `nullptr` so, I needed it... You may need to upgrade your gcc to version 4.7, or the upcoming version 4.8... Info on that here.

Then fix your errors if you typed the program by hand or tried to be "too clever" and something didn't work... Then link it using this monster! `g++ main.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi` So you see, in the "install build dependencies" part, you may also want to check you have the GL, GLU, X11 Xxf86vm (whatever that is) Xrandr posix-thread and Xi (whatever that is) development libraries installed also. Maybe update your graphics drivers too, I think GLFW 3 may require OpenGL version 3 or higher? Perhaps someone can confirm that? You may also need to add the linker options `-ldl -lXinerama -lXcursor` to get it to work correctly if you are getting undefined references to `dlclose` (credit to @user2255242).

And, yes, I really did need that many `-l`s!

Step 3: You are finished, have a nice day!

Hopefully this information was correct and everything worked for you, and you enjoyed writing the GLFW test program. Also hopefully this guide has helped, or will help, a few people in the future who were struggling as I was today yesterday!

By the way, all the tags are the things I searched for on stackoverflow looking for an answer that didn't exist. (Until now.) Hopefully they are what you searched for if you were in a similar position to myself.

Author Note:

This might not be a good idea. This method (using sudo make install) might be harzardous to your system. (See Don't Break Debian)

Ideally I, or someone else, should propose a solution which does not just install lib files etc into the system default directories as these should be managed by package managers such as `apt`, and doing so may cause a conflict and break your package management system.

See the new "2020 answer" for an alternative solution.

How can I create a Java method that accepts a variable number of arguments?

Take a look at the Java guide on varargs.

You can create a method as shown below. Simply call `System.out.printf` instead of `System.out.println(String.format(...`.

``````public static void print(String format, Object... args) {
System.out.printf(format, args);
}
``````

Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:

``````import static java.lang.System.out;

out.printf("Numer of apples: %d", 10);
``````

creating batch script to unzip a file without additional zip tools

Here is a quick and simple solution using PowerShell:

``````powershell.exe -nologo -noprofile -command "& { \$shell = New-Object -COM Shell.Application; \$target = \$shell.NameSpace('C:\extractToThisDirectory'); \$zip = \$shell.NameSpace('C:\extractThis.zip'); \$target.CopyHere(\$zip.Items(), 16); }"
``````

This uses the built-in extract functionality of the Explorer and will also show the typical extract progress window. The second parameter `16` to `CopyHere` answers all questions with yes.

MySQL - Trigger for updating same table after insert

``````DELIMITER \$\$

DROP TRIGGER IF EXISTS `setEditStatus`\$\$
CREATE TRIGGER `setEditStatus` **BEFORE** INSERT on ACCOUNTS
FOR EACH ROW BEGIN

SET NEW.STATUS = 'E';

END\$\$

DELIMITER ;
``````

Closing Applications

for me best solotion this is

`````` Thread.CurrentThread.Abort();
``````

and force close app.

Get last field using awk substr

If you're open to a Perl solution, here one similar to fedorqui's awk solution:

``````perl -F/ -lane 'print \$F[-1]' input
``````

`-F/` specifies `/` as the field separator
`\$F[-1]` is the last element in the `@F` autosplit array

How to create the branch from specific commit in different branch

If you are using this form of the `branch` command (with start point), it does not matter where your `HEAD` is.

What you are doing:

``````git checkout dev
git branch test 07aeec983bfc17c25f0b0a7c1d47da8e35df7af8
``````
• First, you set your `HEAD` to the branch `dev`,

• Second, you start a new branch on commit `07aeec98`. There is no bb.txt at this commit (according to your github repo).

If you want to start a new branch at the location you have just checked out, you can either run branch with no start point:

``````git branch test
``````

or as other have answered, branch and checkout there in one operation:

``````git checkout -b test
``````

I think that you might be confused by that fact that `07aeec98` is part of the branch `dev`. It is true that this commit is an ancestor of `dev`, its changes are needed to reach the latest commit in `dev`. However, they are other commits that are needed to reach the latest `dev`, and these are not necessarily in the history of `07aeec98`.

`8480e8ae` (where you added bb.txt) is for example not in the history of `07aeec98`. If you branch from `07aeec98`, you won't get the changes introduced by `8480e8ae`.

In other words: if you merge branch A and branch B into branch C, then create a new branch on a commit of A, you won't get the changes introduced in B.

Same here, you had two parallel branches master and dev, which you merged in dev. Branching out from a commit of master (older than the merge) won't provide you with the changes of dev.

If you want to permanently integrate new changes from master into your feature branches, you should merge `master` into them and go on. This will create merge commits in your feature branches, though.

If you have not published your feature branches, you can also rebase them on the updated master: `git rebase master featureA`. Be prepared to solve possible conflicts.

If you want a workflow where you can work on feature branches free of merge commits and still integrate with newer changes in master, I recommend the following:

• base every new feature branch on a commit of master
• create a `dev` branch on a commit of master
• when you need to see how your feature branch integrates with new changes in master, merge both master and the feature branch into `dev`.

Do not commit into `dev` directly, use it only for merging other branches.

For example, if you are working on feature A and B:

``````a---b---c---d---e---f---g -master
\       \
\       \-x -featureB
\
\-j---k -featureA
``````

Merge branches into a `dev` branch to check if they work well with the new master:

``````a---b---c---d---e---f---g -master
\       \            \
\       \            \--x'---k' -dev
\       \             /    /
\       \-x----------    /    -featureB
\                      /
\-j---k--------------- -featureA
``````

You can continue working on your feature branches, and keep merging in new changes from both master and feature branches into `dev` regularly.

``````a---b---c---d---e---f---g---h---i----- -master
\       \            \            \
\       \            \--x'---k'---i'---l' -dev
\       \             /    /         /
\       \-x----------    /         /  -featureB
\                      /         /
\-j---k-----------------l------ -featureA
``````

When it is time to integrate the new features, merge the feature branches (not `dev`!) into master.

How to check if a std::thread is still running?

This simple mechanism you can use for detecting finishing of a thread without blocking in join method.

``````std::thread thread([&thread]() {
sleep(3);
});

sleep(1);
``````

You may want to update you .bashrc and .bash_profile files with aliases to recognize the command you are entering.

.bashrc and .bash_profile files are hidden files probably located on your C: drive where you save your program files.

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

In case anyone arrives looking for how to generate a relative path from the rails console

``````ActionView::Helpers::AssetTagHelper
image_path('my_image.png')
=> "/images/my_image.png"
``````

Or the controller

``````include ActionView::Helpers::AssetTagHelper
image_path('my_image.png')
=> "/images/my_image.png"
``````

How do I disable log messages from the Requests library?

In case you came here looking for a way to modify logging of any (possibly deeply nested) module, use `logging.Logger.manager.loggerDict` to get a dictionary of all of the logger objects. The returned names can then be used as the argument to `logging.getLogger`:

``````import requests
import logging
for key in logging.Logger.manager.loggerDict:
print(key)
# requests.packages.urllib3.connectionpool
# requests.packages.urllib3.util
# requests.packages
# requests.packages.urllib3
# requests.packages.urllib3.util.retry
# requests
# requests.packages.urllib3.poolmanager

logging.getLogger('requests').setLevel(logging.CRITICAL)
# Could also use the dictionary directly:
# logging.Logger.manager.loggerDict['requests'].setLevel(logging.CRITICAL)
``````

Per user136036 in a comment, be aware that this method only shows you the loggers that exist at the time you run the above snippet. If, for example, a module creates a new logger when you instantiate a class, then you must put this snippet after creating the class in order to print its name.

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

You will get this error when you call any of the `setXxx()` methods on `PreparedStatement`, while the SQL query string does not have any placeholders `?` for this.

For example this is wrong:

``````String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
``````

You need to fix the SQL query string accordingly to specify the placeholders.

``````String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);
``````

Note the parameter index starts with `1` and that you do not need to quote those placeholders like so:

``````String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";
``````

Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.

How to navigate through textfields (Next / Done Buttons)

This is a simple solution in swift, with no tag using, no storyboard tricks...

Just use this extension :

``````extension UITextField{

func nextTextFieldField() -> UITextField?{
//field to return
var returnField : UITextField?
if self.superview != nil{
//for each view in superview
for (_, view) in self.superview!.subviews.enumerate(){
//if subview is a text's field
if view.isKindOfClass(UITextField){
//cast curent view as text field
let currentTextField = view as! UITextField
//if text field is after the current one
if currentTextField.frame.origin.y > self.frame.origin.y{
//if there is no text field to return already
if returnField == nil {
//set as default return
returnField = currentTextField
}
//else if this this less far than the other
else if currentTextField.frame.origin.y < returnField!.frame.origin.y{
//this is the field to return
returnField = currentTextField
}
}
}
}
}
//end of the mdethod
return returnField
}

}
``````

And call it like this (for example) with your textfield delegate:

``````func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
textField.nextTextFieldField()?.becomeFirstResponder()
return true
}
``````

How to create a popup windows in javafx

You can either create a new `Stage`, add your controls into it or if you require the POPUP as `Dialog` box, then you may consider using DialogsFX or ControlsFX(Requires JavaFX8)

For creating a new Stage, you can use the following snippet

``````@Override
public void start(final Stage primaryStage) {
Button btn = new Button();
btn.setText("Open Dialog");
btn.setOnAction(
new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
final Stage dialog = new Stage();
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.initOwner(primaryStage);
VBox dialogVbox = new VBox(20);
Scene dialogScene = new Scene(dialogVbox, 300, 200);
dialog.setScene(dialogScene);
dialog.show();
}
});
}
``````

If you don't want it to be `modal` (block other windows), use:

``````dialog.initModality(Modality.NONE);
``````

PHP send mail to multiple email addresses

Try this. It works for me.

``````\$to = \$email1 .','. \$email2 .','. \$email3;
``````

Moment get current date

Just call moment as a function without any arguments:

``````moment()
``````

For timezone information with moment, look at the `moment-timezone` package: http://momentjs.com/timezone/

How to roundup a number to the closest ten?

You could also use `CEILING` which rounds up to an integer or desired multiple of significance

ie
`=CEILING(A1,10)`
rounds up to a multiple of 10

`12340.0001` will become `12350`

Selenium Webdriver: Entering text into text field

It might be the JavaScript check for some valid condition.
Two things you can perform a/c to your requirements:

1. either check for the valid string-input in the text-box.
2. or set a loop against that text box to enter the value until you post the form/request.
``````String barcode="0000000047166";

WebElement strLocator = driver.findElement(By.xpath("//*[@id='div-barcode']"));
strLocator.sendKeys(barcode);
``````

How many characters can a Java String have?

The heap part gets worse, my friends. UTF-16 isn't guaranteed to be limited to 16 bits and can expand to 32

How to check if an option is selected?

Consider this as your select list:

``````<select onchange="var optionVal = \$(this).find(':selected').val(); doSomething(optionVal)">

<option value="mostSeen">Most Seen</option>
<option value="mostSell">Most Sell</option>
<option value="mostCheap">Most Cheap</option>
<option value="mostExpensive">Most Expensive</option>

</select>
``````

then you check selected option like this:

``````function doSomething(param) {

if (\$(param.selected)) {
}

}
``````

How to check if BigDecimal variable == 0 in java?

GriffeyDog is definitely correct:

Code:

``````BigDecimal myBigDecimal = new BigDecimal("00000000.000000");
System.out.println("bestPriceBigDecimal=" + myBigDecimal);
System.out.println("BigDecimal.valueOf(0.000000)=" + BigDecimal.valueOf(0.000000));
System.out.println(" equals=" + myBigDecimal.equals(BigDecimal.ZERO));
System.out.println("compare=" + (0 == myBigDecimal.compareTo(BigDecimal.ZERO)));
``````

Results:

``````myBigDecimal=0.000000
BigDecimal.valueOf(0.000000)=0.0
equals=false
compare=true
``````

While I understand the advantages of the BigDecimal compare, I would not consider it an intuitive construct (like the ==, <, >, <=, >= operators are). When you are holding a million things (ok, seven things) in your head, then anything you can reduce your cognitive load is a good thing. So I built some useful convenience functions:

``````public static boolean equalsZero(BigDecimal x) {
return (0 == x.compareTo(BigDecimal.ZERO));
}
public static boolean equals(BigDecimal x, BigDecimal y) {
return (0 == x.compareTo(y));
}
public static boolean lessThan(BigDecimal x, BigDecimal y) {
return (-1 == x.compareTo(y));
}
public static boolean lessThanOrEquals(BigDecimal x, BigDecimal y) {
return (x.compareTo(y) <= 0);
}
public static boolean greaterThan(BigDecimal x, BigDecimal y) {
return (1 == x.compareTo(y));
}
public static boolean greaterThanOrEquals(BigDecimal x, BigDecimal y) {
return (x.compareTo(y) >= 0);
}
``````

Here is how to use them:

``````    System.out.println("Starting main Utils");
BigDecimal bigDecimal0 = new BigDecimal(00000.00);
BigDecimal bigDecimal2 = new BigDecimal(2);
BigDecimal bigDecimal4 = new BigDecimal(4);
BigDecimal bigDecimal20 = new BigDecimal(2.000);
System.out.println("Positive cases:");
System.out.println("bigDecimal0=" + bigDecimal0 + " == zero is " + Utils.equalsZero(bigDecimal0));
System.out.println("bigDecimal2=" + bigDecimal2 + " <  bigDecimal4=" + bigDecimal4 + " is " + Utils.lessThan(bigDecimal2, bigDecimal4));
System.out.println("bigDecimal2=" + bigDecimal2 + " == bigDecimal20=" + bigDecimal20 + " is " + Utils.equals(bigDecimal2, bigDecimal20));
System.out.println("bigDecimal2=" + bigDecimal2 + " <= bigDecimal20=" + bigDecimal20 + " is " + Utils.equals(bigDecimal2, bigDecimal20));
System.out.println("bigDecimal2=" + bigDecimal2 + " <= bigDecimal4=" + bigDecimal4 + " is " + Utils.lessThanOrEquals(bigDecimal2, bigDecimal4));
System.out.println("bigDecimal4=" + bigDecimal4 + " >  bigDecimal2=" + bigDecimal2 + " is " + Utils.greaterThan(bigDecimal4, bigDecimal2));
System.out.println("bigDecimal4=" + bigDecimal4 + " >= bigDecimal2=" + bigDecimal2 + " is " + Utils.greaterThanOrEquals(bigDecimal4, bigDecimal2));
System.out.println("bigDecimal2=" + bigDecimal2 + " >= bigDecimal20=" + bigDecimal20 + " is " + Utils.greaterThanOrEquals(bigDecimal2, bigDecimal20));
System.out.println("Negative cases:");
System.out.println("bigDecimal2=" + bigDecimal2 + " == zero is " + Utils.equalsZero(bigDecimal2));
System.out.println("bigDecimal2=" + bigDecimal2 + " == bigDecimal4=" + bigDecimal4 + " is " + Utils.equals(bigDecimal2, bigDecimal4));
System.out.println("bigDecimal4=" + bigDecimal4 + " <  bigDecimal2=" + bigDecimal2 + " is " + Utils.lessThan(bigDecimal4, bigDecimal2));
System.out.println("bigDecimal4=" + bigDecimal4 + " <= bigDecimal2=" + bigDecimal2 + " is " + Utils.lessThanOrEquals(bigDecimal4, bigDecimal2));
System.out.println("bigDecimal2=" + bigDecimal2 + " >  bigDecimal4=" + bigDecimal4 + " is " + Utils.greaterThan(bigDecimal2, bigDecimal4));
System.out.println("bigDecimal2=" + bigDecimal2 + " >= bigDecimal4=" + bigDecimal4 + " is " + Utils.greaterThanOrEquals(bigDecimal2, bigDecimal4));
``````

The results look like this:

``````Positive cases:
bigDecimal0=0 == zero is true
bigDecimal2=2 <  bigDecimal4=4 is true
bigDecimal2=2 == bigDecimal20=2 is true
bigDecimal2=2 <= bigDecimal20=2 is true
bigDecimal2=2 <= bigDecimal4=4 is true
bigDecimal4=4 >  bigDecimal2=2 is true
bigDecimal4=4 >= bigDecimal2=2 is true
bigDecimal2=2 >= bigDecimal20=2 is true
Negative cases:
bigDecimal2=2 == zero is false
bigDecimal2=2 == bigDecimal4=4 is false
bigDecimal4=4 <  bigDecimal2=2 is false
bigDecimal4=4 <= bigDecimal2=2 is false
bigDecimal2=2 >  bigDecimal4=4 is false
bigDecimal2=2 >= bigDecimal4=4 is false
``````

How to avoid the "divide by zero" error in SQL?

Filter out data in using a where clause so that you don't get 0 values.

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

``````Calendar currentTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
currentTime.set(Calendar.ZONE_OFFSET, TimeZone.getTimeZone("UTC").getRawOffset());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, currentTime.get(Calendar.HOUR_OF_DAY));
calendar.getTimeInMillis()
``````

is working for me

Python: Pandas Dataframe how to multiply entire column with a scalar

You can use the index of the column you want to apply the multiplication for

``````df.loc[:,6] *= -1
``````

This will multiply the column with index 6 with -1.

Return from a promise then()

What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.

``````// new answer

function justTesting() {
return new Promise((resolve, reject) => {
if (true) {
return resolve("testing");
} else {
return reject("promise failed");
}
});
}

justTesting()
.then(res => {
let test = res;
// do something with the output :)
})
.catch(err => {
console.log(err);
});
``````

Hope this helps!

``````// old answer

function justTesting() {
return promise.then(function(output) {
return output + 1;
});
}

justTesting().then((res) => {
var test = res;
// do something with the output :)
}
``````

How can I access a hover state in reactjs?

React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use `:hover` in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use `onMouseEnter` and `onMouseLeave`. You then attach them to handlers in your component like so:

``````<ReactComponent
onMouseEnter={() => this.someHandler}
onMouseLeave={() => this.someOtherHandler}
/>
``````

You'll then use some combination of state/props to pass changed state or properties down to your child React components.

Global Angular CLI version greater than local version

This is how I solved the issue.

Copy and run these commands

``````ng --version
npm install --save-dev @angular/cli@latest
ng --version
``````

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

I faced the same issue. Tried adding the `US_export_policy.jar` and `local_policy.jar` in the java security folder first but the issue persisted. Then added the below in `java_opts` inside tomcat `setenv.sh`file and it worked.

``````-Djdk.tls.ephemeralDHKeySize=2048
``````

Close popup window

You can only close a window using javascript that was opened using javascript, i.e. when the window was opened using :

``````window.open
``````

then

``````window.close
``````

will work. Or else not.

Or you could simply initialize

var x = 0; ( you should use let x = 0;)

This way it will add not concatenate.

jquery to validate phone number

This one is work for me:-

``````/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})\$/
``````

What's the meaning of System.out.println in Java?

``````System.out.println
``````

`System` is a class in the `java.lang` package.

`out` is a `static` data member of the `System` class and references a variable of the `PrintStream` class.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

Overview

As reported by Tim Anderson

Cross-platform development is a big deal, and will continue to be so until a day comes when everyone uses the same platform. Android? HTML? WebKit? iOS? Windows? Xamarin? Titanum? PhoneGap? Corona? ecc.

Sometimes I hear it said that there are essentially two approaches to cross-platform mobile apps. You can either use an embedded browser control and write a web app wrapped as a native app, as in Adobe PhoneGap/Cordova or the similar approach taken by Sencha, or you can use a cross-platform tool that creates native apps, such as Xamarin Studio, Appcelerator Titanium, or Embarcardero FireMonkey.

Within the second category though, there is diversity. In particular, they vary concerning the extent to which they abstract the user interface.

Here is the trade-off. If you design your cross-platform framework you can have your application work almost the same way on every platform. If you are sharing the UI design across all platforms, it is hard to make your design feel equally right in all cases. It might be better to take the approach adopted by most games, using a design that is distinctive to your app and make a virtue of its consistency across platforms, even though it does not have the native look and feel on any platform.

edit Xamarin v3 in 2014 started offering choice of Xamarin.Forms as well as pure native that still follows the philosophy mentioned here (took liberty of inline edit because such a great answer)

Xamarin Studio on the other hand makes no attempt to provide a shared GUI framework:

We don’t try to provide a user interface abstraction layer that works across all the platforms. We think that’s a bad approach that leads to lowest common denominator user interfaces. (Nat Friedman to Tim Anderson)

This is right; but the downside is the effort involved in maintaining two or more user interface designs for your app.

Comparison about PhoneGap and Titanium it's well reported in Kevin Whinnery blog.

PhoneGap

The purpose of PhoneGap is to allow HTML-based web applications to be deployed and installed as native applications. PhoneGap web applications are wrapped in a native application shell, and can be installed via the native app stores for multiple platforms. Additionally, PhoneGap strives to provide a common native API set which is typically unavailable to web applications, such as basic camera access, device contacts, and sensors not already exposed in the browser.

To develop PhoneGap applications, developers will create HTML, CSS, and JavaScript files in a local directory, much like developing a static website. Approaching native-quality UI performance in the browser is a non-trivial task - Sencha employs a large team of web programming experts dedicated full-time to solving this problem. Even so, on most platforms, in most browsers today, reaching native-quality UI performance and responsiveness is simply not possible, even with a framework as advanced as Sencha Touch. Is the browser already “good enough” though? It depends on your requirements and sensibilities, but it is unquestionably less good than native UI. Sometimes much worse, depending on the browser.

PhoneGap is not as truly cross-platform as one might believe, not all features are equally supported on all platforms.

• Javascript is not an application scale programming language, too many global scope interactions, different libraries don't often co-exist nicely. We spent many hours trying to get knockout.js and jQuery.mobile play well together, and we still have problems.

• Fragmented landscape for frameworks and libraries. Too many choices, and too many are not mature enough.

• Strangely enough, for the needs of our app, decent performance could be achieved (not with jQuery.Mobile, though). We tried jqMobi (not very mature, but fast).

• Very limited capability for interaction with other apps or cdevice capabilities, and this would not be cross-platform anyway, as there aren't any standards in HTML5 except for a few, like geolocation, camera and local databases.

Appcelerator Titanium

The goal of Titanium Mobile is to provide a high level, cross-platform JavaScript runtime and API for mobile development (today we support iOS, Android and Windows Phone. Titanium actually has more in common with MacRuby/Hot Cocoa, PHP, or node.js than it does with PhoneGap, Adobe AIR, Corona, or Rhomobile. Titanium is built on two assertions about mobile development: - There is a core of mobile development APIs which can be normalized across platforms. These areas should be targeted for code reuse. - There are platform-specific APIs, UI conventions, and features which developers should incorporate when developing for that platform. Platform-specific code should exist for these use cases to provide the best possible experience.

So for those reasons, Titanium is not an attempt at “write once, run everywhere”. Same as Xamarin.

Titanium are going to do a further step in the direction similar to that of Xamarin. In practice, they will do two layers of different depths: the layer Titanium (in JS), which gives you a bee JS-of-Titanium. If you want to go more low-level, have created an additional layer (called Hyperloop), where (always with JS) to call you back directly to native APIs of SO

Xamarin (+ MVVMCross)

AZDevelop.net

Xamarin (originally a division of Novell) in the last 18 months has brought to market its own IDE and snap-in for Visual Studio. The underlining premise of Mono is to create disparate mobile applications using C# while maintaining native UI development strategies.

In addition to creating a visual design platform to develop native applications, they have integrated testing suites, incorporated native library support and a Nuget style component store. Recently they provided iOS visual design through their IDE freeing the developer from opening XCode. In Visual Studio all three platforms are now supported and a cloud testing suite is on the horizon.

From the get go, Xamarin has provided a rich Android visual design experience. I have yet to download or open Eclipse or any other IDE besides Xamarin. What is truly amazing is that I am able to use LINQ to work with collections as well as create custom delegates and events that free me from objective-C and Java limitations. Many of the libraries I have been spoiled with, like Newtonsoft JSON.Net, work perfectly in all three environments.

In my opinion there are several HUGE advantages including

• native performance
• easier to read code (IMO)
• testability
• shared code between client and server
• support (although Xam could do better on bugzilla)

Upgrade for me is use Xamarin and MVVMCross combined. It's still quite a new framework, but it's born from experience of several other frameworks (such as MvvmLight and monocross) and it's now been used in at several released cross platform projects.

Conclusion

My choice after knowing all these framwework, was to select development tool based on product needs. In general, however if you start to use a tool with which you feel comfortable (even if it requires a higher initial overhead) after you'll use it forever.

I chose Xamarin + MVVMCross and I must say to be happy with this choice. I'm not afraid of approach Native SDK for software updates or seeing limited functionality of a system or the most trivial thing a feature graphics. Write code fairly structured (DDD + SOA) is very useful to have a core project shared with native C# views implementation.

Using HTTPS with REST in Java

Here's the painful route:

``````    SSLContext ctx = null;
try {
KeyStore trustStore;
trustStore = KeyStore.getInstance("JKS");
"asdfgh".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory
.getInstance("SunX509");
tmf.init(trustStore);
ctx = SSLContext.getInstance("SSL");
ctx.init(null, tmf.getTrustManagers(), null);
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
ClientConfig config = new DefaultClientConfig();
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
new HTTPSProperties(null, ctx));

WebResource service = Client.create(config).resource(
"https://localhost:9999/");

// Attempt to view the user's page.
try {
} catch (Exception e) {
e.printStackTrace();
}
``````

Gotta love those six different caught exceptions :). There are certainly some refactoring to simplify the code a bit. But, I like delfuego's -D options on the VM. I wish there was a javax.net.ssl.trustStore static property that I could just set. Just two lines of code and done. Anyone know where that would be?

This may be too much to ask, but, ideally the keytool would not be used. Instead, the trustedStore would be created dynamically by the code and the cert is added at runtime.

There must be a better answer.

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

Installing the "security" package extras for `requests` solved for me:

``````sudo apt-get install libffi-dev
sudo pip install -U requests[security]
``````

How do you reinstall an app's dependencies using npm?

`npm` updated the CLI command for `install` and added the `--force` flag.

``````npm install --force
``````

The `--force` (or `-f`) argument will force `npm` to fetch remote resources even if a local copy exists on disk.

data.frame Group By column

``````require(reshape2)

T <- melt(df, id = c("A"))

T <- dcast(T, A ~ variable, sum)
``````

I am not certain the exact advantages over aggregate.

What does the following Oracle error mean: invalid column index

I had this problem using a prepared statement. I didn't add enough "?" for the "VALUES" My eclipse had crashed after I did add the proper amount, and lost those changes. But that didn't occur to me to be the error until I started combing through the SQL as p.campbell suggested.

How to add label in chart.js for pie chart

...

So, I have re-worked Chart.js. Most of the changes, are associated to requests in "GitHub" issues of Chart.js.

And here is a sample http://jsbin.com/lakiyu/2/edit

``````var newopts = {
inGraphDataShow: true,
inGraphDataFontColor: 'white'
}
var pieData = [
{
value: 30,
color: "#F38630",
},
{
value: 30,
color: "#F34353",
},
{
value: 30,
color: "#F34353",
}
]
var pieCtx = document.getElementById('pieChart').getContext('2d');
new Chart(pieCtx).Pie(pieData, newopts);
``````

It even provides a GUI editor http://charts.livegap.com/

So sweet.

Use sed to replace all backslashes with forward slashes

For me, this replaces one backslash with a forward slash.

``````sed -e "s/\\\\/\//"  file.txt
``````

PHP - include a php file and also send query parameters

You could do something like this to achieve the effect you are after:

``````\$_GET['id']=\$somevar;
include('myFile.php');
``````

However, it sounds like you are using this include like some kind of function call (you mention calling it repeatedly with different arguments).

In this case, why not turn it into a regular function, included once and called multiple times?

How can I generate a list of consecutive numbers?

Just to give you another example, although range(value) is by far the best way to do this, this might help you later on something else.

``````list = []
calc = 0

while int(calc) < 9:
list.append(calc)
calc = int(calc) + 1

print list
[0, 1, 2, 3, 4, 5, 6, 7, 8]
``````

How to push files to an emulator instance using Android Studio

Update (May 2020): Android studio have new tool called Device File Explorer. You can access it in two way:

1. By clicking on `Device File Explorer` icon in right bottom corner of android studio window.
2. If you could not find its icon, inside Android Studio press shift button twice. Quick search window will appear, then type `Device File` in it and Device File Explorer will appear in search result and you can click it.

Then you can navigate to folder which you want to push your file in it. Right click on that folder and select upload(or press Ctrl+Shift+O). Select file you want to upload and it will upload file to desired location.

Push file using `adb.exe`:

In Android 6.0+, you should use same process but your android application cannot access files which pushed inside SDCARD using DDMS File Explorer. It is the same if you try commands like this:

``````adb push myfile.txt /mnt/sdcard/myfile.txt
``````

If you face `EACCES (Permission denied)` exception when you try to read file inside your application, it means you have no access to files inside external storage, since it requires a dangerous permission.

For this situation, you need to request granting access manually using new permission system in Android 6.0 and upper version. For details you can have a look in android tutorial and this link.

Solution for old android studio version:

If you want to do it using graphical interface you can follow this inside android studio menus:

Tools --> Android --> Android Device Monitor

Afterward, Android Device Monitor(DDMS) window will open and you can upload files using File Explorer. You can select an address like `/mnt/sdcard` and then push your file into sdcard.

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I have worked alot with msaccess vba. I think you are looking for MID function

example

``````    dim myReturn as string
myreturn = mid("bonjour tout le monde",9,4)
``````

will give you back the value "tout"

Sublime text 3. How to edit multiple lines?

Select multiple lines by clicking first line then holding shift and clicking last line. Then press:

CTRL+SHIFT+L

or on MAC: CMD+SHIFT+L (as per comments)

Alternatively you can select lines and go to SELECTION MENU >> SPLIT INTO LINES.

Now you can edit multiple lines, move cursors etc. for all selected lines.

How do I get rid of an element's offset using CSS?

moving element top: -12px or positioning it absolutely doesn't solve the problem but only masks it

I had the same problem - check if you have in one wrapping element mixed: floating elements with non-floating ones - my non-floating element caused this strange offset to the floating one

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

``````python setup.py --help
``````

...to get a list of commands. What you are looking to do is...

``````python setup.py install
``````

How to use SortedMap interface in Java?

I would use `TreeMap`, which implements `SortedMap`. It is designed exactly for that.

Example:

``````Map<Integer, String> map = new TreeMap<Integer, String>();

// Add Items to the TreeMap
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Iterate over them
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
``````

See the Java tutorial page for SortedMap.
And here a list of tutorials related to TreeMap.

Showing percentages above bars on Excel column graph

You can do this with a pivot table and add a line with the pourcentage for each category like brettdj showed in his answer. But if you want to keep your data as it is, there is a solution by using some javascript.

Javascript is a powerful language offering a lot of useful data visualization libraries like plotly.js.

Here is a working code I have written for you:

https://www.funfun.io/1/#/edit/5a58c6368dfd67466879ed27

In this example, I use a Json file to get the data from the embedded spreadsheet, so I can use it in my javascript code and create a bar chart.

I calculate the percentage by adding the values of all the category present in the table and using this formula (you can see it in the script.js file): `Percentage (%) = 100 x partial value / total value`

It automatically calculates the total and pourcentage even if you add more categories.

I used plotly.js to create my chart, it has a good documentation and lots of examples for beginners, this code gets all the option you want to use:

``````var trace1 = {
x: xValue,
y: data,
type: 'bar',
text: yValue,
textposition: 'auto',
hoverinfo: 'none',
marker: {
color: 'yellow',
opacity: 0.6,
line: {
color: 'yellow',
width: 1.5
}
}
};
``````

It is rather self explanatory, the `text` is where you put the percentage.

Once you've made your chart you can load it in excel by passing the URL in the Funfun add-in. Here is how it looks like with my example:

I know it is an old post but I hope it helps people with the same problem !

Disclosure : I’m a developer of funfun

Move repository to root of your drive (temporary fix)

You can try to temporarily move the local repository (the entire folder) to the root of your drive or as close to the root as possible.

Since the path is smaller at the root of the drive, it sometimes fixes the issues.

On Windows, I'd move this to `C:\` or another drive's root.

How to add a Java Properties file to my Java Project in Eclipse

It should work ok as it is in Unix, if you have properties file in current working directory. Another option would be adding your properties file to the classpath and getting the inputstream using `this.getClass().getClassLoader().getResourceAsStream("xxxxx.properties");` More here

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

Recently,I also encountered this problem. That's because I used qt(`x64`) in vs `win32`. If you want to use qt application `x64`, you could choose vs `x64`--as the above. If you want to use `win32` and perhaps you haven't,you need to download qt(`32bit`),then correctly set your enviroment, such as the `lib` directory, etc.(note: maybe you are is old set in `x64(other version)`, if you convert your win32 or x64 into another, `Additional Dependencies` includes the old directory!)

Use Async/Await with Axios in React.js

Two issues jump out:

1. Your `getData` never returns anything, so its promise (`async` functions always return a promise) will resolve with `undefined` when it resolves

2. The error message clearly shows you're trying to directly render the promise `getData` returns, rather than waiting for it to resolve and then rendering the resolution

Addressing #1: `getData` should return the result of calling `json`:

``````async getData(){
const res = await axios('/data');
return await res.json();
}
``````

Addressig #2: We'd have to see more of your code, but fundamentally, you can't do

``````<SomeElement>{getData()}</SomeElement>
``````

...because that doesn't wait for the resolution. You'd need instead to use `getData` to set state:

``````this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
``````

...and use that state when rendering:

``````<SomeElement>{this.state.data}</SomeElement>
``````

Update: Now that you've shown us your code, you'd need to do something like this:

``````class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
}
}
render() {
return (
<div>
</div>
);
}
}
``````

Futher update: You've indicated a preference for using `await` in `componentDidMount` rather than `then` and `catch`. You'd do that by nesting an `async` IIFE function within it and ensuring that function can't throw. (`componentDidMount` itself can't be `async`, nothing will consume that promise.) E.g.:

``````class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
(async () => {
try {
this.setState({data: await this.getData()});
} catch (e) {
//...handle the error...
}
})();
}
}
render() {
return (
<div>
</div>
);
}
}
``````

How to run JUnit tests with Gradle?

If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:

``````sourceSets {
test {
java.srcDirs += [
'src/customDir/test/kotlin'
]
print(java.srcDirs)   // Clean
}
}
``````

Pay attention to the operator `+=` and if you want to run integration tests change `test` to `androidTest`.

GL

How do I URl encode something in Node.js?

Use the `escape` function of `querystring`. It generates a URL safe string.

``````var escaped_str = require('querystring').escape('Photo on 30-11-12 at 8.09 AM #2.jpg');
console.log(escaped_str);
// prints 'Photo%20on%2030-11-12%20at%208.09%20AM%20%232.jpg'
``````

SQL RANK() versus ROW_NUMBER()

I haven't done anything with rank, but I discovered this today with row_number().

``````select item, name, sold, row_number() over(partition by item order by sold) as row from table_name
``````

This will result in some repeating row numbers since in my case each name holds all items. Each item will be ordered by how many were sold.

``````+--------+------+-----+----+
|glasses |store1|  30 | 1  |
|glasses |store2|  35 | 2  |
|glasses |store3|  40 | 3  |
|shoes   |store2|  10 | 1  |
|shoes   |store1|  20 | 2  |
|shoes   |store3|  22 | 3  |
+--------+------+-----+----+
``````

__init__ and arguments in Python

In Python:

• Instance methods: require the `self` argument.
• Class methods: take the class as a first argument.
• Static methods: do not require either the instance (`self`) or the class (`cls`) argument.

`__init__` is a special function and without overriding `__new__` it will always be given the instance of the class as its first argument.

An example using the builtin classmethod and staticmethod decorators:

``````import sys

class Num:
max = sys.maxint

def __init__(self,num):
self.n = num

def getn(self):
return self.n

@staticmethod
def getone():
return 1

@classmethod
def getmax(cls):
return cls.max

myObj = Num(3)
# with the appropriate decorator these should work fine
myObj.getone()
myObj.getmax()
myObj.getn()
``````

That said, I would try to use `@classmethod`/`@staticmethod` sparingly. If you find yourself creating objects that consist of nothing but `staticmethod`s the more pythonic thing to do would be to create a new module of related functions.

MySQL server has gone away - in exactly 60 seconds

Increasing SQL-Wait-Timeout worked for me in this case, try this:

``````mysql_query("SET @@session.wait_timeout=900", \$link);
``````

before you first "normal" SQL queries.

What's the difference between unit tests and integration tests?

Unit test is usually done for a single functionality implemented in Software module. The scope of testing is entirely within this SW module. Unit test never fulfils the final functional requirements. It comes under whitebox testing methodology..

Whereas Integration test is done to ensure the different SW module implementations. Testing is usually carried out after module level integration is done in SW development.. This test will cover the functional requirements but not enough to ensure system validation.

Convert timestamp long to normal date format

Not sure if JSF provides a built-in functionality, but you could use `java.sql.Date`'s constructor to convert to a date object: http://download.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html#Date(long)

Then you should be able to use higher level features provided by Java SE, Java EE to display and format the extracted date. You could instantiate a `java.util.Calendar` and explicitly set the time: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#setTime(java.util.Date)

EDIT: The JSF components should not take care of the conversion. Your data access layer (persistence layer) should take care of this. In other words, your JSF components should not handle the `long` typed attributes but only a `Date` or `Calendar` typed attributes.

How to cin to a vector

In this case your `while` loop will look like

``````int i = 0;
int a = 0;
while (i < n){
cin >> a;
V.push_back(a);
++i;
}
``````

Change onclick action with a Javascript function

``````var Foo = function(){
document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
}

var Boo = function(){
}
``````

Implicit type conversion rules in C++ operators

Whole chapter 4 talks about conversions, but I think you should be mostly interested in these :

4.5 Integral promotions [conv.prom]
An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; other-
wise, the source rvalue can be converted to an rvalue of type unsigned int.
An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) can be converted to an rvalue of the first
of the following types that can represent all the values of its underlying type: int, unsigned int,
long, or unsigned long.
An rvalue for an integral bit-field (9.6) can be converted to an rvalue of type int if int can represent all
the values of the bit-field; otherwise, it can be converted to unsigned int if unsigned int can rep-
resent all the values of the bit-field. If the bit-field is larger yet, no integral promotion applies to it. If the
bit-field has an enumerated type, it is treated as any other value of that type for promotion purposes.
An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true
becoming one.
These conversions are called integral promotions.

4.6 Floating point promotion [conv.fpprom]
An rvalue of type float can be converted to an rvalue of type double. The value is unchanged.
This conversion is called floating point promotion.

Therefore, all conversions involving float - the result is float.

Only the one involving both int - the result is int : int / int = int

Javascript/jQuery: Set Values (Selection) in a multiple Select

Just provide the jQuery val function with an array of values:

``````var values = "Test,Prof,Off";
\$('#strings').val(values.split(','));
``````

And to get the selected values in the same format:

``````values = \$('#strings').val();
``````

Java, How to get number of messages in a topic in apache kafka

If you have access to server's JMX interface, the start & end offsets are present at:

``````kafka.log:type=Log,name=LogStartOffset,topic=TOPICNAME,partition=PARTITIONNUMBER
kafka.log:type=Log,name=LogEndOffset,topic=TOPICNAME,partition=PARTITIONNUMBER
``````

(you need to replace `TOPICNAME` & `PARTITIONNUMBER`). Bear in mind you need to check for each of the replicas of given partition, or you need to find out which one of the brokers is the leader for a given partition (and this can change over time).

Alternatively, you can use Kafka Consumer methods `beginningOffsets` and `endOffsets`.

Laravel-5 how to populate select box from database with id value and name value

Laravel provides a Query Builder with lists() function

``````\$items = Items::all(['id', 'name']);
``````

with

``````\$items = Items::lists('name', 'id');
``````

Also, you can chain it with other Query Builder as well.

``````\$items = Items::where('active', true)->orderBy('name')->lists('name', 'id');
``````

Update for Laravel 5.2

Thank you very much @jarry. As you mentioned, the function for Laravel 5.2 should be

``````\$items = Items::pluck('name', 'id');
``````

or

``````\$items = Items::where('active', true)->orderBy('name')->pluck('name', 'id');
``````

Hex to ascii string conversion

`strtol()` is your friend here. The third parameter is the numerical base that you are converting.

Example:

``````#include <stdio.h>      /* printf */
#include <stdlib.h>     /* strtol */

int main(int argc, char **argv)
{
long int num  = 0;
long int num2 =0;
char * str. = "f00d";
char * str2 = "0xf00d";

num = strtol( str, 0, 16);  //converts hexadecimal string to long.
num2 = strtol( str2, 0, 0); //conversion depends on the string passed in, 0x... Is hex, 0... Is octal and everything else is decimal.

printf( "%ld\n", num);
printf( "%ld\n", num);
}
``````

Codeigniter LIKE with wildcard(%)

If you do not want to use the wildcard (%) you can pass to the optional third argument the option 'none'.

``````\$this->db->like('title', 'match', 'none');
// Produces: WHERE title LIKE 'match'
``````

Oracle: How to find out if there is a transaction pending?

you can check if your session has a row in `V\$TRANSACTION` (obviously that requires read privilege on this view):

``````SQL> SELECT COUNT(*)
FROM v\$transaction t, v\$session s, v\$mystat m
AND s.sid = m.sid
AND ROWNUM = 1;

COUNT(*)
----------
0

SQL> insert into a values (1);

1 row inserted

SQL> SELECT COUNT(*)
FROM v\$transaction t, v\$session s, v\$mystat m
AND s.sid = m.sid
AND ROWNUM = 1;

COUNT(*)
----------
1

SQL> commit;

Commit complete

SQL> SELECT COUNT(*)
FROM v\$transaction t, v\$session s, v\$mystat m
AND s.sid = m.sid
AND ROWNUM = 1;

COUNT(*)
----------
0
``````

fatal: The current branch master has no upstream branch

For me, it was because I had deleted the hidden .git folder.

I fixed it by deleting the folder, re-cloning, and re-making the changes.

EOFError: EOF when reading a line

**The best is to use try except block to get rid of EOF **

``````try:
width = input()
height = input()
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
except EOFError as e:
print(end="")
``````

What's is the difference between include and extend in use case diagram?

The include relationship allows one use case to include the steps of another use case.

For example, suppose you have an Amazon Account and you want to check on an order, well it is impossible to check on the order without first logging into your account. So the flow of events would like so...

The extend relationship is used to add an extra step to the flow of a use case, that is usually an optional step...

Imagine that we are still talking about your amazon account. Lets assume the base case is Order and the extension use case is Amazon Prime. The user can choose to just order the item regularly, or, the user has the option to select Amazon Prime which ensure his order will arrive faster at higher cost.

However, note that the user does not have to select Amazon Prime, this is just an option, they can choose to ignore this use case.

How to get rid of blank pages in PDF exported from SSRS

If your report includes a subreport, the width of the subreport could push the boundaries of the body if subreport and hierarchy are allowed to grow. I had a similar problem arise with a subreport that could be placed in a cell (spanning 2 columns). It looked like the span could contain it in the designer and it rendered fine in a winform or a browser and, originally, it could generate printer output (or pdf file) without spilling over onto excess pages.
Then, after changing some other column widths (and without exceeding the body width plus margins), the winform and browser renderings looked still looked fine but when the output (printer or pdf) was generated, it grew past the margins and wrote the right side of each page as a 2nd (4th, etc.) page. I could eliminate my problem by increasing colspan where the subreport was placed.
Whether or not you're using subreports, if you have page spillover and your body design fits within the margins of the page, look for something allowed to grow that pushes the width of the body out.

How to return the output of stored procedure into a variable in sql server

Use this code, Working properly

``````CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT

AS
Begin
DECLARE @cnt int;
DECLARE @status int =0;
SET NOCOUNT OFF
SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
if(@cnt = 1)
Begin
return @status;
End
else
Begin
SET @status =1;
return @status;
End
END
``````

Execute SP

``````DECLARE @statuss bit;
EXECUTE  [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;
``````

"Could not find acceptable representation" using spring-boot-starter-web

``````produces = "application/json"
``````

to the @RequestMapping annotation

TypeError: 'undefined' is not a function (evaluating '\$(document)')

You can pass \$ in function()

``````jQuery(document).ready(function(\$){

// jQuery code is in here

});
``````

or you can replace `\$(document);` with this `jQuery(document);`

or you can use `jQuery.noConflict()`

``````var jq=jQuery.noConflict();
jq('selector').show();
});
``````

Checking if a character is a special character in Java

What I would do:

``````char c;
int cint;
for(int n = 0; n < str.length(); n ++;)
{
c = str.charAt(n);
cint = (int)c;
if(cint <48 || (cint > 57 && cint < 65) || (cint > 90 && cint < 97) || cint > 122)
{
specialCharacterCount++
}
}
``````

That is a simple way to do things, without having to import any special classes. Stick it in a method, or put it straight into the main code.

Configuring Hibernate logging using Log4j XML config file?

Here's what I use:

``````<logger name="org.hibernate">
<level value="warn"/>
</logger>

<logger name="org.hibernate.SQL">
<level value="warn"/>
</logger>

<logger name="org.hibernate.type">
<level value="warn"/>
</logger>

<root>
<priority value="info"/>
<appender-ref ref="C1"/>
</root>
``````

Obviously, I don't like to see Hibernate messages ;) -- set the level to "debug" to get the output.

Char to int conversion in C

Since the ASCII codes for '0','1','2'.... are placed from 48 to 57 they are essentially continuous. Now the arithmetic operations require conversion of char datatype to int datatype.Hence what you are basically doing is: 53-48 and hence it stores the value 5 with which you can do any integer operations.Note that while converting back from int to char the compiler gives no error but just performs a modulo 256 operation to put the value in its acceptable range

Just something I found for Wordpress users,

As obvious as it sounds, If your div is returning some AJAX content based on say a header that would commonly link out to a new post page, some tutorials will say to return false since you're returning the post data on the same page and the return would prevent the page from moving. However if you return false, you also prevent Fancybox2 from doing it's thing as well. I spent hours trying to figure that stupid simple thing out.

So for these kind of links, just make sure that the href property is the hashed (#) div you wish to select, and in your javascript, make sure that you do not return false since you no longer will need to.

Simple I know ^_^

SQL SELECT everything after a certain character

I've been working on something similar and after a few tries and fails came up with this:

Example: STRING-TO-TEST-ON = 'ab,cd,ef,gh'

I wanted to extract everything after the last occurrence of "," (comma) from the string... resulting in "gh".

My query is:

``````SELECT SUBSTR('ab,cd,ef,gh' FROM (LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1)) AS `wantedString`
``````

Now let me try and explain what I did ...

1. I had to find the position of the last "," from the string and to calculate the wantedString length, using `LOCATE(",",REVERSE('ab,cd,ef,gh'))-1` by reversing the initial string I actually had to find the first occurrence of the "," in the string ... which wasn't hard to do ... and then -1 to actually find the string length without the ",".

2. calculate the position of my wantedString by subtracting the string length I've calculated at 1st step from the initial string length:

LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1

I have (+1) because I actually need the string position after the last "," .. and not containing the ",". Hope it makes sense.

1. all it remain to do is running a SUBSTR on my initial string FROM the calculated position.

I haven't tested the query on large strings so I do not know how slow it is. So if someone actually tests it on a large string I would very happy to know the results.

Pandas dataframe get first row of each group

If you only need the first row from each group we can do with `drop_duplicates`, Notice the function default method `keep='first'`.

``````df.drop_duplicates('id')
Out[1027]:
id   value
0    1   first
3    2   first
5    3   first
9    4  second
11   5   first
12   6   first
15   7  fourth
``````

I've connected to USB port directly in my laptop and timeout issue has been resolved.

Previously tried by port replicator, but it did not even recognized arduino, thus I chosen wrong port - resulting in timeout message.

So make sure that it is visible by your OS.

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

Add the line below in application.properties file under resource folder and restart your application.

``````spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
``````

Give all permissions to a user on a PostgreSQL database

In PostgreSQL 9.0+ you would do the following:

``````GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA MY_SCHEMA TO MY_GROUP;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA MY_SCHEMA TO MY_GROUP;
``````

If you want to enable this for newly created relations too, then set the default permissions:

``````ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
GRANT ALL PRIVILEGES ON TABLES TO MY_GROUP;
ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
GRANT ALL PRIVILEGES ON SEQUENCES TO MY_GROUP;
``````

However, seeing that you use 8.1 you have to code it yourself:

``````CREATE FUNCTION grant_all_in_schema (schname name, grant_to name) RETURNS integer AS \$\$
DECLARE
rel RECORD;
BEGIN
FOR rel IN
SELECT c.relname
FROM pg_class c
JOIN pg_namespace s ON c.namespace = s.oid
WHERE s.nspname = schname
LOOP
EXECUTE 'GRANT ALL PRIVILEGES ON ' || quote_ident(schname) || '.' || rel.relname || ' TO ' || quote_ident(grant_to);
END LOOP;
RETURN 1;
END; \$\$ LANGUAGE plpgsql STRICT;
REVOKE ALL ON FUNCTION grant_all_in_schema(name, name) FROM PUBLIC;
``````

This will set the privileges on all relations: tables, views, indexes, sequences, etc. If you want to restrict that, filter on `pg_class.relkind`. See the pg_class docs for details.

You should run this function as superuser and as regular as your application requires. An option would be to package this in a cron job that executes every day or every hour.

What does getActivity() mean?

Two likely definitions:

Fastest way to check if a value exists in a list

You could put your items into a `set`. Set lookups are very efficient.

Try:

``````s = set(a)
if 7 in s:
# do stuff
``````

edit In a comment you say that you'd like to get the index of the element. Unfortunately, sets have no notion of element position. An alternative is to pre-sort your list and then use binary search every time you need to find an element.

How can I access and process nested objects, arrays or JSON?

Just in case, anyone's visiting this question in 2017 or later and looking for an easy-to-remember way, here's an elaborate blog post on Accessing Nested Objects in JavaScript without being bamboozled by

Cannot read property 'foo' of undefined error

1. Oliver Steele's nested object access pattern

The easiest and the cleanest way is to use Oliver Steele's nested object access pattern

``````const name = ((user || {}).personalInfo || {}).name;
``````

With this notation, you'll never run into

Cannot read property 'name' of undefined.

You basically check if user exists, if not, you create an empty object on the fly. This way, the next level key will always be accessed from an object that exists or an empty object, but never from undefined.

2. Access Nested Objects Using Array Reduce

To be able to access nested arrays, you can write your own array reduce util.

``````const getNestedObject = (nestedObj, pathArr) => {
return pathArr.reduce((obj, key) =>
(obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}

// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);

// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'addresses', 0, 'city']);
// this will return the city from the first address item.
``````

There is also an excellent type handling minimal library typy that does all this for you.

Reversing a linked list in Java, recursively

I was asked this question at an interview and was annoyed that I fumbled with it since I was a little nervous.

```1->2->3->4->5->null
it would become:
5->4->3->2->1->null```
``````
//Takes as parameters a node in a linked list, and p, the previous node in that list
//returns the head of the new list
Node reverse(Node n,Node p){
if(n==null) return null;
if(n.next==null){ //if this is the end of the list, then this is the new head
n.next=p;
return n;
}
Node r=reverse(n.next,n);  //call reverse for the next node,
//using yourself as the previous node
n.next=p;                     //Set your next node to be the previous node
return r;                     //Return the head of the new list
}
``````

edit: ive done like 6 edits on this, showing that it's still a little tricky for me lol

How to execute an .SQL script file using c#

This works for me:

``````public void updatedatabase()
{

SqlConnection conn = new SqlConnection("Data Source=" + txtserver.Text.Trim() + ";Initial Catalog=" + txtdatabase.Text.Trim() + ";User ID=" + txtuserid.Text.Trim() + ";Password=" + txtpwd.Text.Trim() + "");
try
{

conn.Open();

// split script on GO command
IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*\$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (string commandString in commandStrings)
{
if (commandString.Trim() != "")
{
new SqlCommand(commandString, conn).ExecuteNonQuery();
}
}
lblmsg.Text = "Database updated successfully.";

}
catch (SqlException er)
{
lblmsg.Text = er.Message;
lblmsg.ForeColor = Color.Red;
}
finally
{
conn.Close();
}
}
``````

Disable/Enable Submit Button until all forms have been filled

You can enable and disable the submit button based on the javascript validation below is the validation code. Working Example Here

``````<script>
function validate() {

var valid = true;
valid = checkEmpty(\$("#name"));
valid = valid && checkEmail(\$("#email"));

\$("#san-button").attr("disabled",true);
if(valid) {
\$("#san-button").attr("disabled",false);
}
}
function checkEmpty(obj) {
var name = \$(obj).attr("name");
\$("."+name+"-validation").html("");
\$(obj).css("border","");
if(\$(obj).val() == "") {
\$(obj).css("border","#FF0000 1px solid");
\$("."+name+"-validation").html("Required");
return false;
}

return true;
}
function checkEmail(obj) {
var result = true;

var name = \$(obj).attr("name");
\$("."+name+"-validation").html("");
\$(obj).css("border","");

result = checkEmpty(obj);

if(!result) {
\$(obj).css("border","#FF0000 1px solid");
\$("."+name+"-validation").html("Required");
return false;
}

var email_regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+\$/;
result = email_regex.test(\$(obj).val());

if(!result) {
\$(obj).css("border","#FF0000 1px solid");
\$("."+name+"-validation").html("Invalid");
return false;
}

return result;
}
</script>
``````

Install tkinter for Python

If, like me, you don't have root privileges on your network because of your wonderful friends in I.S., and you are working in a local install you may have some problems with the above approaches.

I spent ages on Google - but in the end, it's easy.

To install locally on Linux (I did it to my home directory), extract the .tar.gz files for tcl and tk. Then open up the readme files inside the ./unix directory. I ran

``````cd ~/tcl8.5.11/unix
./configure --prefix=/home/cnel711 --exec-prefix=/home/cnel711
make
make install

cd ~/tk8.5.11/unix
./configure --prefix=/home/cnel711 --exec-prefix=/home/cnel711 --with-tcl=/home/cnel711/tcl8.5.11/unix
make
make install
``````

It may seem a pain, but the files are tiny and installation is very fast.

Then re-run `python setup.py build` and `python setup.py install` in your python installation directory - and it should work. It worked for me - and I can now import Tkinter etc to my heart's content - yipidy-yay. An entire afternoon spent on this - hope this note saves others from the pain.

Print raw string from variable? (not getting the answers)

Replace back-slash with forward-slash using one of the below:

• re.sub(r"\", "/", x)
• re.sub(r"\", "/", x)

How can I switch views programmatically in a view controller? (Xcode, iPhone)

The `instantiateViewControllerWithIdentifier` is the `Storyboard ID`.

``````NextViewController *NVC = [self.storyboard instantiateViewControllerWithIdentifier:@"NextViewController"];
[self presentViewController:NVC animated:YES completion:nil];
``````

org.json.simple cannot be resolved

Try importing this in build.gradle dependencies

``````compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1'
``````

How do I Sort a Multidimensional Array in PHP

Introducing: a very generalized solution for PHP 5.3+

I 'd like to add my own solution here, since it offers features that other answers do not.

Specifically, advantages of this solution include:

1. It's reusable: you specify the sort column as a variable instead of hardcoding it.
2. It's flexible: you can specify multiple sort columns (as many as you want) -- additional columns are used as tiebreakers between items that initially compare equal.
3. It's reversible: you can specify that the sort should be reversed -- individually for each column.
4. It's extensible: if the data set contains columns that cannot be compared in a "dumb" manner (e.g. date strings) you can also specify how to convert these items to a value that can be directly compared (e.g. a `DateTime` instance).
5. It's associative if you want: this code takes care of sorting items, but you select the actual sort function (`usort` or `uasort`).
6. Finally, it does not use `array_multisort`: while `array_multisort` is convenient, it depends on creating a projection of all your input data before sorting. This consumes time and memory and may be simply prohibitive if your data set is large.

The code

``````function make_comparer() {
// Normalize criteria up front so that the comparer finds everything tidy
\$criteria = func_get_args();
foreach (\$criteria as \$index => \$criterion) {
\$criteria[\$index] = is_array(\$criterion)
: array(\$criterion, SORT_ASC, null);
}

return function(\$first, \$second) use (&\$criteria) {
foreach (\$criteria as \$criterion) {
// How will we compare this round?
list(\$column, \$sortOrder, \$projection) = \$criterion;
\$sortOrder = \$sortOrder === SORT_DESC ? -1 : 1;

// If a projection was defined project the values now
if (\$projection) {
\$lhs = call_user_func(\$projection, \$first[\$column]);
\$rhs = call_user_func(\$projection, \$second[\$column]);
}
else {
\$lhs = \$first[\$column];
\$rhs = \$second[\$column];
}

// Do the actual comparison; do not return if equal
if (\$lhs < \$rhs) {
return -1 * \$sortOrder;
}
else if (\$lhs > \$rhs) {
return 1 * \$sortOrder;
}
}

return 0; // tiebreakers exhausted, so \$first == \$second
};
}
``````

How to use

Throughout this section I will provide links that sort this sample data set:

``````\$data = array(
array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'),
array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '01/12/1979'),
array('aa', 'name' => 'Paul', 'number' => 16, 'birthday' => '03/11/1987'),
array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'),
);
``````

The basics

The function `make_comparer` accepts a variable number of arguments that define the desired sort and returns a function that you are supposed to use as the argument to `usort` or `uasort`.

The simplest use case is to pass in the key that you 'd like to use to compare data items. For example, to sort `\$data` by the `name` item you would do

``````usort(\$data, make_comparer('name'));
``````

The key can also be a number if the items are numerically indexed arrays. For the example in the question, this would be

``````usort(\$data, make_comparer(0)); // 0 = first numerically indexed column
``````

Multiple sort columns

You can specify multiple sort columns by passing additional parameters to `make_comparer`. For example, to sort by "number" and then by the zero-indexed column:

``````usort(\$data, make_comparer('number', 0));
``````

More advanced features are available if you specify a sort column as an array instead of a simple string. This array should be numerically indexed, and must contain these items:

``````0 => the column name to sort on (mandatory)
1 => either SORT_ASC or SORT_DESC (optional)
2 => a projection function (optional)
``````

Let's see how we can use these features.

Reverse sort

To sort by name descending:

``````usort(\$data, make_comparer(['name', SORT_DESC]));
``````

To sort by number descending and then by name descending:

``````usort(\$data, make_comparer(['number', SORT_DESC], ['name', SORT_DESC]));
``````

Custom projections

In some scenarios you may need to sort by a column whose values do not lend well to sorting. The "birthday" column in the sample data set fits this description: it does not make sense to compare birthdays as strings (because e.g. "01/01/1980" comes before "10/10/1970"). In this case we want to specify how to project the actual data to a form that can be compared directly with the desired semantics.

Projections can be specified as any type of callable: as strings, arrays, or anonymous functions. A projection is assumed to accept one argument and return its projected form.

It should be noted that while projections are similar to the custom comparison functions used with `usort` and family, they are simpler (you only need to convert one value to another) and take advantage of all the functionality already baked into `make_comparer`.

Let's sort the example data set without a projection and see what happens:

``````usort(\$data, make_comparer('birthday'));
``````

That was not the desired outcome. But we can use `date_create` as a projection:

``````usort(\$data, make_comparer(['birthday', SORT_ASC, 'date_create']));
``````

This is the correct order that we wanted.

There are many more things that projections can achieve. For example, a quick way to get a case-insensitive sort is to use `strtolower` as a projection.

That said, I should also mention that it's better to not use projections if your data set is large: in that case it would be much faster to project all your data manually up front and then sort without using a projection, although doing so will trade increased memory usage for faster sort speed.

Finally, here is an example that uses all the features: it first sorts by number descending, then by birthday ascending:

``````usort(\$data, make_comparer(
['number', SORT_DESC],
['birthday', SORT_ASC, 'date_create']
));
``````

How do I make the method return type generic?

You could define `callFriend` this way:

``````public <T extends Animal> T callFriend(String name, Class<T> type) {
return type.cast(friends.get(name));
}
``````

Then call it as such:

``````jerry.callFriend("spike", Dog.class).bark();
jerry.callFriend("quacker", Duck.class).quack();
``````

This code has the benefit of not generating any compiler warnings. Of course this is really just an updated version of casting from the pre-generic days and doesn't add any additional safety.

how to get the attribute value of an xml node using java

try something like this :

``````    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document dDoc = builder.parse("d://utf8test.xml");

XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
System.out.println(node.getTextContent());
}
``````

• we ask for a nodeset (XPathConstants.NODESET) and not only for a single node.
• the xpath is now //xml/ep/source/@type and not //xml/source/@type/text()

PS: can you add the tag java to your question ? thanks.

In Rails, how do you render JSON using a view?

Just add `show.json.erb` file with the contents

``````<%= @user.to_json %>
``````

Sometimes it is useful when you need some extra helper methods that are not available in controller, i.e. `image_path(@user.avatar)` or something to generate additional properties in JSON:

``````<%= @user.attributes.merge(:avatar => image_path(@user.avatar)).to_json %>
``````

Calculating Covariance with Python and Numpy

When `a` and `b` are 1-dimensional sequences, `numpy.cov(a,b)[0][1]` is equivalent to your `cov(a,b)`.

The 2x2 array returned by `np.cov(a,b)` has elements equal to

``````cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)
``````

(where, again, `cov` is the function you defined above.)

Implementing autocomplete

PrimeNG has a native AutoComplete component with advanced features like templating and multiple selection.

http://www.primefaces.org/primeng/#/autocomplete

How to scanf only integer?

Use `fgets` and `strtol`,

A pointer to the first character following the integer representation in `s` is stored in the object pointed by `p`, if `*p` is different to `\n` then you have a bad input.

``````#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char *p, s[100];
long n;

while (fgets(s, sizeof(s), stdin)) {
n = strtol(s, &p, 10);
if (p == s || *p != '\n') {
} else break;
}
printf("You entered: %ld\n", n);
return 0;
}
``````

How to create a circle icon button in Flutter?

``````RawMaterialButton(
onPressed: () {},
constraints: BoxConstraints(),
elevation: 2.0,
fillColor: Colors.white,
child: Icon(
Icons.pause,
size: 35.0,
),
shape: CircleBorder(),
)
``````

note down `constraints: BoxConstraints()`, it's for not allowing padding in left.

Happy fluttering!!

Log record changes in SQL server in an audit table

I know this is old, but maybe this will help someone else.

Do not log "new" values. Your existing table, GUESTS, has the new values. You'll have double entry of data, plus your DB size will grow way too fast that way.

I cleaned this up and minimized it for this example, but here is the tables you'd need for logging off changes:

``````CREATE TABLE GUESTS (
GuestID INT IDENTITY(1,1) PRIMARY KEY,
GuestName VARCHAR(50),
ModifiedBy INT,
ModifiedOn DATETIME
)

CREATE TABLE GUESTS_LOG (
GuestLogID INT IDENTITY(1,1) PRIMARY KEY,
GuestID INT,
GuestName VARCHAR(50),
ModifiedBy INT,
ModifiedOn DATETIME
)
``````

When a value changes in the GUESTS table (ex: Guest name), simply log off that entire row of data, as-is, to your Log/Audit table using the Trigger. Your GUESTS table has current data, the Log/Audit table has the old data.

Then use a select statement to get data from both tables:

``````SELECT 0 AS 'GuestLogID', GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS] WHERE GuestID = 1
UNION
SELECT GuestLogID, GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS_LOG] WHERE GuestID = 1
ORDER BY ModifiedOn ASC
``````

Your data will come out with what the table looked like, from Oldest to Newest, with the first row being what was created & the last row being the current data. You can see exactly what changed, who changed it, and when they changed it.

Optionally, I used to have a function that looped through the RecordSet (in Classic ASP), and only displayed what values had changed on the web page. It made for a GREAT audit trail so that users could see what had changed over time.

How to add elements of a string array to a string array list?

You should instantiate your `ArrayList` before trying to add items:

``````private List<String> species = new ArrayList<String>();
``````

How do I connect to a MySQL Database in Python?

Stop Using MySQLDb if you want to avoid installing mysql headers just to access mysql from python.

Use pymysql. It does all of what MySQLDb does, but it was implemented purely in Python with NO External Dependencies. This makes the installation process on all operating systems consistent and easy. `pymysql` is a drop in replacement for MySQLDb and IMHO there is no reason to ever use MySQLDb for anything... EVER! - `PTSD from installing MySQLDb on Mac OSX and *Nix systems`, but that's just me.

Installation

`pip install pymysql`

That's it... you are ready to play.

Example usage from pymysql Github repo

``````import pymysql.cursors
import pymysql

# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)

try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('[email protected]', 'very-secret'))

# connection is not autocommit by default. So you must commit to save
connection.commit()

with connection.cursor() as cursor:
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('[email protected]',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
``````

ALSO - Replace MySQLdb in existing code quickly and transparently

If you have existing code that uses MySQLdb, you can easily replace it with pymysql using this simple process:

``````# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()
``````

All subsequent references to MySQLdb will use pymysql transparently.

Determine installed PowerShell version

I needed to check the version of PowerShell and then run the appropriate code. Some of our servers run v5, and others v4. This means that some functions, like compress, may or may not be available.

This is my solution:

``````if (\$PSVersionTable.PSVersion.Major -eq 5) {
#Execute code available in PowerShell 5, like Compress
Write-Host "You are running PowerShell version 5"
}
else {
#Use a different process
Write-Host "This is version \$PSVersionTable.PSVersion.Major"
}
``````

Is a GUID unique 100% of the time?

I experienced a duplicate GUID.

I use the Neat Receipts desktop scanner and it comes with proprietary database software. The software has a sync to cloud feature, and I kept getting an error upon syncing. A gander at the logs revealed the awesome line:

I was a bit in disbelief, but surely enough, when I found a way into my local neatworks database and deleted the record containing that GUID, the error stopped occurring.

So to answer your question with anecdotal evidence, no. A duplicate is possible. But it is likely that the reason it happened wasn't due to chance, but due to standard practice not being adhered to in some way. (I am just not that lucky) However, I cannot say for sure. It isn't my software.

Their customer support was EXTREMELY courteous and helpful, but they must have never encountered this issue before because after 3+ hours on the phone with them, they didn't find the solution. (FWIW, I am very impressed by Neat, and this glitch, however frustrating, didn't change my opinion of their product.)

VB.NET Empty String Array

Dim array As String() = Array.Empty(Of String)

Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity,

Regardless of the echo (which would need to be replaced with print_r or var_dump), if an exception is thrown the object should stay empty:

``````DOMNodeList Object
(
)
``````

Solution

1. Set `recover` to true, and `strictErrorChecking` to false

``````\$content = file_get_contents(\$url);

\$doc = new DOMDocument();
\$doc->recover = true;
\$doc->strictErrorChecking = false;
``````
2. Use php's entity-encoding on the markup's contents, which is a most common error source.

How to sum columns in a dataTable?

I doubt that this is what you want but your question is a little bit vague

``````Dim totalCount As Int32 = DataTable1.Columns.Count * DataTable1.Rows.Count
``````

If all your columns are numeric-columns you might want this:

You could use DataTable.Compute to `Sum` all values in the column.

`````` Dim totalCount As Double
For Each col As DataColumn In DataTable1.Columns
totalCount += Double.Parse(DataTable1.Compute(String.Format("SUM({0})", col.ColumnName), Nothing).ToString)
Next
``````

`````` Dim totalRow = DataTable1.NewRow
For Each col As DataColumn In DataTable1.Columns
totalRow(col.ColumnName) = Double.Parse(DataTable1.Compute("SUM(" & col.ColumnName & ")", Nothing).ToString)
Next
``````

ArrayAdapter in android to create simple listview

``````public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)
``````

I am also new to Android , so i might be wrong. But as per my understanding while using this for listview creation 2nd argument is the layout of list items. A layout consists of many views (image view,text view etc). With 3rd argument you are specifying in which view or textview you want the text to be displayed.

Tuples( or arrays ) as Dictionary keys in C#

If you are on .NET 4.0 use a Tuple:

``````lookup = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();
``````

If not you can define a `Tuple` and use that as the key. The Tuple needs to override `GetHashCode`, `Equals` and `IEquatable`:

``````struct Tuple<T, U, W> : IEquatable<Tuple<T,U,W>>
{

public Tuple(T first, U second, W third)
{
this.first = first;
this.second = second;
this.third = third;
}

public T First { get { return first; } }
public U Second { get { return second; } }
public W Third { get { return third; } }

public override int GetHashCode()
{
return first.GetHashCode() ^ second.GetHashCode() ^ third.GetHashCode();
}

public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return Equals((Tuple<T, U, W>)obj);
}

public bool Equals(Tuple<T, U, W> other)
{
return other.first.Equals(first) && other.second.Equals(second) && other.third.Equals(third);
}
}
``````

Best way to store time (hh:mm) in a database

IMHO what the best solution is depends to some extent on how you store time in the rest of the database (and the rest of your application)

Personally I have worked with SQLite and try to always use unix timestamps for storing absolute time, so when dealing with the time of day (like you ask for) I do what Glen Solsberry writes in his answer and store the number of seconds since midnight

When taking this general approach people (including me!) reading the code are less confused if I use the same standard everywhere

Avoid dropdown menu close on click inside

Like for instance Bootstrap 4 Alpha has this Menu Event. Why not use?

``````// PREVENT INSIDE MEGA DROPDOWN
e.stopPropagation();
e.preventDefault();
});
``````

Option to ignore case with .contains method?

Kotlin Devs, go with any / none

``````private fun compareCategory(
categories: List<String>?,
category: String
) = categories?.any { it.equals(category, true) } ?: false
``````