Programs & Examples On #Normalization

Use [tag:database-normalization] for normalizing database-structure, and [tag:unicode-normalization] for normalizing unicode text. Normalization refers to transformations which aim to reduce variation of various types of data and thereby allow more consistent processing, searching, sorting, comparison, etc.

How to normalize an array in NumPy to a unit vector?

There is also the function unit_vector() to normalize vectors in the popular transformations module by Christoph Gohlke:

import transformations as trafo
import numpy as np

data = np.array([[1.0, 1.0, 0.0],
                 [1.0, 1.0, 1.0],
                 [1.0, 2.0, 3.0]])

print(trafo.unit_vector(data, axis=1))

How to normalize a 2-dimensional numpy array in python less verbose?

In case you are trying to normalize each row such that its magnitude is one (i.e. a row's unit length is one or the sum of the square of each element in a row is one):

import numpy as np

a = np.arange(0,27,3).reshape(3,3)

result = a / np.linalg.norm(a, axis=-1)[:, np.newaxis]
# array([[ 0.        ,  0.4472136 ,  0.89442719],
#        [ 0.42426407,  0.56568542,  0.70710678],
#        [ 0.49153915,  0.57346234,  0.65538554]])

Verifying:

np.sum( result**2, axis=-1 )
# array([ 1.,  1.,  1.]) 

Why do we have to normalize the input for an artificial neural network?

When you use unnormalized input features, the loss function is likely to have very elongated valleys. When optimizing with gradient descent, this becomes an issue because the gradient will be steep with respect some of the parameters. That leads to large oscillations in the search space, as you are bouncing between steep slopes. To compensate, you have to stabilize optimization with small learning rates.

Consider features x1 and x2, where range from 0 to 1 and 0 to 1 million, respectively. It turns out the ratios for the corresponding parameters (say, w1 and w2) will also be large.

Normalizing tends to make the loss function more symmetrical/spherical. These are easier to optimize because the gradients tend to point towards the global minimum and you can take larger steps.

How to normalize a histogram in MATLAB?

The area of abcd`s PDF is not one, which is impossible like pointed out in many comments. Assumptions done in many answers here

  1. Assume constant distance between consecutive edges.
  2. Probability under pdf should be 1. The normalization should be done as Normalization with probability, not as Normalization with pdf, in histogram() and hist().

Fig. 1 Output of hist() approach, Fig. 2 Output of histogram() approach

enter image description here enter image description here

The max amplitude differs between two approaches which proposes that there are some mistake in hist()'s approach because histogram()'s approach uses the standard normalization. I assume the mistake with hist()'s approach here is about the normalization as partially pdf, not completely as probability.

Code with hist() [deprecated]

Some remarks

  1. First check: sum(f)/N gives 1 if Nbins manually set.
  2. pdf requires the width of the bin (dx) in the graph g

Code

%http://stackoverflow.com/a/5321546/54964
N=10000;
Nbins=50;
[f,x]=hist(randn(N,1),Nbins); % create histogram from ND

%METHOD 4: Count Densities, not Sums!
figure(3)
dx=diff(x(1:2)); % width of bin
g=1/sqrt(2*pi)*exp(-0.5*x.^2) .* dx; % pdf of ND with dx
% 1.0000
bar(x, f/sum(f));hold on
plot(x,g,'r');hold off

Output is in Fig. 1.

Code with histogram()

Some remarks

  1. First check: a) sum(f) is 1 if Nbins adjusted with histogram()'s Normalization as probability, b) sum(f)/N is 1 if Nbins is manually set without normalization.
  2. pdf requires the width of the bin (dx) in the graph g

Code

%%METHOD 5: with histogram()
% http://stackoverflow.com/a/38809232/54964
N=10000;

figure(4);
h = histogram(randn(N,1), 'Normalization', 'probability') % hist() deprecated!
Nbins=h.NumBins;
edges=h.BinEdges; 
x=zeros(1,Nbins);
f=h.Values;
for counter=1:Nbins
    midPointShift=abs(edges(counter)-edges(counter+1))/2; % same constant for all
    x(counter)=edges(counter)+midPointShift;
end
dx=diff(x(1:2)); % constast for all
g=1/sqrt(2*pi)*exp(-0.5*x.^2) .* dx; % pdf of ND
% Use if Nbins manually set
%new_area=sum(f)/N % diff of consecutive edges constant
% Use if histogarm() Normalization probability
new_area=sum(f)
% 1.0000
% No bar() needed here with histogram() Normalization probability
hold on;
plot(x,g,'r');hold off

Output in Fig. 2 and expected output is met: area 1.0000.

Matlab: 2016a
System: Linux Ubuntu 16.04 64 bit
Linux kernel 4.6

Standardize data columns in R

Before I happened to find this thread, I had the same problem. I had user dependant column types, so I wrote a for loop going through them and getting needed columns scale'd. There are probably better ways to do it, but this solved the problem just fine:

 for(i in 1:length(colnames(df))) {
        if(class(df[,i]) == "numeric" || class(df[,i]) == "integer") {
            df[,i] <- as.vector(scale(df[,i])) }
        }

as.vector is a needed part, because it turned out scale does rownames x 1 matrix which is usually not what you want to have in your data.frame.

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

How to update std::map after using the find method?

I would use the operator[].

map <char, int> m1;

m1['G'] ++;  // If the element 'G' does not exist then it is created and 
             // initialized to zero. A reference to the internal value
             // is returned. so that the ++ operator can be applied.

// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'

So using this technique it becomes really easy to read all the character from a stream and count them:

map <char, int>                m1;
std::ifstream                  file("Plop");
std::istreambuf_iterator<char> end;

for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
    ++m1[*loop]; // prefer prefix increment out of habbit
}

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

Time Zone Handling

I just want to clarify, even though this has been commented so future people don't miss this very important distinction.

DateTime.strptime("1318996912",'%s') # => Wed, 19 Oct 2011 04:01:52 +0000

displays a return value in UTC and requires the seconds to be a String and outputs a UTC Time object, whereas

Time.at(1318996912) # => 2011-10-19 00:01:52 -0400

displays a return value in the LOCAL time zone, normally requires a FixNum argument, but the Time object itself is still in UTC even though the display is not.

So even though I passed the same integer to both methods, I seemingly two different results because of how the class' #to_s method works. However, as @Eero had to remind me twice of:

Time.at(1318996912) == DateTime.strptime("1318996912",'%s') # => true

An equality comparison between the two return values still returns true. Again, this is because the values are basically the same (although different classes, the #== method takes care of this for you), but the #to_s method prints drastically different strings. Although, if we look at the strings, we can see they are indeed the same time, just printed in different time zones.

Method Argument Clarification

The docs also say "If a numeric argument is given, the result is in local time." which makes sense, but was a little confusing to me because they don't give any examples of non-integer arguments in the docs. So, for some non-integer argument examples:

Time.at("1318996912")
TypeError: can't convert String into an exact number

you can't use a String argument, but you can use a Time argument into Time.at and it will return the result in the time zone of the argument:

Time.at(Time.new(2007,11,1,15,25,0, "+09:00"))
=> 2007-11-01 15:25:00 +0900

Benchmarks

After a discussion with @AdamEberlin on his answer, I decided to publish slightly changed benchmarks to make everything as equal as possible. Also, I never want to have to build these again so this is as good a place as any to save them.

Time.at(int).to_datetime ~ 2.8x faster

09:10:58-watsw018:~$ ruby -v
ruby 2.3.7p456 (2018-03-28 revision 63024) [universal.x86_64-darwin18]
09:11:00-watsw018:~$ irb
irb(main):001:0> require 'benchmark'
=> true
irb(main):002:0> require 'date'
=> true
irb(main):003:0>
irb(main):004:0* format = '%s'
=> "%s"
irb(main):005:0> times = ['1318996912', '1318496913']
=> ["1318996912", "1318496913"]
irb(main):006:0> int_times = times.map(&:to_i)
=> [1318996912, 1318496913]
irb(main):007:0>
irb(main):008:0* datetime_from_strptime = DateTime.strptime(times.first, format)
=> #<DateTime: 2011-10-19T04:01:52+00:00 ((2455854j,14512s,0n),+0s,2299161j)>
irb(main):009:0> datetime_from_time = Time.at(int_times.first).to_datetime
=> #<DateTime: 2011-10-19T00:01:52-04:00 ((2455854j,14512s,0n),-14400s,2299161j)>
irb(main):010:0>
irb(main):011:0* datetime_from_strptime === datetime_from_time
=> true
irb(main):012:0>
irb(main):013:0* Benchmark.measure do
irb(main):014:1*   100_000.times {
irb(main):015:2*     times.each do |i|
irb(main):016:3*       DateTime.strptime(i, format)
irb(main):017:3>     end
irb(main):018:2>   }
irb(main):019:1> end
=> #<Benchmark::Tms:0x00007fbdc18f0d28 @label="", @real=0.8680500000045868, @cstime=0.0, @cutime=0.0, @stime=0.009999999999999998, @utime=0.86, @total=0.87>
irb(main):020:0>
irb(main):021:0* Benchmark.measure do
irb(main):022:1*   100_000.times {
irb(main):023:2*     int_times.each do |i|
irb(main):024:3*       Time.at(i).to_datetime
irb(main):025:3>     end
irb(main):026:2>   }
irb(main):027:1> end
=> #<Benchmark::Tms:0x00007fbdc3108be0 @label="", @real=0.33059399999910966, @cstime=0.0, @cutime=0.0, @stime=0.0, @utime=0.32000000000000006, @total=0.32000000000000006>

****edited to not be completely and totally incorrect in every way****

****added benchmarks****

Efficient way to rotate a list in python

For a list X = ['a', 'b', 'c', 'd', 'e', 'f'] and a desired shift value of shift less than list length, we can define the function list_shift() as below

def list_shift(my_list, shift):
    assert shift < len(my_list)
    return my_list[shift:] + my_list[:shift]

Examples,

list_shift(X,1) returns ['b', 'c', 'd', 'e', 'f', 'a'] list_shift(X,3) returns ['d', 'e', 'f', 'a', 'b', 'c']

How to handle-escape both single and double quotes in an SQL-Update statement

You can escape the quotes with a backslash:

"I asked my son's teacher, \"How is my son doing now?\""

Submit a form using jQuery

For information
if anyone use

$('#formId').submit();

Do not something like this

<button name = "submit">

It took many hours to find me that submit() won't work like this.

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

It sounds like your site has CSS or JS that depends on running in quirks mode. Which is why you need garbage above your doctype to render "correctly". I suggest removing said garbage and then fixing your CSS+JS to actually work in standards mode; you'll save yourself a lot of pain in the long run.

How are VST Plugins made?

I know this is 3 years old, but for everyone reading this now: Don't stick to VST, AU or any vendor's format. Steinberg has stopped supporting VST2, and people are in trouble porting their code to newer formats, because it's too tied to VST2.

These tutorials cover creating plugins that run on Win/Mac, 32/64, all plugin formats from the same code base.

Date in mmm yyyy format in postgresql

I think in Postgres you can play with formats for example if you want dd/mm/yyyy

TO_CHAR(submit_time, 'DD/MM/YYYY') as submit_date

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

JavaScript get child element

I'd suggest doing something similar to:

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = parent.getElementsByClassName('sub');
        if (sub[0].style.display == 'inline'){
            sub[0].style.display = 'none';
        }
        else {
            sub[0].style.display = 'inline';
        }
    }
}

document.getElementById('cat').onclick = function(){
    show_sub(this.id);
};????

JS Fiddle demo.

Though the above relies on the use of a class rather than a name attribute equal to sub.

As to why your original version "didn't work" (not, I must add, a particularly useful description of the problem), all I can suggest is that, in Chromium, the JavaScript console reported that:

Uncaught TypeError: Object # has no method 'getElementsByName'.

One approach to working around the older-IE family's limitations is to use a custom function to emulate getElementsByClassName(), albeit crudely:

function eBCN(elem,classN){
    if (!elem || !classN){
        return false;
    }
    else {
        var children = elem.childNodes;
        for (var i=0,len=children.length;i<len;i++){
            if (children[i].nodeType == 1
                &&
                children[i].className == classN){
                    var sub = children[i];
            }
        }
        return sub;
    }
}

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = eBCN(parent,'sub');
        if (sub.style.display == 'inline'){
            sub.style.display = 'none';
        }
        else {
            sub.style.display = 'inline';
        }
    }
}

var D = document,
    listElems = D.getElementsByTagName('li');
for (var i=0,len=listElems.length;i<len;i++){
    listElems[i].onclick = function(){
        show_sub(this.id);
    };
}?

JS Fiddle demo.

jQuery creating objects

Another way to make objects in Javascript using JQuery, getting data from the dom and pass it to the object Box and, for example, store them in an array of Boxes, could be:

var box = {}; // my object
var boxes =  []; // my array

$('div.test').each(function (index, value) {
    color = $('p', this).attr('color');
    box = {
        _color: color // being _color a property of `box`
    }
    boxes.push(box);
});

Hope it helps!

Calculate a MD5 hash from a string

A MD5 hash is 128 bits, so you can't represent it in hex with less than 32 characters...

Nginx - Customizing 404 page

You use the error_page property in the nginx config.

For example, if you intend to set the 404 error page to /404.html, use

error_page 404 /404.html;

Setting the 500 error page to /500.html is just as easy as:

error_page 500 /500.html;

CKEditor automatically strips classes from div

Edit: this answer is for those who use ckeditor module in drupal.

I found a solution which doesn't require modifying ckeditor js file.

this answer is copied from here. all credits should goes to original author.

Go to "Admin >> Configuration >> CKEditor"; under Profiles, choose your profile (e.g. Full).

Edit that profile, and on "Advanced Options >> Custom JavaScript configuration" add config.allowedContent = true;.

enter image description here

Don't forget to flush the cache under "Performance tab."

Add Bean Programmatically to Spring Web App Context

Here is a simple code:

ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton(bean.getClass().getCanonicalName(), bean);

How to limit text width

I think what you are trying to do is to wrap long text without spaces.

look at this :Hyphenator.js and it's demo.

jdk7 32 bit windows version to download

Go to the download page and download the Windows x86 version with filename jdk-7-windows-i586.exe.

How to set cellpadding and cellspacing in table with CSS?

Use padding on the cells and border-spacing on the table. The former will give you cellpadding while the latter will give you cellspacing.

table { border-spacing: 5px; } /* cellspacing */

th, td { padding: 5px; } /* cellpadding */

jsFiddle Demo

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

get current date and time in groovy?

Date has the time part, so we only need to extract it from Date

I personally prefer the default format parameter of the Date when date and time needs to be separated instead of using the extra SimpleDateFormat

Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")

println "datePart : " + datePart + "\ttimePart : " + timePart

Working with INTERVAL and CURDATE in MySQL

I usually use

DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)

Which is almost same as Pekka's but this way you can control your INTERVAL to be negative or positive...

Modulo operator in Python

When you have the expression:

a % b = c

It really means there exists an integer n that makes c as small as possible, but non-negative.

a - n*b = c

By hand, you can just subtract 2 (or add 2 if your number is negative) over and over until the end result is the smallest positive number possible:

  3.14 % 2
= 3.14 - 1 * 2
= 1.14

Also, 3.14 % 2 * pi is interpreted as (3.14 % 2) * pi. I'm not sure if you meant to write 3.14 % (2 * pi) (in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).

Arraylist swap elements

You can use Collections.swap(List<?> list, int i, int j);

BarCode Image Generator in Java

There is a free library called barcode4j

MySQL SELECT only not null values

Following query working for me

when i have set default value of column 'NULL' then

select * from table where column IS NOT NULL

and when i have set default value nothing then

select * from table where column <>''

ParseError: not well-formed (invalid token) using cElementTree

This code snippet worked for me. I have an issue with the parsing batch of XML files. I had to encode them to 'iso-8859-5'

import xml.etree.ElementTree as ET

tree = ET.parse(filename, parser = ET.XMLParser(encoding = 'iso-8859-5'))

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

Fun problem: when I glanced at your bottle image I thought it was a can too. But, as a human, what I did to tell the difference is that I then noticed it was also a bottle...

So, to tell cans and bottles apart, how about simply scanning for bottles first? If you find one, mask out the label before looking for cans.

Not too hard to implement if you're already doing cans. The real downside is it doubles your processing time. (But thinking ahead to real-world applications, you're going to end up wanting to do bottles anyway ;-)

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

Ben is right. I also can't think of any way to do this. I'd suggest either the method Ben recommends, or the following to strip the Workbook name off.

Dim cell As Range
Dim address As String
Set cell = Worksheets(1).Cells.Range("A1")
address = cell.address(External:=True)
address = Right(address, Len(address) - InStr(1, address, "]"))

jQuery function after .append

You've got many valid answers in here but none of them really tells you why it works as it does.

In JavaScript commands are executed one at a time, synchronously in the order they come, unless you explicitly tell them to be asynchronous by using a timeout or interval.

This means that your .append method will be executed and nothing else (disregarding any potential timeouts or intervals that may exist) will execute until that method have finished its job.

To summarize, there's no need for a callback since .append will be run synchronously.

Apache is downloading php files instead of displaying them

I had similar symptoms, yet another solution: in /etc/apache2/mods-enabled/php5.conf there was a helpful advice in the comment, which I followed:

# To re-enable php in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.

How do I programmatically "restart" an Android app?

fun triggerRestart(context: Activity) {
    val intent = Intent(context, MainActivity::class.java)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    context.startActivity(intent)
    if (context is Activity) {
        (context as Activity).finish()
    }
    Runtime.getRuntime().exit(0)
}

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

$("#text").val(function(i,v) { 
   return v.replace(".", ":"); 
});

How do I extract data from JSON with PHP?

Intro

First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

 $data = json_decode($json);

Therein you might find:

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.


Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut

Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

Iterate over it with foreach.

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

Glazed
Chocolate with Sprinkles
Maple

Or mess about with any of the bazillion built-in array functions.


Accessing nested items

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004

Passing true as the second argument to json_decode()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key'].

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple

Accessing associative array items

When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value) syntax, eg

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}

Prints

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'


Don't know how the data is structured

Read the documentation for whatever it is you're getting the JSON from.

Look at the JSON - where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a print_r():

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

print_r($yummy);

and check the output:

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

If you can only get so far into it before you get lost - go that far and hit that with print_r():

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

Break the problem down into pieces that are easier to wrap your head around.


json_decode() returns null

This happens because either:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msg or put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.


Object property name contains a special character

Sometimes you'll have an object property name that contains something like a hyphen - or at sign @ which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

If you have an integer as property see: How to access object properties with names like integers? as reference.


Someone put JSON in your JSON

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

Data doesn't fit in memory

If your JSON is too large for json_decode() to handle at once things start to get tricky. See:


How to sort it

See: Reference: all basic ways to sort arrays and data in PHP.

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

How can I move a tag on a git branch to a different commit?

Use the -f option to git tag:

-f
--force

    Replace an existing tag with the given name (instead of failing)

You probably want to use -f in conjunction with -a to force-create an annotated tag instead of a non-annotated one.

Example

  1. Delete the tag on any remote before you push

    git push origin :refs/tags/<tagname>
    
  2. Replace the tag to reference the most recent commit

    git tag -fa <tagname>
    
  3. Push the tag to the remote origin

    git push origin master --tags
    

Javascript to convert UTC to local time

To format your date try the following function:

var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");

But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).

Chris

How to create a release signed apk file using Gradle?

Adding my way to do it in React-Native using react-native-config package.
Create a .env file:

RELEASE_STORE_PASSWORD=[YOUR_PASSWORD]
RELEASE_KEY_PASSWORD=[YOUR_PASSWORD]

note this should not be part of the version control.

in your build.gradle:

signingConfigs {
        debug {
            ...
        }
        release {
            storeFile file(RELEASE_STORE_FILE)
            storePassword project.env.get('RELEASE_STORE_PASSWORD')
            keyAlias RELEASE_KEY_ALIAS
            keyPassword project.env.get('RELEASE_KEY_PASSWORD')
        }
    }

java: HashMap<String, int> not working

You can use reference type in generic arguments, not primitive type. So here you should use

Map<String, Integer> myMap = new HashMap<String, Integer>();

and store value as

myMap.put("abc", 5);

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

On localhost, how do I pick a free port number?

You can listen on whatever port you want; generally, user applications should listen to ports 1024 and above (through 65535). The main thing if you have a variable number of listeners is to allocate a range to your app - say 20000-21000, and CATCH EXCEPTIONS. That is how you will know if a port is unusable (used by another process, in other words) on your computer.

However, in your case, you shouldn't have a problem using a single hard-coded port for your listener, as long as you print an error message if the bind fails.

Note also that most of your sockets (for the slaves) do not need to be explicitly bound to specific port numbers - only sockets that wait for incoming connections (like your master here) will need to be made a listener and bound to a port. If a port is not specified for a socket before it is used, the OS will assign a useable port to the socket. When the master wants to respond to a slave that sends it data, the address of the sender is accessible when the listener receives data.

I presume you will be using UDP for this?

nvarchar(max) still being truncated

Your first problem is a limitation of the PRINT statement. I'm not sure why sp_executesql is failing. It should support pretty much any length of input.

Perhaps the reason the query is malformed is something other than truncation.

Download and install an ipa from self hosted url on iOS

NSURL *url = [NSURL URLWithString:@"itms-services://?action=download-manifest&amp;url=https://xxxxxx.com/rest/images/apps/ipa/dev/xyz.plist"]];
[[UIApplication sharedApplication] openURL:url];

openUrl method was deprecated.

[[UIApplication sharedApplication] openURL: url options:@{} completionHandler:nil];

This method latest openUrl method and it will display prompt dialog.The dialog will show

xxxxxx.com would like to install "YOUR_APP_NAME"

this messages. If you click the "install" button application will close and ipa will download.

How to bind Dataset to DataGridView in windows application

use like this :-

gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();

I hope it helps!!

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

This solution worked for me

1) Click the "Export" tab for the database

2) Click the "Custom" radio button

3) Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.

4) Scroll to the bottom and click "GO".

If it's related to wordpress, more info on why it is happening.

How to add extension methods to Enums

we have just made an enum extension for c# https://github.com/simonmau/enum_ext

It's just a implementation for the typesafeenum, but it works great so we made a package to share - have fun with it

public sealed class Weekday : TypeSafeNameEnum<Weekday, int>
{
    public static readonly Weekday Monday = new Weekday(1, "--Monday--");
    public static readonly Weekday Tuesday = new Weekday(2, "--Tuesday--");
    public static readonly Weekday Wednesday = new Weekday(3, "--Wednesday--");
    ....

    private Weekday(int id, string name) : base(id, name)
    {
    }

    public string AppendName(string input)
    {
        return $"{Name} {input}";
    }
}

I know the example is kind of useless, but you get the idea ;)

How to convert a 3D point into 2D perspective projection?

I see this question is a bit old, but I decided to give an answer anyway for those who find this question by searching.
The standard way to represent 2D/3D transformations nowadays is by using homogeneous coordinates. [x,y,w] for 2D, and [x,y,z,w] for 3D. Since you have three axes in 3D as well as translation, that information fits perfectly in a 4x4 transformation matrix. I will use column-major matrix notation in this explanation. All matrices are 4x4 unless noted otherwise.
The stages from 3D points and to a rasterized point, line or polygon looks like this:

  1. Transform your 3D points with the inverse camera matrix, followed with whatever transformations they need. If you have surface normals, transform them as well but with w set to zero, as you don't want to translate normals. The matrix you transform normals with must be isotropic; scaling and shearing makes the normals malformed.
  2. Transform the point with a clip space matrix. This matrix scales x and y with the field-of-view and aspect ratio, scales z by the near and far clipping planes, and plugs the 'old' z into w. After the transformation, you should divide x, y and z by w. This is called the perspective divide.
  3. Now your vertices are in clip space, and you want to perform clipping so you don't render any pixels outside the viewport bounds. Sutherland-Hodgeman clipping is the most widespread clipping algorithm in use.
  4. Transform x and y with respect to w and the half-width and half-height. Your x and y coordinates are now in viewport coordinates. w is discarded, but 1/w and z is usually saved because 1/w is required to do perspective-correct interpolation across the polygon surface, and z is stored in the z-buffer and used for depth testing.

This stage is the actual projection, because z isn't used as a component in the position any more.

The algorithms:

Calculation of field-of-view

This calculates the field-of view. Whether tan takes radians or degrees is irrelevant, but angle must match. Notice that the result reaches infinity as angle nears 180 degrees. This is a singularity, as it is impossible to have a focal point that wide. If you want numerical stability, keep angle less or equal to 179 degrees.

fov = 1.0 / tan(angle/2.0)

Also notice that 1.0 / tan(45) = 1. Someone else here suggested to just divide by z. The result here is clear. You would get a 90 degree FOV and an aspect ratio of 1:1. Using homogeneous coordinates like this has several other advantages as well; we can for example perform clipping against the near and far planes without treating it as a special case.

Calculation of the clip matrix

This is the layout of the clip matrix. aspectRatio is Width/Height. So the FOV for the x component is scaled based on FOV for y. Far and near are coefficients which are the distances for the near and far clipping planes.

[fov * aspectRatio][        0        ][        0              ][        0       ]
[        0        ][       fov       ][        0              ][        0       ]
[        0        ][        0        ][(far+near)/(far-near)  ][        1       ]
[        0        ][        0        ][(2*near*far)/(near-far)][        0       ]

Screen Projection

After clipping, this is the final transformation to get our screen coordinates.

new_x = (x * Width ) / (2.0 * w) + halfWidth;
new_y = (y * Height) / (2.0 * w) + halfHeight;

Trivial example implementation in C++

#include <vector>
#include <cmath>
#include <stdexcept>
#include <algorithm>

struct Vector
{
    Vector() : x(0),y(0),z(0),w(1){}
    Vector(float a, float b, float c) : x(a),y(b),z(c),w(1){}

    /* Assume proper operator overloads here, with vectors and scalars */
    float Length() const
    {
        return std::sqrt(x*x + y*y + z*z);
    }
    
    Vector Unit() const
    {
        const float epsilon = 1e-6;
        float mag = Length();
        if(mag < epsilon){
            std::out_of_range e("");
            throw e;
        }
        return *this / mag;
    }
};

inline float Dot(const Vector& v1, const Vector& v2)
{
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}

class Matrix
{
    public:
    Matrix() : data(16)
    {
        Identity();
    }
    void Identity()
    {
        std::fill(data.begin(), data.end(), float(0));
        data[0] = data[5] = data[10] = data[15] = 1.0f;
    }
    float& operator[](size_t index)
    {
        if(index >= 16){
            std::out_of_range e("");
            throw e;
        }
        return data[index];
    }
    Matrix operator*(const Matrix& m) const
    {
        Matrix dst;
        int col;
        for(int y=0; y<4; ++y){
            col = y*4;
            for(int x=0; x<4; ++x){
                for(int i=0; i<4; ++i){
                    dst[x+col] += m[i+col]*data[x+i*4];
                }
            }
        }
        return dst;
    }
    Matrix& operator*=(const Matrix& m)
    {
        *this = (*this) * m;
        return *this;
    }

    /* The interesting stuff */
    void SetupClipMatrix(float fov, float aspectRatio, float near, float far)
    {
        Identity();
        float f = 1.0f / std::tan(fov * 0.5f);
        data[0] = f*aspectRatio;
        data[5] = f;
        data[10] = (far+near) / (far-near);
        data[11] = 1.0f; /* this 'plugs' the old z into w */
        data[14] = (2.0f*near*far) / (near-far);
        data[15] = 0.0f;
    }

    std::vector<float> data;
};

inline Vector operator*(const Vector& v, const Matrix& m)
{
    Vector dst;
    dst.x = v.x*m[0] + v.y*m[4] + v.z*m[8 ] + v.w*m[12];
    dst.y = v.x*m[1] + v.y*m[5] + v.z*m[9 ] + v.w*m[13];
    dst.z = v.x*m[2] + v.y*m[6] + v.z*m[10] + v.w*m[14];
    dst.w = v.x*m[3] + v.y*m[7] + v.z*m[11] + v.w*m[15];
    return dst;
}

typedef std::vector<Vector> VecArr;
VecArr ProjectAndClip(int width, int height, float near, float far, const VecArr& vertex)
{
    float halfWidth = (float)width * 0.5f;
    float halfHeight = (float)height * 0.5f;
    float aspect = (float)width / (float)height;
    Vector v;
    Matrix clipMatrix;
    VecArr dst;
    clipMatrix.SetupClipMatrix(60.0f * (M_PI / 180.0f), aspect, near, far);
    /*  Here, after the perspective divide, you perform Sutherland-Hodgeman clipping 
        by checking if the x, y and z components are inside the range of [-w, w].
        One checks each vector component seperately against each plane. Per-vertex
        data like colours, normals and texture coordinates need to be linearly
        interpolated for clipped edges to reflect the change. If the edge (v0,v1)
        is tested against the positive x plane, and v1 is outside, the interpolant
        becomes: (v1.x - w) / (v1.x - v0.x)
        I skip this stage all together to be brief.
    */
    for(VecArr::iterator i=vertex.begin(); i!=vertex.end(); ++i){
        v = (*i) * clipMatrix;
        v /= v.w; /* Don't get confused here. I assume the divide leaves v.w alone.*/
        dst.push_back(v);
    }

    /* TODO: Clipping here */

    for(VecArr::iterator i=dst.begin(); i!=dst.end(); ++i){
        i->x = (i->x * (float)width) / (2.0f * i->w) + halfWidth;
        i->y = (i->y * (float)height) / (2.0f * i->w) + halfHeight;
    }
    return dst;
}

If you still ponder about this, the OpenGL specification is a really nice reference for the maths involved. The DevMaster forums at http://www.devmaster.net/ have a lot of nice articles related to software rasterizers as well.

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Scroll back to the top of scrollable div

For me the scrollTop way did not work, but I found other:

element.style.display = 'none';
setTimeout(function() { element.style.display = 'block' }, 100);

Did not check the minimum time for reliable css rendering though, 100ms might be overkill.

Importing files from different folder

I've had these problems a number of times. I've come to this same page a lot. In my last problem I had to run the server from a fixed directory, but whenever debugging I wanted to run from different sub-directories.

import sys
sys.insert(1, /path) 

did NOT work for me because at different modules I had to read different *.csv files which were all in the same directory.

In the end, what worked for me was not pythonic, I guess, but:

I used a if __main__ on top of the module I wanted to debug, that is run from a different than usual path.

So:

# On top of the module, instead of on the bottom
import os
if __name__ == '__main__':
    os.chdir('/path/for/the/regularly/run/directory')

Webpack.config how to just copy the index.html to the dist folder

You could use the CopyWebpackPlugin. It's working just like this:

module.exports = {
  plugins: [
    new CopyWebpackPlugin([{
      from: './*.html'
    }])
  ]
}

Iterating through all the cells in Excel VBA or VSTO 2005

If you only need to look at the cells that are in use you can use:

sub IterateCells()

   For Each Cell in ActiveSheet.UsedRange.Cells
      'do some stuff
   Next

End Sub

that will hit everything in the range from A1 to the last cell with data (the bottom right-most cell)

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

Spring Boot Adding Http Request Interceptors

I had the same issue of WebMvcConfigurerAdapter being deprecated. When I searched for examples, I hardly found any implemented code. Here is a piece of working code.

create a class that extends HandlerInterceptorAdapter

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import me.rajnarayanan.datatest.DataTestApplication;
@Component
public class EmployeeInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(DataTestApplication.class);
    @Override
    public boolean preHandle(HttpServletRequest request, 
            HttpServletResponse response, Object handler) throws Exception {

            String x = request.getMethod();
            logger.info(x + "intercepted");
        return true;
    }

}

then Implement WebMvcConfigurer interface

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import me.rajnarayanan.datatest.interceptor.EmployeeInterceptor;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    EmployeeInterceptor employeeInterceptor ;

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(employeeInterceptor).addPathPatterns("/employee");
    }
}

JavaScript: Create and destroy class instance through class method

1- There is no way to actually destroy an object in javascript, but using delete, we could remove a reference from an object:

var obj = {};
obj.mypointer = null;
delete obj.mypointer;

2- The important point about the delete keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.

3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}] overriding the value of the array like array = [] would remove the references to the two objects inside the array and those two objects would be marked as collectible.

4- for your solution the easiest way is just this:

var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;

As mentioned above, either setting storage.instance = null or delete storage.instance would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null then the storage object still has a property called instance (with the value null). If you delete storage.instance then the storage object no longer has a property named instance.

and WHAT ABOUT destroy method ??

the paradoxical point here is if you use instance.destroy in the destroy function you have no access to the actual instance pointer, and it won't let you delete it.

The only way is to pass the reference to the destroy function and then delete it:

// Class constructor
var Class = function () {
     this.destroy = function (baseObject, refName) {
         delete baseObject[refName];
     };
};

// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined

BUT if I were you I would simply stick to the first solution and delete the object like this:

storage.instance = null;
// OR
delete storage.instance;

WOW it was too much :)

SET versus SELECT when assigning variables?

Quote, which summarizes from this article:

  1. SET is the ANSI standard for variable assignment, SELECT is not.
  2. SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  3. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  4. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)
  5. As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

Clear Application's Data Programmatically

Try this code

private void clearAppData() {
    try {
        if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
            ((ActivityManager)getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData();
        } else {
            Runtime.getRuntime().exec("pm clear " + getApplicationContext().getPackageName());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Check build.gradle(Module: Android) fixed problem for me.

Modify it to workable version.

android {
    buildToolsVersion '23.0.1'
}

ImportError: No module named 'MySQL'

May be simple install from cli?

pip3 install mysql-connector-python-rf

Package name differs from import library name

Or my universal variant in code:

import pip
pip.main(['install','mysql-connector-python-rf'])

For new version of pip:

from pip._internal import main
main(['install','mysql-connector-python-rf'])

It's better - install needed modules in running python installation (if many)

How do I remove a property from a JavaScript object?

The obvious way to remove a property from an object is to use the delete keyword. this can be done like this:

delete myObject['regex']

or this:

delete myObject.regex

If you are cocerned with mutability, you can create a new object by copying all the properties from the old, except the one you would like to remove

let myObject = {
   ircEvent: "PRIVMSG",
   method: "newURI",
   regex: "^http://.*"
};

const propertyToRemove = 'regex'
const newObject = Object.keys(myObject).reduce((object, key) => {
   if (key !== propertyToRemove ) {
      object[key] = car[key]
   }
return object }, {})

Is it possible to delete an object's property in PHP?

This also works specially if you are looping over an object.

unset($object[$key])

Update

Newer versions of PHP throw fatal error Fatal error: Cannot use object of type Object as array as mentioned by @CXJ . In that case you can use brackets instead

unset($object->{$key})

Making the main scrollbar always visible

An alternative approach is to set the width of the html element to 100vw. On many if not most browsers, this negates the effect of scrollbars on the width.

html { width: 100vw; }

Merge 2 arrays of objects

const extend = function*(ls,xs){
   yield* ls;
   yield* xs;
}

console.log( [...extend([1,2,3],[4,5,6])]  );

How do you programmatically update query params in react-router?

I prefer you to use below function that is ES6 style:

getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .split('&')
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
            )
        : {}
};

TABLOCK vs TABLOCKX

Big difference, TABLOCK will try to grab "shared" locks, and TABLOCKX exclusive locks.

If you are in a transaction and you grab an exclusive lock on a table, EG:

SELECT 1 FROM TABLE WITH (TABLOCKX)

No other processes will be able to grab any locks on the table, meaning all queries attempting to talk to the table will be blocked until the transaction commits.

TABLOCK only grabs a shared lock, shared locks are released after a statement is executed if your transaction isolation is READ COMMITTED (default). If your isolation level is higher, for example: SERIALIZABLE, shared locks are held until the end of a transaction.


Shared locks are, hmmm, shared. Meaning 2 transactions can both read data from the table at the same time if they both hold a S or IS lock on the table (via TABLOCK). However, if transaction A holds a shared lock on a table, transaction B will not be able to grab an exclusive lock until all shared locks are released. Read about which locks are compatible with which at msdn.


Both hints cause the db to bypass taking more granular locks (like row or page level locks). In principle, more granular locks allow you better concurrency. So for example, one transaction could be updating row 100 in your table and another row 1000, at the same time from two transactions (it gets tricky with page locks, but lets skip that).

In general granular locks is what you want, but sometimes you may want to reduce db concurrency to increase performance of a particular operation and eliminate the chance of deadlocks.

In general you would not use TABLOCK or TABLOCKX unless you absolutely needed it for some edge case.

How to Troubleshoot Intermittent SQL Timeout Errors

The issue is because of a bad query the time to executing query is taking more than 60 seconds or a Lock on the Table

The issue looks like a deadlock is occurring; we have queries which are blocking the queries to complete in time. The default timeout for a query is 60 secs and beyond that we will have the SQLException for timeout.

Please check the SQL Server logs for deadlocks. The other way to solve the issue to to increase the Timeout on the Command Object (Temp Solution).

How can I specify the default JVM arguments for programs I run from eclipse?

Yes, right click the project. Click Run as then Run Configurations. You can change the parameters passed to the JVM in the Arguments tab in the VM Arguments box.

That configuration can then be used as the default when running the project.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

for sbt, use below versions

val glassfishEl = "org.glassfish" % "javax.el" % "3.0.1-b09"

val hibernateValidator = "org.hibernate.validator" % "hibernate-validator" % "6.0.17.Final"

val hibernateValidatorCdi = "org.hibernate.validator" % "hibernate-validator-cdi" % "6.0.17.Final"

Escaping double quotes in JavaScript onClick event handler

I think that the best approach is to assign the onclick handler unobtrusively.

Something like this:

window.onload = function(){
    var myLink = document.getElementsById('myLinkId');
    myLink.onclick = function(){ 
        parse('#', false, '<a href="xyz');
        return false;
    }
}

//...


<a href="#" id="myLink">Test</a>

What does -XX:MaxPermSize do?

In Java 8 that parameter is commonly used to print a warning message like this one:

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0

The reason why you get this message in Java 8 is because Permgen has been replaced by Metaspace to address some of PermGen's drawbacks (as you were able to see for yourself, one of those drawbacks is that it had a fixed size).

FYI: an article on Metaspace: http://java-latte.blogspot.in/2014/03/metaspace-in-java-8.html

Select single item from a list

just saw this now, if you are working with a list of object you can try this

 public class user
{
    public string username { get; set; }
    public string password { get; set; }
}

  List<user> userlist = new List<user>();

        userlist.Add(new user { username = "macbruno", password = "1234" });
        userlist.Add(new user { username = "james", password = "5678" });
        string myusername = "james";
        string mypassword = "23432";

  user theUser = userlist.Find(
            delegate (user thisuser)
            {
                return thisuser.username== myusername && thisuser.password == mypassword;
            }
            );

            if (theUser != null)
            {
               Dosomething();
            }
            else
            {
                DoSomethingElse();

            }

RGB to hex and hex to RGB

Based on @MichalPerlakowski answer (EcmaScipt 6) and his answer based on Tim Down's answer

I wrote a modified version of the function of converting hexToRGB with the addition of safe checking if the r/g/b color components are between 0-255 and also the funtions can take Number r/g/b params or String r/g/b parameters and here it is:

 function rgbToHex(r, g, b) {
     r = Math.abs(r);
     g = Math.abs(g);
     b = Math.abs(b);

     if ( r < 0 ) r = 0;
     if ( g < 0 ) g = 0;
     if ( b < 0 ) b = 0;

     if ( r > 255 ) r = 255;
     if ( g > 255 ) g = 255;
     if ( b > 255 ) b = 255;

    return '#' + [r, g, b].map(x => {
      const hex = x.toString(16);
      return hex.length === 1 ? '0' + hex : hex
    }).join('');
  }

To use the function safely - you should ckeck whether the passing string is a real rbg string color - for example a very simple check could be:

if( rgbStr.substring(0,3) === 'rgb' ) {

  let rgbColors = JSON.parse(rgbStr.replace('rgb(', '[').replace(')', ']'))
  rgbStr = this.rgbToHex(rgbColors[0], rgbColors[1], rgbColors[2]);

  .....
}

How to make a transparent border using CSS?

Well if you want fully transparent than you can use

border: 5px solid transparent;

If you mean opaque/transparent, than you can use

border: 5px solid rgba(255, 255, 255, .5);

Here, a means alpha, which you can scale, 0-1.

Also some might suggest you to use opacity which does the same job as well, the only difference is it will result in child elements getting opaque too, yes, there are some work arounds but rgba seems better than using opacity.

For older browsers, always declare the background color using #(hex) just as a fall back, so that if old browsers doesn't recognize the rgba, they will apply the hex color to your element.

Demo

Demo 2 (With a background image for nested div)

Demo 3 (With an img tag instead of a background-image)

body {
    background: url(http://www.desktopas.com/files/2013/06/Images-1920x1200.jpg);   
}

div.wrap {
    border: 5px solid #fff; /* Fall back, not used in fiddle */
    border: 5px solid rgba(255, 255, 255, .5);
    height: 400px;
    width: 400px;
    margin: 50px;
    border-radius: 50%;
}

div.inner {
    background: #fff; /* Fall back, not used in fiddle */
    background: rgba(255, 255, 255, .5);
    height: 380px;
    width: 380px;
    border-radius: 50%; 
    margin: auto; /* Horizontal Center */
    margin-top: 10px; /* Vertical Center ... Yea I know, that's 
                         manually calculated*/
}

Note (For Demo 3): Image will be scaled according to the height and width provided so make sure it doesn't break the scaling ratio.

How to use the 'main' parameter in package.json?

One important function of the main key is that it provides the path for your entry point. This is very helpful when working with nodemon. If you work with nodemon and you define the main key in your package.json as let say "main": "./src/server/app.js", then you can simply crank up the server with typing nodemon in the CLI with root as pwd instead of nodemon ./src/server/app.js.

Get Absolute Position of element within the window in wpf

Since .NET 3.0, you can simply use *yourElement*.TranslatePoint(new Point(0, 0), *theContainerOfYourChoice*).

This will give you the point 0, 0 of your button, but towards the container. (You can also give an other point that 0, 0)

Check here for the doc.

How to remove the default link color of the html hyperlink 'a' tag?

<style>
a {
color:      ;
}
</style>

This code changes the color from the default to what is specified in the style. Using a:hover, you can change the color of the text from the default on hover.

How to add the text "ON" and "OFF" to toggle button

_x000D_
_x000D_
.switch {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  width: 90px;_x000D_
  height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
  position: absolute;_x000D_
  cursor: pointer;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  background-color: #ca2222;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  height: 26px;_x000D_
  width: 26px;_x000D_
  left: 4px;_x000D_
  bottom: 4px;_x000D_
  background-color: white;_x000D_
  -webkit-transition: .4s;_x000D_
  transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
  background-color: #2ab934;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
  box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
  -webkit-transform: translateX(55px);_x000D_
  -ms-transform: translateX(55px);_x000D_
  transform: translateX(55px);_x000D_
}_x000D_
_x000D_
/*------ ADDED CSS ---------*/_x000D_
.on_x000D_
{_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.on, .off_x000D_
{_x000D_
  color: white;_x000D_
  position: absolute;_x000D_
  transform: translate(-50%,-50%);_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  font-size: 10px;_x000D_
  font-family: Verdana, sans-serif;_x000D_
}_x000D_
_x000D_
input:checked+ .slider .on_x000D_
{display: block;}_x000D_
_x000D_
input:checked + .slider .off_x000D_
{display: none;}_x000D_
_x000D_
/*--------- END --------*/_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
  border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
  border-radius: 50%;}
_x000D_
<label class="switch"><input type="checkbox" id="togBtn"><div class="slider round"><!--ADDED HTML --><span class="on">Confirmed</span><span class="off">NA</span><!--END--></div></label>
_x000D_
_x000D_
_x000D_

React-Native: Module AppRegistry is not a registered callable module

For me my issue was putting the wrong entry-file when bundling.

I was using App.js as my entry-file, hence the App couldn't find AppRegistry

Correct:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/

Incorrect:

react-native bundle --platform android --dev false --entry-file App.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/

How to show PIL Image in ipython notebook

You can use IPython's Module: display to load the image. You can read more from the Doc.

from IPython.display import Image 
pil_img = Image(filename='data/empire.jpg')
display(pil_img)

updated

As OP's requirement is to use PIL, if you want to show inline image, you can use matplotlib.pyplot.imshow with numpy.asarray like this too:

from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image

%matplotlib inline
pil_im = Image.open('data/empire.jpg', 'r')
imshow(np.asarray(pil_im))

If you only require a preview rather than an inline, you may just use show like this:

pil_im = Image.open('data/empire.jpg', 'r')
pil_im.show()

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

How to add font-awesome to Angular 2 + CLI project

To use Font Awesome 5 in your Angular project, insert the code below in the of the src/index.html file.

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">

Good luck!

Converting a list to a set changes element order

In case you have a small number of elements in your two initial lists on which you want to do set difference operation, instead of using collections.OrderedDict which complicates the implementation and makes it less readable, you can use:

# initial lists on which you want to do set difference
>>> nums = [1,2,2,3,3,4,4,5]
>>> evens = [2,4,4,6]
>>> evens_set = set(evens)
>>> result = []
>>> for n in nums:
...   if not n in evens_set and not n in result:
...     result.append(n)
... 
>>> result
[1, 3, 5]

Its time complexity is not that good but it is neat and easy to read.

React Native: Possible unhandled promise rejection

Adding here my experience that hopefully might help somebody.

I was experiencing the same issue on Android emulator in Linux with hot reload. The code was correct as per accepted answer and the emulator could reach the internet (I needed a domain name).

Refreshing manually the app made it work. So maybe it has something to do with the hot reloading.

Copy file from source directory to binary directory using CMake

If you want to put the content of example into install folder after build:

code/
  src/
  example/
  CMakeLists.txt

try add the following to your CMakeLists.txt:

install(DIRECTORY example/ DESTINATION example)

Excluding files/directories from Gulp task

Quick answer

On src, you can always specify files to ignore using "!".

Example (you want to exclude all *.min.js files on your js folder and subfolder:

gulp.src(['js/**/*.js', '!js/**/*.min.js'])

You can do it as well for individual files.

Expanded answer:

Extracted from gulp documentation:

gulp.src(globs[, options])

Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.

glob refers to node-glob syntax or it can be a direct file path.

So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.

On minimatch documentation, they point out the following:

if the pattern starts with a ! character, then it is negated.

And that is why using ! symbol will exclude files / directories from a gulp task

Sorting by date & time in descending order?

If you mean you want to sort by date first then by names

SELECT id, name, form_id, DATE(updated_at) as date
  FROM wp_frm_items
  WHERE user_id = 11 && form_id=9
  ORDER BY updated_at DESC,name ASC

This will sort the records by date first, then by names

JAVA_HOME directory in Linux

Just another solution, this one's cross platform (uses java), and points you to the location of the jre.

java -XshowSettings:properties -version 2>&1 > /dev/null | grep 'java.home'

Outputs all of java's current settings, and finds the one called java.home.

For windows, you can go with findstr instead of grep.

java -XshowSettings:properties -version 2>&1 | findstr "java.home"

How to load URL in UIWebView in Swift?

Loading URL to WebView is very easy. Just create a WebView in your storyboard and then you can use the following code to load url.

    let url = NSURL (string: "https://www.simplifiedios.net");
    let request = NSURLRequest(URL: url!);
    webView.loadRequest(request);

As simple as that only 3 lines of codes :)

Ref: UIWebView Example

bash: shortest way to get n-th column of output

Because you seem to be unfamiliar with scripts, here is an example.

#!/bin/sh
# usage: svn st | x 2 | xargs rm
col=$1
shift
awk -v col="$col" '{print $col}' "${@--}"

If you save this in ~/bin/x and make sure ~/bin is in your PATH (now that is something you can and should put in your .bashrc) you have the shortest possible command for generally extracting column n; x n.

The script should do proper error checking and bail if invoked with a non-numeric argument or the incorrect number of arguments, etc; but expanding on this bare-bones essential version will be in unit 102.

Maybe you will want to extend the script to allow a different column delimiter. Awk by default parses input into fields on whitespace; to use a different delimiter, use -F ':' where : is the new delimiter. Implementing this as an option to the script makes it slightly longer, so I'm leaving that as an exercise for the reader.


Usage

Given a file file:

1 2 3
4 5 6

You can either pass it via stdin (using a useless cat merely as a placeholder for something more useful);

$ cat file | sh script.sh 2
2
5

Or provide it as an argument to the script:

$ sh script.sh 2 file
2
5

Here, sh script.sh is assuming that the script is saved as script.sh in the current directory; if you save it with a more useful name somewhere in your PATH and mark it executable, as in the instructions above, obviously use the useful name instead (and no sh).

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

How to check a string for specific characters?

My simple, simple, simple approach! =D

Code

string_to_test = "The criminals stole $1,000,000 in jewels."
chars_to_check = ["$", ",", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for char in chars_to_check:
    if char in string_to_test:
        print("Char \"" + char + "\" detected!")

Output

Char "$" detected!
Char "," detected!
Char "0" detected!
Char "1" detected!

Thanks!

How to show Bootstrap table with sort icon

BOOTSTRAP 4

you can use a combination of

  • fa-chevron-down, fa-chevron-up

  • fa-sort-down, fa-sort-up

<th class="text-center">
    <div class="btn-group" role="group">
        <button type="button" class="btn btn-xs btn-link py-0 pl-0 pr-1">
             Some Text OR icon
        </button>
        <div class="btn-group-vertical">
            <a href="?sort=asc" class="btn btn-xs btn-link p-0">
                <i class="fas fa-sort-up"></i>
            </a>
            <a href="?sort=desc" class="btn btn-xs btn-link p-0">
                <i class="fas fa-sort-down"></i>
            </a>
        </div>
    </div>
</th>

Global Angular CLI version greater than local version

this should solve the issue:

ng update @angular/cli @angular/core

Setting a PHP $_SESSION['var'] using jQuery

A lot of responses on here are addressing the how but not the why. PHP $_SESSION key/value pairs are stored on the server. This differs from a cookie, which is stored on the browser. This is why you are able to access values in a cookie from both PHP and JavaScript. To make matters worse, AJAX requests from the browser do not include any of the cookies you have set for the website. So, you will have to make JavaScript pull the Session ID cookie and include it in every AJAX request for the server to be able to make heads or tails of it. On the bright side, PHP Sessions are designed to fail-over to a HTTP GET or POST variable if cookies are not sent along with the HTTP headers. I would look into some of the principles of RESTful web applications and use of of the design patterns that are common with those kinds of applications instead of trying to mangle with the session handler.

how do I create an infinite loop in JavaScript

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}

git replacing LF with CRLF

  1. Open the file in the Notepad++.
  2. Go to Edit/EOL Conversion.
  3. Click to the Windows Format.
  4. Save the file.

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

I had the same issue on windows 10, after trying all the previous solution the problem persists so I decided to uninstall my python 2.7 and install the version 2.7.13 and it works perfectly.

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

There's no need for all the code mentioned by galambalazs. The cross-browser way to do it in pure JavaScript is simply to test document.readyState:

if (document.readyState === "complete") { init(); }

This is also how jQuery does it.

Depending on where the JavaScript is loaded, this can be done inside an interval:

var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
        clearInterval(readyStateCheckInterval);
        init();
    }
}, 10);

In fact, document.readyState can have three states:

Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded. -- document.readyState at Mozilla Developer Network

So if you only need the DOM to be ready, check for document.readyState === "interactive". If you need the whole page to be ready, including images, check for document.readyState === "complete".

onclick="javascript:history.go(-1)" not working in Chrome

javascript:history.go(-1);

was used in the older browser.IE6. For other browser compatibility try

window.history.go(-1);

where -1 represent the number of pages you want to go back (-1,-2...etc) and return false is required to prevent default event.

For example :

<a href="#" onclick="window.history.go(-1); return false;"> Link </a>   

How to enable Bootstrap tooltip on disabled button?

Working code for Bootstrap 3.3.6

Javascript:

$('body').tooltip({
  selector: '[data-toggle="tooltip"]'
});

$(".btn").click(function(e) {
 if ($(this).hasClass("disabled")){
   e.preventDefault();
 }
});

CSS:

a.btn.disabled, fieldset[disabled] a.btn {
  pointer-events: auto;
}

Disabling Log4J Output in Java

In addition, it is also possible to turn logging off programmatically:

Logger.getRootLogger().setLevel(Level.OFF);

Or

Logger.getRootLogger().removeAllAppenders();
Logger.getRootLogger().addAppender(new NullAppender());

These use imports:

import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.NullAppender;

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

Python variables as keys to dict

This question has practically been answered, but I just wanted to say it was funny that you said

This isn't anything fancy, like putting all local variables into a dictionary.

Because it is actually "fancier"

what you want is:

apple = 1
banana = 'f'
carrot = 3
fruitdict = {}

# I want to set the key equal to variable name, and value equal to variable value
# is there a more Pythonic way to get {'apple': 1, 'banana': 'f', 'carrot': 3}?

names= 'apple banana carrot'.split() # I'm just being lazy for this post
items = globals()                    # or locals()

for name in names:
    fruitdict[name] = items[name]

Honestly, what you are doing is just copying items from one dictionary to another.

(Greg Hewgill practically gave the whole answer, I just made it complete)

...and like people suggested, you should probably be putting these in the dictionary in the first place, but I'll assume that for some reason you can't

Cannot install node modules that require compilation on Windows 7 x64/VS2012

After DAYS of digging, someone on IRC suggested that I try to use the

Windows 7.1 SDK Command Prompt

Shortcut (links to C:\Windows\System32\cmd.exe /E:ON /V:ON /T:0E /K "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd"). I think you MUST have the older 7.1 SDK (even on Windows 8.1) because the newer ones use msbuild.exe instead of vcbuild.exe which is what node-gyp wants even though it's twice as old as node at this point :/

Once in that prompt, I had to run the following to get x86 context because the compiler was throwing as error otherwise about architecture:

setenv.cmd /Release /x86

THEN I was able to successfully run npm commands that were trying to use node-gyp to recompile things.

How to get instance variables in Python?

Both the Vars() and dict methods will work for the example the OP posted, but they won't work for "loosely" defined objects like:

class foo:
  a = 'foo'
  b = 'bar'

To print all non-callable attributes, you can use the following function:

def printVars(object):
    for i in [v for v in dir(object) if not callable(getattr(object,v))]:
        print '\n%s:' % i
        exec('print object.%s\n\n') % i

How to insert image in mysql database(table)?

Please try below code

INSERT INTO xx_BLOB(ID,IMAGE) VALUES(1,LOAD_FILE('E:/Images/jack.jpg'));

AngularJs ReferenceError: angular is not defined

If you've downloaded the angular.js file from Google, you need to make sure that Everyone has Read access to it, or it will not be loaded by your HTML file. By default, it seems to download with No access permissions, so you'll also be getting a message such as:

GET http://localhost/myApp/js/angular.js

This maddened me for about half an hour!

Inserting string at position x of another string

The Underscore.String library has a function that does Insert

insert(string, index, substring) => string

like so

insert("Hello ", 6, "world");
// => "Hello world"

How to export private key from a keystore of self-signed certificate

public static void main(String[] args) {

try {
        String keystorePass = "20174";
        String keyPass = "rav@789";
        String alias = "TyaGi!";
        InputStream keystoreStream = new FileInputStream("D:/keyFile.jks");
        KeyStore keystore = KeyStore.getInstance("JCEKS");
        keystore.load(keystoreStream, keystorePass.toCharArray());
        Key key = keystore.getKey(alias, keyPass.toCharArray());

        byte[] bt = key.getEncoded();
        String s = new String(bt);
        System.out.println("------>"+s);      
        String str12 = Base64.encodeBase64String(bt);

        System.out.println("Fetched Key From JKS : " + str12);

    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
        System.out.println(ex);

    }
}

Override default Spring-Boot application.properties settings in Junit Test

Otherwise we may change the default property configurator name, setting the property spring.config.name=test and then having class-path resource src/test/test.properties our native instance of org.springframework.boot.SpringApplication will be auto-configured from this separated test.properties, ignoring application properties;

Benefit: auto-configuration of tests;

Drawback: exposing "spring.config.name" property at C.I. layer

ref: http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

spring.config.name=application # Config file name

What exactly is Spring Framework for?

Basically Spring is a framework for which is a pattern that allows building very decoupled systems.

The problem

For example, suppose you need to list the users of the system and thus declare an interface called UserLister:

public interface UserLister {
    List<User> getUsers();
}

And maybe an implementation accessing a database to get all the users:

public class UserListerDB implements UserLister {
    public List<User> getUsers() {
        // DB access code here
    }
}

In your view you'll need to access an instance (just an example, remember):

public class SomeView {
    private UserLister userLister;

    public void render() {
        List<User> users = userLister.getUsers();
        view.render(users);
    }
}

Note that the code above hasn't initialized the variable userLister. What should we do? If I explicitly instantiate the object like this:

UserLister userLister = new UserListerDB();

...I'd couple the view with my implementation of the class that access the DB. What if I want to switch from the DB implementation to another that gets the user list from a comma-separated file (remember, it's an example)? In that case, I would go to my code again and change the above line to:

UserLister userLister = new UserListerCommaSeparatedFile();

This has no problem with a small program like this but... What happens in a program that has hundreds of views and a similar number of business classes? The maintenance becomes a nightmare!

Spring (Dependency Injection) approach

What Spring does is to wire the classes up by using an XML file or annotations, this way all the objects are instantiated and initialized by Spring and injected in the right places (Servlets, Web Frameworks, Business classes, DAOs, etc, etc, etc...).

Going back to the example in Spring we just need to have a setter for the userLister field and have either an XML file like this:

<bean id="userLister" class="UserListerDB" />

<bean class="SomeView">
    <property name="userLister" ref="userLister" />
</bean>

or more simply annotate the filed in our view class with @Inject:

@Inject
private UserLister userLister;

This way when the view is created it magically will have a UserLister ready to work.

List<User> users = userLister.getUsers();  // This will actually work
                                           // without adding any line of code

It is great! Isn't it?

  • What if you want to use another implementation of your UserLister interface? Just change the XML.
  • What if don't have a UserLister implementation ready? Program a temporal mock implementation of UserLister and ease the development of the view.
  • What if I don't want to use Spring anymore? Just don't use it! Your application isn't coupled to it. Inversion of Control states: "The application controls the framework, not the framework controls the application".

There are some other options for Dependency Injection around there, what in my opinion has made Spring so famous besides its simplicity, elegance and stability is that the guys of SpringSource have programmed many many POJOs that help to integrate Spring with many other common frameworks without being intrusive in your application. Also, Spring has several good subprojects like Spring MVC, Spring WebFlow, Spring Security and again a loooong list of etceteras.

Hope this helps. Anyway, I encourage you to read Martin Fowler's article about Dependency Injection and Inversion of Control because he does it better than me. After understanding the basics take a look at Spring Documentation, in my opinion, it is used to be the best Spring book ever.

How to disable horizontal scrolling of UIScrollView?

You can select the view, then under Attributes Inspector uncheck User Interaction Enabled .

How to do error logging in CodeIgniter (PHP)

In config.php add or edit the following lines to this:
------------------------------------------------------
$config['log_threshold'] = 4; // (1/2/3)
$config['log_path'] = '/home/path/to/application/logs/';

Run this command in the terminal:
----------------------------------
sudo chmod -R 777 /home/path/to/application/logs/

Index (zero based) must be greater than or equal to zero

Change this line:

The 2 should be 0. Every count starts at 0.

//Aboutme.Text = String.Format("{2}", reader.GetString(0));//wrong

//Aboutme.Text = String.Format("{0}", reader.GetString(0));//correct

Why should a Java class implement comparable?

Quoted from the javadoc;

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

Edit: ..and made the important bit bold.

PHP - remove <img> tag from string

You need to assign the result back to $content as preg_replace does not modify the original string.

$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);

Insert current date in datetime format mySQL

Just use with your timezone :

date_default_timezone_set('Asia/Kolkata');      
$date=date("Y/m/d h:i:sa");

How to set selected value of jquery select2?

This may help someone loading select2 data from AJAX while loading data for editing (applicable for single or multi-select):

During my form/model load :

  $.ajax({
        type: "POST",
        ...        
        success: function (data) {
          selectCountries(fixedEncodeURI(data.countries));
         }

Call to select data for Select2:

var countrySelect = $('.select_country');
function selectCountries(countries)
    {
        if (countries) {
            $.ajax({
                type: 'GET',
                url: "/regions/getCountries/",
                data: $.param({ 'idsSelected': countries }, true),

            }).then(function (data) {
                // create the option and append to Select2                     
                $.each(data, function (index, value) {
                    var option = new Option(value.text, value.id, true, true);
                    countrySelect.append(option).trigger('change');
                    console.log(option);
                });
                // manually trigger the `select2:select` event
                countrySelect.trigger({
                    type: 'select2:select',
                    params: {
                        data: data
                    }
                });
            });
        }
    }

and if you may be having issues with encoding you may change as your requirement:

function fixedEncodeURI(str) {
        return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%22/g,"");

    }

Gridview get Checkbox.Checked value

If you want a method other than findcontrol try the following:

 GridViewRow row = Gridview1.SelectedRow;
 int CustomerId = int.parse(row.Cells[0].Text);// to get the column value
 CheckBox checkbox1= row.Cells[0].Controls[0] as CheckBox; // you can access the controls like this

How do I change the language of moment.js?

I'm using angular2-moment, but usage must be similar.

import { MomentModule } from "angular2-moment";
import moment = require("moment");

export class AppModule {

  constructor() {
    moment.locale('ru');
  }
}

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

Try this one

var getValue = cmd.ExecuteScalar();    
conn.Close();
return (getValue == null) ? string.Empty : getValue.ToString();

How to redirect in a servlet filter?

Try and check of your ServletResponse response is an instanceof HttpServletResponse like so:

if (response instanceof HttpServletResponse) {
    response.sendRedirect(....);
}

Using Bootstrap Tooltip with AngularJS

You can use selector option for dynamic single page applications:

jQuery(function($) {
    $(document).tooltip({
        selector: '[data-toggle="tooltip"]'
    });
});

if a selector is provided, tooltip objects will be delegated to the specified targets. In practice, this is used to enable dynamic HTML content to have tooltips added.

How to compare oldValues and newValues on React Hooks useEffect?

Incase anybody is looking for a TypeScript version of usePrevious:

In a .tsx module:

import { useEffect, useRef } from "react";

const usePrevious = <T extends unknown>(value: T): T | undefined => {
  const ref = useRef<T>();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

Or in a .ts module:

import { useEffect, useRef } from "react";

const usePrevious = <T>(value: T): T | undefined => {
  const ref = useRef<T>();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

Pass multiple optional parameters to a C# function

1.You can make overload functions.

SomeF(strin s){}   
SomeF(string s, string s2){}    
SomeF(string s1, string s2, string s3){}   

More info: http://csharpindepth.com/Articles/General/Overloading.aspx

2.or you may create one function with params

SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like

More info: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

3.or you can use simple array

Main(string[] args){}

Print in one line dynamically

Change print item to:

  • print item, in Python 2.7
  • print(item, end=" ") in Python 3

If you want to print the data dynamically use following syntax:

  • print(item, sep=' ', end='', flush=True) in Python 3

Jersey Exception : SEVERE: A message body reader for Java class

Q) Code was working fine in Intellj but failing in command line.

Sol) Add dependencies of jersey as a direct dependency rather than a transient one.

Reasoning: Since, it was working fine with IntelliJ, dependencies are correctly configured.

  1. Get required dependencies by one of the following:

    1. check for the IntelliJ running command. Stackoverflow-link
    2. List dependencies from maven mvn dependency:tree
  2. Now, add those problematic jersey dependencies explicitly.

Custom CSS Scrollbar for Firefox

Firefox 64 adds support for the spec draft CSS Scrollbars Module Level 1, which adds two new properties of scrollbar-width and scrollbar-color which give some control over how scrollbars are displayed.

You can set scrollbar-color to one of the following values (descriptions from MDN):

  • auto Default platform rendering for the track portion of the scrollbar, in the absence of any other related scrollbar color properties.
  • dark Show a dark scrollbar, which can be either a dark variant of scrollbar provided by the platform, or a custom scrollbar with dark colors.
  • light Show a light scrollbar, which can be either a light variant of scrollbar provided by the platform, or a custom scrollbar with light colors.
  • <color> <color> Applies the first color to the scrollbar thumb, the second to the scrollbar track.

Note that dark and light values are not currently implemented in Firefox.

macOS notes:

The auto-hiding semi-transparent scrollbars that are the macOS default cannot be colored with this rule (they still choose their own contrasting color based on the background). Only the permanently showing scrollbars (System Preferences > Show Scroll Bars > Always) are colored.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 20%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-color-auto {_x000D_
  scrollbar-color: auto;_x000D_
}_x000D_
.scroll-color-dark {_x000D_
  scrollbar-color: dark;_x000D_
}_x000D_
.scroll-color-light {_x000D_
  scrollbar-color: light;_x000D_
}_x000D_
.scroll-color-colors {_x000D_
  scrollbar-color: orange lightyellow;_x000D_
}
_x000D_
<div class="scroll scroll-color-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-dark">_x000D_
<p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-light">_x000D_
<p>light</p><p>light</p><p>light</p><p>light</p><p>light</p><p>light</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-colors">_x000D_
<p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can set scrollbar-width to one of the following values (descriptions from MDN):

  • auto The default scrollbar width for the platform.
  • thin A thin scrollbar width variant on platforms that provide that option, or a thinner scrollbar than the default platform scrollbar width.
  • none No scrollbar shown, however the element will still be scrollable.

You can also set a specific length value, according to the spec. Both thin and a specific length may not do anything on all platforms, and what exactly it does is platform-specific. In particular, Firefox doesn't appear to be currently support a specific length value (this comment on their bug tracker seems to confirm this). The thin keywork does appear to be well-supported however, with macOS and Windows support at-least.

It's probably worth noting that the length value option and the entire scrollbar-width property are being considered for removal in a future draft, and if that happens this particular property may be removed from Firefox in a future version.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 30%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-width-auto {_x000D_
  scrollbar-width: auto;_x000D_
}_x000D_
.scroll-width-thin {_x000D_
  scrollbar-width: thin;_x000D_
}_x000D_
.scroll-width-none {_x000D_
  scrollbar-width: none;_x000D_
}
_x000D_
<div class="scroll scroll-width-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-thin">_x000D_
<p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-none">_x000D_
<p>none</p><p>none</p><p>none</p><p>none</p><p>none</p><p>none</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to hide collapsible Bootstrap 4 navbar on click

add below code in your < a > TAG

data-toggle="collapse" data-target=".navbar-collapse.show"

as shows below in every TAG

<li class="nav-item">
   <a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
</li>

Angular 5 Button Submit On Enter Key Press

Try to use keyup.enter but make sure to use it inside your input tag

<input
  matInput
  placeholder="enter key word"
  [(ngModel)]="keyword"
  (keyup.enter)="addToKeywords()"
/>

Can you create nested WITH clauses for Common Table Expressions?

we can create nested cte.please see the below cte in example

;with cte_data as 
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from [HumanResources].[Department]
)

select * from cte_data,cte_data1

What is the purpose of the : (colon) GNU Bash builtin?

Another way, not yet mentioned here is the initialisation of parameters in infinite while-loops. Below is not the cleanest example, but it serves it's purpose.

#!/usr/bin/env bash
[ "$1" ] && foo=0 && bar="baz"
while : "${foo=2}" "${bar:=qux}"; do
    echo "$foo"
    (( foo == 3 )) && echo "$bar" && break
    (( foo=foo+1 ))
done

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

I think my ugly one-liners are just necessary here.

z = next(z.update(y) or z for z in [x.copy()])
# or
z = (lambda z: z.update(y) or z)(x.copy())
  1. Dicts are merged.
  2. Single expression.
  3. Don't ever dare to use it.

P.S. This is a solution working in both versions of Python. I know that Python 3 has this {**x, **y} thing and it is the right thing to use (as well as moving to Python 3 if you still have Python 2 is the right thing to do).

ASP.NET MVC Global Variables

You could also use a static class, such as a Config class or something along those lines...

public static class Config
{
    public static readonly string SomeValue = "blah";
}

Align text to the bottom of a div

Flex Solution

It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

_x000D_
_x000D_
.wrap {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border: 1px solid #aaa;_x000D_
  margin: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
  align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <span>Align me to the bottom</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.


Old Solution (Valid if you are not willing to use flex)

If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

_x000D_
_x000D_
div {_x000D_
  display: table-cell;_x000D_
  vertical-align: bottom;_x000D_
  border: 1px solid #f00;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
_x000D_
_x000D_

(Or JSFiddle)

How to capture a list of specific type with mockito

Yeah, this is a general generics problem, not mockito-specific.

There is no class object for ArrayList<SomeType>, and thus you can't type-safely pass such an object to a method requiring a Class<ArrayList<SomeType>>.

You can cast the object to the right type:

Class<ArrayList<SomeType>> listClass =
              (Class<ArrayList<SomeType>>)(Class)ArrayList.class;
ArgumentCaptor<ArrayList<SomeType>> argument = ArgumentCaptor.forClass(listClass);

This will give some warnings about unsafe casts, and of course your ArgumentCaptor can't really differentiate between ArrayList<SomeType> and ArrayList<AnotherType> without maybe inspecting the elements.

(As mentioned in the other answer, while this is a general generics problem, there is a Mockito-specific solution for the type-safety problem with the @Captor annotation. It still can't distinguish between an ArrayList<SomeType> and an ArrayList<OtherType>.)

Edit:

Take also a look at tenshis comment. You can change the original code from Paulo Ebermann to this (much simpler)

final ArgumentCaptor<List<SomeType>> listCaptor
        = ArgumentCaptor.forClass((Class) List.class);

Why shouldn't `&apos;` be used to escape single quotes?

&quot; is on the official list of valid HTML 4 entities, but &apos; is not.

From C.16. The Named Character Reference ':

The named character reference &apos; (the apostrophe, U+0027) was introduced in XML 1.0 but does not appear in HTML. Authors should therefore use &#39; instead of &apos; to work as expected in HTML 4 user agents.

Parse JSON object with string and value only

My pseudocode example will be as follows:

JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();

for (each json in jsonArray) {
    String id = json.get("id");
    String name = json.get("name");

    newJson.put(id, name);
}

return newJson;

How to install requests module in Python 3.4, instead of 2.7

Just answering this old thread can be installed without pip On windows or Linux:

1) Download Requests from https://github.com/kennethreitz/requests click on clone or download button

2) Unzip the files in your python directory .Exp your python is installed in C:Python\Python.exe then unzip there

3) Depending on the Os run the following command:

  • Windows use command cd to your python directory location then setup.py install
  • Linux command: python setup.py install

Thats it :)

Concatenating two std::vectors

vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2 = {11, 12, 13, 14, 15};
copy(v2.begin(), v2.end(), back_inserter(v1));

Writing to a TextBox from another thread?

Have a look at Control.BeginInvoke method. The point is to never update UI controls from another thread. BeginInvoke will dispatch the call to the UI thread of the control (in your case, the Form).

To grab the form, remove the static modifier from the sample function and use this.BeginInvoke() as shown in the examples from MSDN.

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I had the exact same problem, but the solution to my problem was entirely different. I had, somewhere else in the database, a foreign key with the same name. That caused the error 1005.

Renaming my foreign key to something more specific to that situation solved the problem.

How can I get a file's size in C++?

Using standard library:

Assuming that your implementation meaningfully supports SEEK_END:

fseek(f, 0, SEEK_END); // seek to end of file
size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
// proceed with allocating memory and reading the file

Linux/POSIX:

You can use stat (if you know the filename), or fstat (if you have the file descriptor).

Here is an example for stat:

#include <sys/stat.h>
struct stat st;
stat(filename, &st);
size = st.st_size;

Win32:

You can use GetFileSize or GetFileSizeEx.

Get index of a key in json

Its too late, but it may be simple and useful

var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };
var keytoFind = "key2";
var index = Object.keys(json).indexOf(keytoFind);
alert(index);

Node.js setting up environment specific configs to be used with everyauth

An elegant way is to use .env file to locally override production settings. No need for command line switches. No need for all those commas and brackets in a config.json file. See my answer here

Example: on my machine the .env file is this:

NODE_ENV=dev
TWITTER_AUTH_TOKEN=something-needed-for-api-calls

My local .env overrides any environment variables. But on the staging or production servers (maybe they're on heroku.com) the environment variables are pre-set to stage NODE_ENV=stage or production NODE_ENV=prod.

Python pandas: fill a dataframe row by row

This is a simpler version

import pandas as pd
df = pd.DataFrame(columns=('col1', 'col2', 'col3'))
for i in range(5):
   df.loc[i] = ['<some value for first>','<some value for second>','<some value for third>']`

Travel/Hotel API's?

You could probably trying using Yahoo or Google's APIs. They are generic, but by specifying the right set of parameters, you could probably narrow down the results to just hotels. Check out Yahoo's Local Search API and Google's Local Search API

What is the difference between `sorted(list)` vs `list.sort()`?

The .sort() function stores the value of new list directly in the list variable; so answer for your third question would be NO. Also if you do this using sorted(list), then you can get it use because it is not stored in the list variable. Also sometimes .sort() method acts as function, or say that it takes arguments in it.

You have to store the value of sorted(list) in a variable explicitly.

Also for short data processing the speed will have no difference; but for long lists; you should directly use .sort() method for fast work; but again you will face irreversible actions.

Removing an element from an Array (Java)

Swap the item to be removed with the last item, if resizing the array down is not an interest.

Check if the file exists using VBA

Use the Office FileDialog object to have the user pick a file from the filesystem. Add a reference in your VB project or in the VBA editor to Microsoft Office Library and look in the help. This is much better than having people enter full paths.

Here is an example using msoFileDialogFilePicker to allow the user to choose multiple files. You could also use msoFileDialogOpen.

'Note: this is Excel VBA code
Public Sub LogReader()
    Dim Pos As Long
    Dim Dialog As Office.FileDialog
    Set Dialog = Application.FileDialog(msoFileDialogFilePicker)

    With Dialog
        .AllowMultiSelect = True
        .ButtonName = "C&onvert"
        .Filters.Clear
        .Filters.Add "Log Files", "*.log", 1
        .Title = "Convert Logs to Excel Files"
        .InitialFileName = "C:\InitialPath\"
        .InitialView = msoFileDialogViewList

        If .Show Then
            For Pos = 1 To .SelectedItems.Count
                LogRead .SelectedItems.Item(Pos) ' process each file
            Next
        End If
    End With
End Sub

There are lots of options, so you'll need to see the full help files to understand all that is possible. You could start with Office 2007 FileDialog object (of course, you'll need to find the correct help for the version you're using).

How to create websockets server in PHP

I've searched the minimal solution possible to do PHP + WebSockets during hours, until I found this article:

Super simple PHP WebSocket example

It doesn't require any third-party library.

Here is how to do it: create a index.html containing this:

<html>
<body>
    <div id="root"></div>
    <script>
        var host = 'ws://<<<IP_OF_YOUR_SERVER>>>:12345/websockets.php';
        var socket = new WebSocket(host);
        socket.onmessage = function(e) {
            document.getElementById('root').innerHTML = e.data;
        };
    </script>
</body>
</html>

and open it in the browser, just after you have launched php websockets.php in the command-line (yes, it will be an event loop, constantly running PHP script), with this websockets.php file.

Find files containing a given text

find them and grep for the string:

This will find all files of your 3 types in /starting/path and grep for the regular expression '(document\.cookie|setcookie)'. Split over 2 lines with the backslash just for readability...

find /starting/path -type f -name "*.php" -o -name "*.html" -o -name "*.js" | \
 xargs egrep -i '(document\.cookie|setcookie)'

How do I print the content of a .txt file in Python?

Reading and printing the content of a text file (.txt) in Python3

Consider this as the content of text file with the name world.txt:

Hello World! This is an example of Content of the Text file we are about to read and print
using python!

First we will open this file by doing this:

file= open("world.txt", 'r')

Now we will get the content of file in a variable using .read() like this:

content_of_file= file.read()

Finally we will just print the content_of_file variable using print command.

print(content_of_file)

Output:

Hello World! This is an example of Content of the Text file we are about to read and print using python!

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

What's is the difference between train, validation and test set, in neural networks?

Cross-validation set is used for model selection, for example, select the polynomial model with the least amount of errors for a given parameter set. The test set is then used to report the generalization error on the selected model. From here: https://www.coursera.org/learn/machine-learning/lecture/QGKbr/model-selection-and-train-validation-test-sets

How to construct a REST API that takes an array of id's for the resources

I find another way of doing the same thing by using @PathParam. Here is the code sample.

@GET
@Path("data/xml/{Ids}")
@Produces("application/xml")
public Object getData(@PathParam("zrssIds") String Ids)
{
  System.out.println("zrssIds = " + Ids);
  //Here you need to use String tokenizer to make the array from the string.
}

Call the service by using following url.

http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76

where

http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76

How do I alias commands in git?

Follwing are the 4 git shortcuts or aliases youc an use to save time.

Open the commandline and type these below 4 commands and use the shortcuts after.

git config --global alias.co checkout  
git config --global alias.ci commit    
git config --global alias.st status    
git config --global alias.br branch  

Now test them!

$ git co              # use git co instead of git checkout
$ git ci              # use git ci instead of git commit
$ git st              # use git st instead of git status
$ git br              # use git br instead of git branch

What is the difference between a static method and a non-static method?

Well, more technically speaking, the difference between a static method and a virtual method is the way the are linked.

A traditional "static" method like in most non OO languages gets linked/wired "statically" to its implementation at compile time. That is, if you call method Y() in program A, and link your program A with library X that implements Y(), the address of X.Y() is hardcoded to A, and you can not change that.

In OO languages like JAVA, "virtual" methods are resolved "late", at run-time, and you need to provide an instance of a class. So in, program A, to call virtual method Y(), you need to provide an instance, B.Y() for example. At runtime, every time A calls B.Y() the implementation called will depend on the instance used, so B.Y() , C.Y() etc... could all potential provide different implementations of Y() at runtime.

Why will you ever need that? Because that way you can decouple your code from the dependencies. For example, say program A is doing "draw()". With a static language, thats it, but with OO you will do B.draw() and the actual drawing will depend on the type of object B, which, at runtime, can change to square a circle etc. That way your code can draw multiple things with no need to change, even if new types of B are provided AFTER the code was written. Nifty -

CURRENT_DATE/CURDATE() not working as default DATE value

Currently from MySQL 8 you can set the following to a DATE column:

In MySQL Workbench, in the Default field next to the column, write: (curdate())

If you put just curdate() it will fail. You need the extra ( and ) at the beginning and end.

Min / Max Validator in Angular 2 Final

In your code you are using min and not minlength. Please also notice that this will not validate if a number is > 0 but its length.

Align a div to center

This has always worked for me.

Provided you set a fixed width for your DIV, and the proper DOCTYPE, try this

div {        
  margin-left:auto;
  margin-right:auto;
}

Hope this helps.

How to add display:inline-block in a jQuery show() function?

Best way is to add !important suffix to the selector .

Example:

 #selector{
     display: inline-block !important;                   
}

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

Make sure to not require a package before making sure the vendor folder exists.

Check if you have done composer install before. You may be just cloned the repository to your machine. So, you have to install the old packages before requiring a new one. Or you may want to include this option --profile to your composer command to see the timing and memory usage information.

Angular 2.0 router not working on reloading the browser

I checked in angular 2 seed how it works.

You can use express-history-api-fallback to redirect automatically when a page is reload.

I think it's the most elegant way to resolve this problem IMO.

.autocomplete is not a function Error

Note that if you're not using the full jquery UI library, this can be triggered if you're missing Widget, Menu, Position, or Core. There might be different dependencies depending on your version of jQuery UI

How can I get browser to prompt to save password?

The truth is, you can't force the browser to ask. I'm sure the browser has it's own algorithm for guessing if you've entered a username/password, such as looking for an input of type="password" but you cannot set anything to force the browser.

You could, as others suggest, add user information in a cookie. If you do this, you better encrypt it at the least and do not store their password. Perhaps store their username at most.

How to disable copy/paste from/to EditText

In addition to the setCustomSelectionActionModeCallback, and disabled long-click solutions, it's necessary to prevent the PASTE/REPLACE menus from appearing when the text selection handle is clicked, as per the image below:

Text selection handle with paste menu

The solution lies in preventing PASTE/REPLACE menu from appearing in the show() method of the (non-documented) android.widget.Editor class. Before the menu appears, a check is done to if (!canPaste && !canSuggest) return;. The two methods that are used as the basis to set these variables are both in the EditText class:

A more complete answer is available here.

How to resize Twitter Bootstrap modal dynamically based on the content

As of Bootstrap 4 - it has a style of:

@media (min-width: 576px)
.modal-dialog {
    max-width: 500px;
}

so if you are looking to resize the modal width to some-width larger, I would suggest using this in your css for example:

.modal-dialog { max-width: 87vw; }

Note that setting width: 87vw; will not override bootstrap's max-width: 500px;.

When should I use git pull --rebase?

I think you should use git pull --rebase when collaborating with others on the same branch. You are in your work ? commit ? work ? commit cycle, and when you decide to push your work your push is rejected, because there's been parallel work on the same branch. At this point I always do a pull --rebase. I do not use squash (to flatten commits), but I rebase to avoid the extra merge commits.

As your Git knowledge increases you find yourself looking a lot more at history than with any other version control systems I've used. If you have a ton of small merge commits, it's easy to lose focus of the bigger picture that's happening in your history.

This is actually the only time I do rebasing(*), and the rest of my workflow is merge based. But as long as your most frequent committers do this, history looks a whole lot better in the end.

(*) While teaching a Git course, I had a student arrest me on this, since I also advocated rebasing feature branches in certain circumstances. And he had read this answer ;) Such rebasing is also possible, but it always has to be according to a pre-arranged/agreed system, and as such should not "always" be applied. And at that time I usually don't do pull --rebase either, which is what the question is about ;)

Angular 4 default radio button checked by default

if you're using reactive forms then you can use the following way. consider the following example.

in component.html

 `<p class="mr-3"> Require Shipping: 

          <input type="radio" class="ml-2" value="true" name="requiresShipping" 
           id="requiresShipping" formControlName="requiresShipping">

                   &nbsp;  Yes  &nbsp;

          <input type="radio" class="ml-2" value="false" name="requiresShipping" 
          id="requiresShipping" formControlName="requiresShipping">

                   &nbsp;  No   &nbsp;
 </p>`

in component.ts

`
 export class ClassName implements OnInit {
      public yourForm: FormGroup
      
      constructor(
            private fromBuilder: FormBuilder
      ) {
            this.yourForm= this.fromBuilder.group({
                  requiresShipping: this.fromBuilder.control('true'),
            })
        }
 }

`

now you will get the default selected radio button.

enter image description here

Eclipse IDE: How to zoom in on text?

What I am doing is using the Windows 10 magnifier. Not the same as zooming on firefox, but it has been quite useful.

Add text at the end of each line

You could try using something like:

sed -n 's/$/:80/' ips.txt > new-ips.txt

Provided that your file format is just as you have described in your question.

The s/// substitution command matches (finds) the end of each line in your file (using the $ character) and then appends (replaces) the :80 to the end of each line. The ips.txt file is your input file... and new-ips.txt is your newly-created file (the final result of your changes.)


Also, if you have a list of IP numbers that happen to have port numbers attached already, (as noted by Vlad and as given by aragaer,) you could try using something like:

sed '/:[0-9]*$/ ! s/$/:80/' ips.txt > new-ips.txt

So, for example, if your input file looked something like this (note the :80):

127.0.0.1
128.0.0.0:80
121.121.33.111

The final result would look something like this:

127.0.0.1:80
128.0.0.0:80
121.121.33.111:80

Generate random 5 characters string

Source: PHP Function that Generates Random Characters

This simple PHP function worked for me:

function cvf_ps_generate_random_code($length=10) {

   $string = '';
   // You can define your own characters here.
   $characters = "23456789ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz";

   for ($p = 0; $p < $length; $p++) {
       $string .= $characters[mt_rand(0, strlen($characters)-1)];
   }

   return $string;

}

Usage:

echo cvf_ps_generate_random_code(5);

How do I open workbook programmatically as read-only?

Does this work?

Workbooks.Open Filename:=filepath, ReadOnly:=True

Or, as pointed out in a comment, to keep a reference to the opened workbook:

Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)

Conditional Replace Pandas

.ix indexer works okay for pandas version prior to 0.20.0, but since pandas 0.20.0, the .ix indexer is deprecated, so you should avoid using it. Instead, you can use .loc or iloc indexers. You can solve this problem by:

mask = df.my_channel > 20000
column_name = 'my_channel'
df.loc[mask, column_name] = 0

Or, in one line,

df.loc[df.my_channel > 20000, 'my_channel'] = 0

mask helps you to select the rows in which df.my_channel > 20000 is True, while df.loc[mask, column_name] = 0 sets the value 0 to the selected rows where maskholds in the column which name is column_name.

Update: In this case, you should use loc because if you use iloc, you will get a NotImplementedError telling you that iLocation based boolean indexing on an integer type is not available.

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

If you see those characters you probably just didn’t specify the character encoding properly. Because those characters are the result when an UTF-8 multi-byte string is interpreted with a single-byte encoding like ISO 8859-1 or Windows-1252.

In this case ë could be encoded with 0xC3 0xAB that represents the Unicode character ë (U+00EB) in UTF-8.

Checking if a key exists in a JavaScript object?

A fast and easy solution is to convert your object to json then you will be able to do this easy task:

const allowed = {
    '/login' : '',
    '/register': '',
    '/resetpsw': ''
};
console.log('/login' in allowed); //returns true

If you use an array the object key will be converted to integers ex 0,1,2,3 etc. therefore, it will always be false

How get total sum from input box values using Javascript?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
_x000D_
  //iterate through each textboxes and add keyup_x000D_
  //handler to trigger sum event_x000D_
  $(".txt").each(function() {_x000D_
_x000D_
   $(this).keyup(function(){_x000D_
    calculateSum();_x000D_
   });_x000D_
  });_x000D_
_x000D_
 });_x000D_
_x000D_
 function calculateSum() {_x000D_
_x000D_
  var sum = 0;_x000D_
  //iterate through each textboxes and add the values_x000D_
  $(".txt").each(function() {_x000D_
_x000D_
   //add only if the value is number_x000D_
   if(!isNaN(this.value) && this.value.length!=0) {_x000D_
    sum += parseFloat(this.value);_x000D_
   }_x000D_
_x000D_
  });_x000D_
  //.toFixed() method will roundoff the final sum to 2 decimal places_x000D_
  $("#sum").html(sum.toFixed(2));_x000D_
 }
_x000D_
body {_x000D_
    font-family: sans-serif;_x000D_
   }_x000D_
   #summation {_x000D_
    font-size: 18px;_x000D_
    font-weight: bold;_x000D_
    color:#174C68;_x000D_
   }_x000D_
   .txt {_x000D_
    background-color: #FEFFB0;_x000D_
    font-weight: bold;_x000D_
    text-align: right;_x000D_
   }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">_x000D_
 <tr>_x000D_
  <td width="40px">1</td>_x000D_
  <td>Butter</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>2</td>_x000D_
  <td>Cheese</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>3</td>_x000D_
  <td>Eggs</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>4</td>_x000D_
  <td>Milk</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>5</td>_x000D_
  <td>Bread</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>6</td>_x000D_
  <td>Soap</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr id="summation">_x000D_
  <td>&nbsp;</td>_x000D_
  <td align="right">Sum :</td>_x000D_
  <td align="center"><span id="sum">0</span></td>_x000D_
 </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Example use of "continue" statement in Python?

Here's a simple example:

for letter in 'Django':    
    if letter == 'D':
        continue
    print("Current Letter: " + letter)

Output will be:

Current Letter: j
Current Letter: a
Current Letter: n
Current Letter: g
Current Letter: o

It continues to the next iteration of the loop.

How to get first character of a string in SQL?

SELECT SUBSTR(thatColumn, 1, 1) As NewColumn from student

Check if a string contains another string

Building on Rene's answer, you could also write a function that returned either TRUE if the substring was present, or FALSE if it wasn't:

Public Function Contains(strBaseString As String, strSearchTerm As String) As Boolean
'Purpose: Returns TRUE if one string exists within another
On Error GoTo ErrorMessage
    Contains = InStr(strBaseString, strSearchTerm)
Exit Function
ErrorMessage:
MsgBox "The database has generated an error. Please contact the database administrator, quoting the following error message: '" & Err.Description & "'", vbCritical, "Database Error"
End
End Function

Setting the JVM via the command line on Windows

You should be able to do this via the command line arguments, assuming these are Sun VMs installed using the usual Windows InstallShield mechanisms with the JVM finder EXE in system32.

Type java -help for the options. In particular, see:

-version:<value>
              require the specified version to run
-jre-restrict-search | -jre-no-restrict-search
              include/exclude user private JREs in the version search

AngularJS - $http.post send data as json

Use JSON.stringify() to wrap your json

var parameter = JSON.stringify({type:"user", username:user_email, password:user_password});
    $http.post(url, parameter).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        console.log(data);
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

Getting Textarea Value with jQuery

change id="#message" to id="message" on your textarea element.

and by the way, just use this:

$('#send-thoughts')

remember that you should only use ID's once and you can use classes over and over.

https://css-tricks.com/the-difference-between-id-and-class/

What is the difference between & and && in Java?

boolean a, b;

Operation     Meaning                       Note
---------     -------                       ----
   a && b     logical AND                    short-circuiting
   a || b     logical OR                     short-circuiting
   a &  b     boolean logical AND            not short-circuiting
   a |  b     boolean logical OR             not short-circuiting
   a ^  b     boolean logical exclusive OR
  !a          logical NOT

short-circuiting        (x != 0) && (1/x > 1)   SAFE
not short-circuiting    (x != 0) &  (1/x > 1)   NOT SAFE

A generic list of anonymous class

For your second example, where you have to initialize a new List<T>, one idea is to create an anonymous list, and then clear it.

var list = new[] { o, o1 }.ToList();
list.Clear();

//and you can keep adding.
while (....)
{
    ....
    list.Add(new { Id = x, Name = y });
    ....
}

Or as an extension method, should be easier:

public static List<T> GetEmptyListOfThisType<T>(this T item)
{
    return new List<T>();
}

//so you can call:
var list = new { Id = 0, Name = "" }.GetEmptyListOfThisType();

Or probably even shorter,

var list = new int[0].Select(x => new { Id = 0, Name = "" }).Tolist();

How to save SELECT sql query results in an array in C# Asp.net

Use a SQL DATA READER:

In this example i use a List instead an array.

try
{
    SqlCommand comm = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;",connection);
    connection.Open();

    SqlDataReader reader = comm.ExecuteReader();
    List<string> str = new List<string>();
    int i=0;
    while (reader.Read())
    {
        str.Add( reader.GetValue(i).ToString() );
        i++;
    }
    reader.Close();
}
catch (Exception)
{
    throw;
}
finally
{
    connection.Close();
}

Regex using javascript to return just numbers

If you want dot/comma separated numbers also, then:

\d*\.?\d*

or

[0-9]*\.?[0-9]*

You can use https://regex101.com/ to test your regexes.

PHP - count specific array values

To count a value in a two dimensional array, here is the useful snippet to process and get count of a particular value-

    <?php
    
    $list = [
      ['id' => 1, 'userId' => 5],
      ['id' => 2, 'userId' => 5],
      ['id' => 3, 'userId' => 6],
    ];

    $userId = 5;
    
    echo array_count_values(array_column($list, 'userId'))[$userId]; // outputs: 2
    

Reading InputStream as UTF-8

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

Writing a Python list of lists to a csv file

Using csv.writer in my very large list took quite a time. I decided to use pandas, it was faster and more easy to control and understand:

 import pandas

 yourlist = [[...],...,[...]]
 pd = pandas.DataFrame(yourlist)
 pd.to_csv("mylist.csv")

The good part you can change somethings to make a better csv file:

 yourlist = [[...],...,[...]]
 columns = ["abcd","bcde","cdef"] #a csv with 3 columns
 index = [i[0] for i in yourlist] #first element of every list in yourlist
 not_index_list = [i[1:] for i in yourlist]
 pd = pandas.DataFrame(not_index_list, columns = columns, index = index)

 #Now you have a csv with columns and index:
 pd.to_csv("mylist.csv")

How To Remove Outline Border From Input Button

It works for me simply :)

*:focus {
    outline: 0 !important;
}

Android Studio says "cannot resolve symbol" but project compiles

For my case working with AndroidStudio 2.2.3 the solution was to change the gradle wrapper/distribution to use local one in the Gradle Settings (despite of being "recommended"). enter image description here

How to change the current URL in javascript?

Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.

You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:

function nextImage() {
    return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
        return((Number(p1) + 1) + p2);
    }));
}

You can then call it like this:

window.location.href = nextImage();

Demo here: http://jsfiddle.net/jfriend00/3VPEq/

This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.

How do I find out if the GPS of an Android device is enabled

Yes you can check below is the code:

public boolean isGPSEnabled (Context mContext){
    LocationManager locationManager = (LocationManager)
                mContext.getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

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

Most of the answers are correct but I want to add little more. The ternary operator is right-associative, which means it can be chained in the following way if … else-if … else-if … else :

function example() {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

Equivalent to:

function example() {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}

More details is here

How to declare std::unique_ptr and what is the use of it?

Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr

In this case:

unique_ptr<double> uptr2 (pd);

pd will be destroyed when uptr2 goes out of scope. This facilitates memory management by automatic deletion.

The case of unique_ptr<int> uptr (new int(3)); is not different, except that the raw pointer is not assigned to any variable here.

How to make an AlertDialog in Flutter?

Another easy option to show Dialog is to use stacked_services package

 _dialogService.showDialog(
      title: "Title",
      description: "Dialog message Tex",
         );
     });