Programs & Examples On #Data access

Service located in another namespace

I stumbled over the same issue and found a nice solution which does not need any static ip configuration:

You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local

You can use that DNS name to reference it in another namespace via a local service:

kind: Service
apiVersion: v1
metadata:
  name: service-y
  namespace: namespace-a
spec:
  type: ExternalName
  externalName: service-x.namespace-b.svc.cluster.local
  ports:
  - port: 80

Encrypt & Decrypt using PyCrypto AES 256

For the benefit of others, here is my decryption implementation which I got to by combining the answers of @Cyril and @Marcus. This assumes that this coming in via HTTP Request with the encryptedText quoted and base64 encoded.

import base64
import urllib2
from Crypto.Cipher import AES


def decrypt(quotedEncodedEncrypted):
    key = 'SecretKey'

    encodedEncrypted = urllib2.unquote(quotedEncodedEncrypted)

    cipher = AES.new(key)
    decrypted = cipher.decrypt(base64.b64decode(encodedEncrypted))[:16]

    for i in range(1, len(base64.b64decode(encodedEncrypted))/16):
        cipher = AES.new(key, AES.MODE_CBC, base64.b64decode(encodedEncrypted)[(i-1)*16:i*16])
        decrypted += cipher.decrypt(base64.b64decode(encodedEncrypted)[i*16:])[:16]

    return decrypted.strip()

How to get index using LINQ?

I will make my contribution here... why? just because :p Its a different implementation, based on the Any LINQ extension, and a delegate. Here it is:

public static class Extensions
{
    public static int IndexOf<T>(
            this IEnumerable<T> list, 
            Predicate<T> condition) {               
        int i = -1;
        return list.Any(x => { i++; return condition(x); }) ? i : -1;
    }
}

void Main()
{
    TestGetsFirstItem();
    TestGetsLastItem();
    TestGetsMinusOneOnNotFound();
    TestGetsMiddleItem();   
    TestGetsMinusOneOnEmptyList();
}

void TestGetsFirstItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("a"));

    // Assert
    if(index != 0)
    {
        throw new Exception("Index should be 0 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsLastItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("d"));

    // Assert
    if(index != 3)
    {
        throw new Exception("Index should be 3 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMinusOneOnNotFound()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("e"));

    // Assert
    if(index != -1)
    {
        throw new Exception("Index should be -1 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMinusOneOnEmptyList()
{
    // Arrange
    var list = new string[] {  };

    // Act
    int index = list.IndexOf(item => item.Equals("e"));

    // Assert
    if(index != -1)
    {
        throw new Exception("Index should be -1 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMiddleItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d", "e" };

    // Act
    int index = list.IndexOf(item => item.Equals("c"));

    // Assert
    if(index != 2)
    {
        throw new Exception("Index should be 2 but is: " + index);
    }

    "Test Successful".Dump();
}        

How to retry image pull in a kubernetes Pods?

$ kubectl replace --force -f <resource-file>

if all goes well, you should see something like:

<resource-type> <resource-name> deleted
<resource-type> <resource-name> replaced

details of this can be found in the Kubernetes documentation, "manage-deployment" and kubectl-cheatsheet pages at the time of writing.

Allow multi-line in EditText view in Android?

Try this, add these lines to your edit text view, i'll add mine. make sure you understand it

android:overScrollMode="always"
android:scrollbarStyle="insideInset"
android:scrollbars="vertical"

<EditText
    android:inputType="textMultiLine"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/editText_newprom_description"
    android:padding="10dp"
    android:lines="5"
    android:overScrollMode="always"
    android:scrollbarStyle="insideInset"
    android:minLines="5"
    android:gravity="top|left"
    android:scrollbars="vertical"
    android:layout_marginBottom="20dp"/>

and on your java class make on click listner to this edit text as follows, i'll add mine, chane names according to yours.

EditText description;
description = (EditText)findViewById(R.id.editText_newprom_description);

description.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                view.getParent().requestDisallowInterceptTouchEvent(true);
                switch (motionEvent.getAction() & MotionEvent.ACTION_MASK){
                    case MotionEvent.ACTION_UP:
                        view.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                }

                return false;
            }

        });

this works fine for me

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

@Drewid's answer didn't work in my Firefox 25 if the flash plugin is just disabled but installed.

@invertedSpear's comment in that answer worked in firefox but not in any IE version.

So combined both their code and got this. Tested in Google Chrome 31, Firefox 25, IE 8-10. Thanks Drewid and invertedSpear :)

var hasFlash = false;
try {
  var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
  if (fo) {
    hasFlash = true;
  }
} catch (e) {
  if (navigator.mimeTypes
        && navigator.mimeTypes['application/x-shockwave-flash'] != undefined
        && navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
    hasFlash = true;
  }
}

How is a non-breaking space represented in a JavaScript string?

The jQuery docs for text() says

Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.

I'd use $td.html() instead.

How do you use script variables in psql?

FWIW, the real problem was that I had included a semicolon at the end of my \set command:

\set owner_password 'thepassword';

The semicolon was interpreted as an actual character in the variable:

\echo :owner_password thepassword;

So when I tried to use it:

CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD :owner_password NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';

...I got this:

CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD thepassword; NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';

That not only failed to set the quotes around the literal, but split the command into 2 parts (the second of which was invalid as it started with "NOINHERIT").

The moral of this story: PostgreSQL "variables" are really macros used in text expansion, not true values. I'm sure that comes in handy, but it's tricky at first.

How do you wait for input on the same Console.WriteLine() line?

Use Console.Write instead, so there's no newline written:

Console.Write("What is your name? ");
var name = Console.ReadLine();

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

Disable vertical scroll bar on div overflow: auto

If you want to accomplish the same in Gecko (NS6+, Mozilla, etc) and IE4+ simultaneously, I believe this should do the trick:V

body {
overflow: -moz-scrollbars-vertical;
overflow-x: hidden;
overflow-y: auto;
}

This will be applied to entire body tag, please update it to your relevant css and apply this properties.

Remove the first character of a string

Just do this:

r = "hello"
r = r[1:]
print(r) # ello

Finding child element of parent pure javascript

You have a parent element, you want to get all child of specific attribute 1. get the parent 2. get the parent nodename by using parent.nodeName.toLowerCase() convert the nodename to lower case e.g DIV will be div 3. for further specific purpose, get an attribute of the parent e.g parent.getAttribute("id"). this will give you id of the parent 4. Then use document.QuerySelectorAll(paret.nodeName.toLowerCase()+"#"_parent.getAttribute("id")+" input " ); if you want input children of the parent node

_x000D_
_x000D_
let parent = document.querySelector("div.classnameofthediv")_x000D_
let parent_node = parent.nodeName.toLowerCase()_x000D_
let parent_clas_arr = parent.getAttribute("class").split(" ");_x000D_
let parent_clas_str = '';_x000D_
  parent_clas_arr.forEach(e=>{_x000D_
     parent_clas_str +=e+'.';_x000D_
  })_x000D_
let parent_class_name = parent_clas_str.substr(0, parent_clas_str.length-1)  //remove the last dot_x000D_
let allchild = document.querySelectorAll(parent_node+"."+parent_class_name+" input")
_x000D_
_x000D_
_x000D_

Is there a wikipedia API just for retrieve content summary?

If you are just looking for the text which you can then split up but don't want to use the API take a look at en.wikipedia.org/w/index.php?title=Elephant&action=raw

Executing <script> elements inserted with .innerHTML

Just do:

document.body.innerHTML = document.body.innerHTML + '<img src="../images/loaded.gif" alt="" onload="alert(\'test\');this.parentNode.removeChild(this);" />';

How to use a WSDL file to create a WCF service (not make a call)

Using svcutil, you can create interfaces and classes (data contracts) from the WSDL.

svcutil your.wsdl (or svcutil your.wsdl /l:vb if you want Visual Basic)

This will create a file called "your.cs" in C# (or "your.vb" in VB.NET) which contains all the necessary items.

Now, you need to create a class "MyService" which will implement the service interface (IServiceInterface) - or the several service interfaces - and this is your server instance.

Now a class by itself doesn't really help yet - you'll need to host the service somewhere. You need to either create your own ServiceHost instance which hosts the service, configure endpoints and so forth - or you can host your service inside IIS.

Gson - convert from Json to a typed ArrayList<T>

You may use TypeToken to load the json string into a custom object.

logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());

Documentation:

Represents a generic type T.

Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.

For example, to create a type literal for List<String>, you can create an empty anonymous inner class:

TypeToken<List<String>> list = new TypeToken<List<String>>() {};

This syntax cannot be used to create type literals that have wildcard parameters, such as Class<?> or List<? extends CharSequence>.

Kotlin:

If you need to do it in Kotlin you can do it like this:

val myType = object : TypeToken<List<JsonLong>>() {}.type
val logs = gson.fromJson<List<JsonLong>>(br, myType)

Or you can see this answer for various alternatives.

I just assigned a variable, but echo $variable shows something else

echo $var output highly depends on the value of IFS variable. By default it contains space, tab, and newline characters:

[ks@localhost ~]$ echo -n "$IFS" | cat -vte
 ^I$

This means that when shell is doing field splitting (or word splitting) it uses all these characters as word separators. This is what happens when referencing a variable without double quotes to echo it ($var) and thus expected output is altered.

One way to prevent word splitting (besides using double quotes) is to set IFS to null. See http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_05 :

If the value of IFS is null, no field splitting shall be performed.

Setting to null means setting to empty value:

IFS=

Test:

[ks@localhost ~]$ echo -n "$IFS" | cat -vte
 ^I$
[ks@localhost ~]$ var=$'key\nvalue'
[ks@localhost ~]$ echo $var
key value
[ks@localhost ~]$ IFS=
[ks@localhost ~]$ echo $var
key
value
[ks@localhost ~]$ 

C - Convert an uppercase letter to lowercase

If condition is wrong. Also return type for lower is needed.

#include <stdio.h>

int lower(int a)  
{
    if ((a >= 65) && (a <= 90))
        a = a + 32; 
    return a;  
}

int _tmain(int argc, _TCHAR* argv[])
{

    putchar(lower('A')); 
    return 0;
}

jump to line X in nano editor

The shortcut is: CTRL+shift+- ("shift+-" results in "_") After typing the shortcut, nano will let you to enter the line you wanna jump to, type in the line number, then press ENTR.

linux find regex

You should have a look on the -regextype argument of find, see manpage:

      -regextype type
          Changes the regular expression syntax understood by -regex and -iregex 
          tests which occur later on the command line.  Currently-implemented  
          types  are  emacs (this is the default), posix-awk, posix-basic, 
          posix-egrep and posix-extended. 

I guess the emacs type doesn't support the [[:digit:]] construct. I tried it with posix-extended and it worked as expected:

find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'

HTTP GET Request in Node.js Express

Request and Superagent are pretty good libraries to use.

note: request is deprecated, use at your risk!

Using request:

var request=require('request');

request.get('https://someplace',options,function(err,res,body){
  if(err) //TODO: handle err
  if(res.statusCode === 200 ) //etc
  //TODO Do something with response
});

System.drawing namespace not found under console application

  1. Add using System.Drawing;
  2. Go to solution explorer and right click on references and select add reference
  3. Click on assemblies on the left
  4. search for system.drawing
  5. check system.drawing
  6. Click OK
  7. Done

Simple 3x3 matrix inverse code (C++)

//Function for inverse of the input square matrix 'J' of dimension 'dim':

vector<vector<double > > inverseVec33(vector<vector<double > > J, int dim)
{
//Matrix of Minors
 vector<vector<double > > invJ(dim,vector<double > (dim));
for(int i=0; i<dim; i++)
{
    for(int j=0; j<dim; j++)
    {
        invJ[i][j] = (J[(i+1)%dim][(j+1)%dim]*J[(i+2)%dim][(j+2)%dim] -
                      J[(i+2)%dim][(j+1)%dim]*J[(i+1)%dim][(j+2)%dim]);
    }
}

//determinant of the matrix:
double detJ = 0.0;
for(int j=0; j<dim; j++)
{ detJ += J[0][j]*invJ[0][j];}

//Inverse of the given matrix.
 vector<vector<double > > invJT(dim,vector<double > (dim));
 for(int i=0; i<dim; i++)
{
    for(int j=0; j<dim; j++)
    {
        invJT[i][j] = invJ[j][i]/detJ;
    }
}

return invJT;
}

void main()
{
    //given matrix:
vector<vector<double > > Jac(3,vector<double > (3));
Jac[0][0] = 1; Jac[0][1] = 2;  Jac[0][2] = 6;
Jac[1][0] = -3; Jac[1][1] = 4;  Jac[1][2] = 3;
Jac[2][0] = 5; Jac[2][1] = 1;  Jac[2][2] = -4;`

//Inverse of the matrix Jac:
vector<vector<double > > JacI(3,vector<double > (3));
    //call function and store inverse of J as JacI:
JacI = inverseVec33(Jac,3);
}

Laravel - Form Input - Multiple select for a one to many relationship

@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.

On your controller

$dogs = Dog::lists('name', 'id');

On customer create view you can use.

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}

Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:

{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}

Update For Laravel 5.1

The lists method now returns a Collection. Upgrading To 5.1.0

{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}

How do you serve a file for download with AngularJS or Javascript?

This can be done in javascript without the need to open another browser window.

window.location.assign('url');

Replace 'url' with the link to your file. You can put this in a function and call it with ng-click if you need to trigger the download from a button.

How to convert object to Dictionary<TKey, TValue> in C#?

I use this helper:

public static class ObjectToDictionaryHelper
{
    public static IDictionary<string, object> ToDictionary(this object source)
    {
        return source.ToDictionary<object>();
    }

    public static IDictionary<string, T> ToDictionary<T>(this object source)
    {
        if (source == null)
            ThrowExceptionWhenSourceArgumentIsNull();

        var dictionary = new Dictionary<string, T>();
        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
            AddPropertyToDictionary<T>(property, source, dictionary);
        return dictionary;
    }

    private static void AddPropertyToDictionary<T>(PropertyDescriptor property, object source, Dictionary<string, T> dictionary)
    {
        object value = property.GetValue(source);
        if (IsOfType<T>(value))
            dictionary.Add(property.Name, (T)value);
    }

    private static bool IsOfType<T>(object value)
    {
        return value is T;
    }

    private static void ThrowExceptionWhenSourceArgumentIsNull()
    {
        throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
    }
}

the usage is just to call .ToDictionary() on an object

Hope it helps.

String.Format alternative in C++

You can just concatenate the strings and build a command line.

std::string command = a + ' ' + b + " > " + c;
system(command.c_str());

You don't need any extra libraries for this.

Calling async method on button click

This is what's killing you:

task.Wait();

That's blocking the UI thread until the task has completed - but the task is an async method which is going to try to get back to the UI thread after it "pauses" and awaits an async result. It can't do that, because you're blocking the UI thread...

There's nothing in your code which really looks like it needs to be on the UI thread anyway, but assuming you really do want it there, you should use:

private async void Button_Click(object sender, RoutedEventArgs 
{
    Task<List<MyObject>> task = GetResponse<MyObject>("my url");
    var items = await task;
    // Presumably use items here
}

Or just:

private async void Button_Click(object sender, RoutedEventArgs 
{
    var items = await GetResponse<MyObject>("my url");
    // Presumably use items here
}

Now instead of blocking until the task has completed, the Button_Click method will return after scheduling a continuation to fire when the task has completed. (That's how async/await works, basically.)

Note that I would also rename GetResponse to GetResponseAsync for clarity.

Why call super() in a constructor?

There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).

An example, where the explicit call to super() gives you some extra control over the title of the frame:

class MyFrame extends JFrame
{
    public MyFrame() {
        super("My Window Title");
        ...
    }
}

How can I revert a single file to a previous version?

Extracted from here: http://git.661346.n2.nabble.com/Revert-a-single-commit-in-a-single-file-td6064050.html

 git revert <commit> 
 git reset 
 git add <path> 
 git commit ... 
 git reset --hard # making sure you didn't have uncommited changes earlier 

It worked very fine to me.

Maven: Failed to read artifact descriptor

For me , it was related to setting the "User Setting.xml" inside

Window > preferences > Maven > User Settings > and then browsing to the user Settings inside the { maven unarchived directory / }/apache-maven-2.2.1/conf/settings.xml . 

Get time of specific timezone

short answer from client-side: NO, you have to get it from the server side.

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

Sorry for the late reply

Obviously lists method has been deprecated in Laravel, but you can use the pluck method.

For Eg:

Laravel 5.7

public function create()
{
    $countries =  Country::pluck('country_name','id');
    return View::make('test.new')->with('countries', $countries);
}

and in the view if you are FORM components just pass as

{{  Form::select('testname',$countries,null,['class' => 'required form-control select2','id'=>'testname']) }}

if will generate the dropdown

but i have a situation to show that select country as the first option and as null value

<option value="" selected="selected">--Select  Country--</option>

so I have referred to

https://stackoverflow.com/a/51324218/8487424

and fixed this, but in later times if I want to change this I hate being changing it in the view

So have created the helper function based on https://stackoverflow.com/a/51324218/8487424 and placed in the Country Model

public static  function toDropDown($tableName='',$nameField='',$idField='',$defaultNullText='--Select--')
{
    if ($idField == null)
    {
        $idField="id";
    }

    $listFiledValues = DB::table($tableName)->select($idField,$nameField)->get();

            $selectArray=[];
            $selectArray[null] = $defaultNullText;
            foreach ($listFiledValues as $listFiledValue) 
            {
                $selectArray[$listFiledValue->$idField] = $listFiledValue->$nameField;
            }
            return $selectArray;
        }

and in controller

public function create()
    {
      $countries = Country::toDropDown('countries','name','id','--Select  Country--');
      return View::make('test.new')->with('countries', $countries);
    }

and finally in the view

 {{  Form::select('testname',$countries,null,['class' => 'required form-control select2','id'=>'testname']) }}

and the result is as expected, but I strongly recommend to use pluck() method

How to disable/enable a button with a checkbox if checked

HTML

<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />

JS

var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function() {
  sendbtn.disabled = !!this.checked;
};

DEMO

SQL Query NOT Between Two Dates

For there to be an overlap the table's start_date has to be LESS THAN the interval end date (i.e. it has to start before the end of the interval) AND the table's end_date has to be GREATER THAN the interval start date. You may need to use <= and >= depending on your requirements.

How can I scroll to a specific location on the page using jquery?

Here's a pure javascript version:

location.hash = '#123';

It'll scroll automatically. Remember to add the "#" prefix.

What is the difference between ndarray and array in numpy?

numpy.array is just a convenience function to create an ndarray; it is not a class itself.

You can also create an array using numpy.ndarray, but it is not the recommended way. From the docstring of numpy.ndarray:

Arrays should be constructed using array, zeros or empty ... The parameters given here refer to a low-level method (ndarray(...)) for instantiating an array.

Most of the meat of the implementation is in C code, here in multiarray, but you can start looking at the ndarray interfaces here:

https://github.com/numpy/numpy/blob/master/numpy/core/numeric.py

How do I create a user account for basic authentication?

in iis manager click directory to protect.

choose authorization rules.

add deny anonymous users rule.

add allow all users rule.

go back to: "in iis manager click directory to protect" click authentication disable all except basic authentication.

the directory is now protected. only people with user accounts can access the folder over the web.

Will #if RELEASE work like #if DEBUG does in C#?

No, it won't, unless you do some work.

The important part here is what DEBUG really is, and it's a kind of constant defined that the compiler can check against.

If you check the project properties, under the Build tab, you'll find three things:

  • A text box labelled "Conditional compilation symbols"
  • A check box labelled "Define DEBUG constant"
  • A check box labelled "Define TRACE constant"

There is no such checkbox, nor constant/symbol pre-defined that has the name RELEASE.

However, you can easily add that name to the text box labelled Conditional compilation symbols, but make sure you set the project configuration to Release-mode before doing so, as these settings are per configuration.

So basically, unless you add that to the text box, #if RELEASE won't produce any code under any configuration.

Django model "doesn't declare an explicit app_label"

I received this error after I moved the SECRET_KEY to pull from an environment variable and forgot to set it when running the application. If you have something like this in your settings.py

SECRET_KEY = os.getenv('SECRET_KEY')

then make sure you are actually setting the environment variable.

Way to insert text having ' (apostrophe) into a SQL table

I know the question is aimed at the direct escaping of the apostrophe character but I assume that usually this is going to be triggered by some sort of program providing the input.

What I have done universally in the scripts and programs I have worked with is to substitute it with a ` character when processing the formatting of the text being input.

Now I know that in some cases, the backtick character may in fact be part of what you might be trying to save (such as on a forum like this) but if you're simply saving text input from users it's a possible solution.

Going into the SQL database

$newval=~s/\'/`/g;

Then, when coming back out for display, filtered again like this:

$showval=~s/`/\'/g;

This example was when PERL/CGI is being used but it can apply to PHP and other bases as well. I have found it works well because I think it helps prevent possible injection attempts, because all ' are removed prior to attempting an insertion of a record.

Open URL in same window and in same tab

You can do

window.close();
window.open("index.html");

and it worked successfully on my website.

Plot a bar using matplotlib using a dictionary

Why not just:

import seaborn as sns

sns.barplot(list(D.keys()), list(D.values()))

ValueError: invalid literal for int () with base 10

As Lattyware said, there is a difference between Python2 & Python3 that leads to this error:

With Python2, int(str(5/2)) gives you 2. With Python3, the same gives you: ValueError: invalid literal for int() with base 10: '2.5'

If you need to convert some string that could contain float instead of int, you should always use the following ugly formula:

int(float(myStr))

As float('3.0') and float('3') give you 3.0, but int('3.0') gives you the error.

WCF Service, the type provided as the service attribute values…could not be found

Faced this exact issue. The problem resolved when i changed the Service="Namespace.ServiceName" tag in the Markup (right click xxxx.svc and select View Markup in visual studio) to match the namespace i used for my xxxx.svc.cs file

MS-DOS Batch file pause with enter key

Depending on which OS you're using, if you are flexible, then CHOICE can be used to wait on almost any key EXCEPT enter

If you are really referring to what Microsoft insists on calling "Command Prompt" which is simply an MS-DOS emulator, then perhaps TIMEOUT may suit your purpose (timeout /t -1 waits on any key, not just ENTER) and of course CHOICE is available again in recent WIN editions.

And a warning on SET /P - whereas set /p DUMMY=Hit ENTER to continue... will work,

set "dummy="
set /p DUMMY=Hit ENTER to continue...
if defined dummy (echo not just ENTER was pressed) else (echo just ENTER was pressed)

will detect whether just ENTER or something else, ending in ENTER was keyed in.

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

How can I check if a scrollbar is visible?

The solutions provided above will work in the most cases, but checking the scrollHeight and overflow is sometimes not enough and can fail for body and html elements as seen here: https://codepen.io/anon/pen/EvzXZw

1. Solution - Check if the element is scrollable:

function isScrollableY (element) {
  return !!(element.scrollTop || (++element.scrollTop && element.scrollTop--));
}

Note: elements with overflow: hidden are also treated as scrollable (more info), so you might add a condition against that too if needed:

function isScrollableY (element) {
    let style = window.getComputedStyle(element);
    return !!(element.scrollTop || (++element.scrollTop && element.scrollTop--)) 
           && style["overflow"] !== "hidden" && style["overflow-y"] !== "hidden";
}

As far as I know this method only fails if the element has scroll-behavior: smooth.

Explanation: The trick is, that the attempt of scrolling down and reverting it won't be rendered by the browser. The topmost function can also be written like the following:

_x000D_
_x000D_
function isScrollableY (element) {
  // if scrollTop is not 0 / larger than 0, then the element is scrolled and therefore must be scrollable
  // -> true  
  if (element.scrollTop === 0) {
    // if the element is zero it may be scrollable  
    // -> try scrolling about 1 pixel
    element.scrollTop++;
    // if the element is zero then scrolling did not succeed and therefore it is not scrollable 
    // -> false  
    if (element.scrollTop === 0) return false;
    // else the element is scrollable; reset the scrollTop property
    // -> true
    element.scrollTop--;
  }
  return true;
}
_x000D_
_x000D_
_x000D_

2. Solution - Do all the necessary checks:

function isScrollableY (element) {
  const style = window.getComputedStyle(element);
  
  if (element.scrollHeight > element.clientHeight &&
      style["overflow"] !== "hidden" && style["overflow-y"] !== "hidden" &&
      style["overflow"] !== "clip" && style["overflow-y"] !== "clip"
  ) {
    if (element === document.scrollingElement) return true;
    else if (style["overflow"] !== "visible" && style["overflow-y"] !== "visible") {
      // special check for body element (https://drafts.csswg.org/cssom-view/#potentially-scrollable)
      if (element === document.body) {
        const parentStyle = window.getComputedStyle(element.parentElement);
        if (parentStyle["overflow"] !== "visible" && parentStyle["overflow-y"] !== "visible" &&
            parentStyle["overflow"] !== "clip" && parentStyle["overflow-y"] !== "clip"
        ) {
          return true;
        }
      }
      else return true;
    }
  }
  
  return false;
}

How to reload the current route with the angular 2 router

I am using setTimeout and navigationByUrl to solve this issue... And it is working fine for me.

It is redirected to other URL and instead comes again in the current URL...

 setTimeout(() => {
     this.router.navigateByUrl('/dashboard', {skipLocationChange: false}).then(() =>
           this.router.navigate([route]));
     }, 500)

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

Its because the variable '$user_location' is not getting defined. If you are using any if loop inside which you are declaring the '$user_location' variable then you must also have an else loop and define the same. For example:

$a=10;
if($a==5) { $user_location='Paris';} else { }
echo $user_location;

The above code will create error as The if loop is not satisfied and in the else loop '$user_location' was not defined. Still PHP was asked to echo out the variable. So to modify the code you must do the following:

$a=10;
if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
echo $user_location;

Media Player called in state 0, error (-38,0)

For me this worked

mp.seekTo(0);
mp.start();

regular expression to match exactly 5 digits

what is about this? \D(\d{5})\D

This will do on:

f 23 23453 234 2344 2534 hallo33333 "50000"

23453, 33333 50000

Get connection string from App.config

It seems like problem is not with reference, you are getting connectionstring as null so please make sure you have added the value to the config file your running project meaning the main program/library that gets started/executed first.

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

As mentioned by removing the colon : and replacing with slash / before the sid worked for me.

I have had this issue before, too.

Implementing Singleton with an Enum (in Java)

An enum type is a special type of class.

Your enum will actually be compiled to something like

public final class MySingleton {
    public final static MySingleton INSTANCE = new MySingleton();
    private MySingleton(){} 
}

When your code first accesses INSTANCE, the class MySingleton will be loaded and initialized by the JVM. This process initializes the static field above once (lazily).

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

How to remove the left part of a string?

If the string is fixed you can simply use:

if line.startswith("Path="):
    return line[5:]

which gives you everything from position 5 on in the string (a string is also a sequence so these sequence operators work here, too).

Or you can split the line at the first =:

if "=" in line:
    param, value = line.split("=",1)

Then param is "Path" and value is the rest after the first =.

Test if registry value exists

Probably an issue with strings having whitespace. Here's a cleaned up version that works for me:

Function Test-RegistryValue($regkey, $name) {
    $exists = Get-ItemProperty -Path "$regkey" -Name "$name" -ErrorAction SilentlyContinue
    If (($exists -ne $null) -and ($exists.Length -ne 0)) {
        Return $true
    }
    Return $false
}

How do you convert a DataTable into a generic list?

You could use

List<DataRow> list = new List<DataRow>(dt.Select());

dt.Select() will return all rows in your table, as an array of datarows, and the List constructor accepts that array of objects as an argument to initially fill your list with.

how to add lines to existing file using python

Open the file for 'append' rather than 'write'.

with open('file.txt', 'a') as file:
    file.write('input')

Post-increment and pre-increment within a 'for' loop produce same output

Because in either case the increment is done after the body of the loop and thus doesn't affect any of the calculations of the loop. If the compiler is stupid, it might be slightly less efficient to use post-increment (because normally it needs to keep a copy of the pre value for later use), but I would expect any differences to be optimized away in this case.

It might be handy to think of how the for loop is implemented, essentially translated into a set of assignments, tests, and branch instructions. In pseudo-code the pre-increment would look like:

      set i = 0
test: if i >= 5 goto done
      call printf,"%d",i
      set i = i + 1
      goto test
done: nop

Post-increment would have at least another step, but it would be trivial to optimize away

      set i = 0
test: if i >= 5 goto done
      call printf,"%d",i
      set j = i   // store value of i for later increment
      set i = j + 1  // oops, we're incrementing right-away
      goto test
done: nop

Node.js Generate html

You can use jade + express:

app.get('/', function (req, res) { res.render('index', { title : 'Home' } ) });

above you see 'index' and an object {title : 'Home'}, 'index' is your html and the object is your data that will be rendered in your html.

Accessing variables from other functions without using global variables

I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:

var MyApp = {}; // Globally scoped object

function foo(){
    MyApp.color = 'green';
}

function bar(){
    alert(MyApp.color); // Alerts 'green'
} 

No one should yell at you for doing something like the above.

How do you stash an untracked file?

If you want to stash untracked files, but keep indexed files (the ones you're about to commit for example), just add -k (keep index) option to the -u

git stash -u -k

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

Models must be named and called with the first letter of the model name capitalized and the rest in lowercase.

For example: $this->load->model('Logon_model');

and:

class Logon_model extends CI_Model {
...

But you are correct about the file name.

What are the different NameID format used for?

It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:

  1. unspecified
  2. emailAddress – e.g. [email protected]
  3. X509SubjectName – e.g. CN=john,O=Company Ltd.,C=US
  4. WindowsDomainQualifiedName – e.g. CompanyDomain\John
  5. kerberos– e.g. john@realm
  6. entity – this one in used to identify entities that provide SAML-based services and looks like a URI
  7. persistent – this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.
  8. transient – opaque identifier which should be treated as temporary.

How do I iterate and modify Java Sets?

You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().

however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.

Set<Integer> s; //contains your Integers
...
Set<Integer> temp = new Set<Integer>();
for(Integer i : s)
    temp.add(i+1);
s.clear();
s.addAll(temp);

Git Bash doesn't see my PATH

In my case It happened while installing heroku cli and git bash, Here is what i did to work.

got to this location

C:\Users\<username here>\AppData\Local

and delete the file in my case heroku folder. So I deleded folder and run cmd. It is working

SQL Server: Multiple table joins with a WHERE clause

try this

DECLARE @Application TABLE(Id INT PRIMARY KEY, NAME VARCHAR(20))
INSERT @Application ( Id, NAME )
VALUES  ( 1,'Word' ), ( 2,'Excel' ), ( 3,'PowerPoint' )
DECLARE @software TABLE(Id INT PRIMARY KEY, ApplicationId INT, Version INT)
INSERT @software ( Id, ApplicationId, Version )
VALUES  ( 1,1, 2003 ), ( 2,1,2007 ), ( 3,2, 2003 ), ( 4,2,2007 ),( 5,3, 2003 ), ( 6,3,2007 )

DECLARE @Computer TABLE(Id INT PRIMARY KEY, NAME VARCHAR(20))
INSERT @Computer ( Id, NAME )
VALUES  ( 1,'Name1' ), ( 2,'Name2' )

DECLARE @Software_Computer  TABLE(Id INT PRIMARY KEY, SoftwareId int, ComputerId int)
INSERT @Software_Computer ( Id, SoftwareId, ComputerId )
VALUES  ( 1,1, 1 ), ( 2,4,1 ), ( 3,2, 2 ), ( 4,5,2 )

SELECT Computer.Name ComputerName, Application.Name ApplicationName, MAX(Software2.Version) Version
FROM @Application Application 
JOIN @Software Software
    ON Application.ID = Software.ApplicationID
CROSS JOIN @Computer Computer
LEFT JOIN @Software_Computer Software_Computer
    ON Software_Computer.ComputerId = Computer.Id AND Software_Computer.SoftwareId = Software.Id
LEFT JOIN @Software Software2
    ON Software2.ID = Software_Computer.SoftwareID
WHERE Computer.ID = 1 
GROUP BY Computer.Name, Application.Name

How to parse JSON in Java

Since nobody mentioned it yet, here is a beginning of a solution using Nashorn (JavaScript runtime part of Java 8, but deprecated in Java 11).

Solution

private static final String EXTRACTOR_SCRIPT =
    "var fun = function(raw) { " +
    "var json = JSON.parse(raw); " +
    "return [json.pageInfo.pageName, json.pageInfo.pagePic, json.posts[0].post_id];};";

public void run() throws ScriptException, NoSuchMethodException {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    engine.eval(EXTRACTOR_SCRIPT);
    Invocable invocable = (Invocable) engine;
    JSObject result = (JSObject) invocable.invokeFunction("fun", JSON);
    result.values().forEach(e -> System.out.println(e));
}

Performance comparison

I wrote JSON content containing three arrays of respectively 20, 20 and 100 elements. I only want to get the 100 elements from the third array. I use the following JavaScript function to parse and get my entries.

var fun = function(raw) {JSON.parse(raw).entries};

Running the call a million times using Nashorn takes 7.5~7.8 seconds

(JSObject) invocable.invokeFunction("fun", json);

org.json takes 20~21 seconds

new JSONObject(JSON).getJSONArray("entries");

Jackson takes 6.5~7 seconds

mapper.readValue(JSON, Entries.class).getEntries();

In this case Jackson performs better than Nashorn, which performs much better than org.json. Nashorn API is harder to use than org.json's or Jackson's. Depending on your requirements Jackson and Nashorn both can be viable solutions.

Right click to select a row in a Datagridview and show a menu to delete it

I have a new workaround to come in same result, but, with less code. for Winforms... That's example is in portuguese Follow up step by step

  1. Create a contextMenuStrip in your form and create one item
  2. Sign one event click (OnCancelarItem_Click) for this contextMenuStrip enter image description here
  3. Create a event 'UserDeletingRow' on gridview enter image description here and now... you've simulating on key press del from user

    you don't forget to enable delete on the gridview, right?!

enter image description here enter image description here and finally... enter image description here

Sass calculate percent minus px

IF you know the width of the container, you could do like this:

#container
  width: #{200}px
  #element
    width: #{(0.25 * 200) - 5}px

I'm aware that in many cases #container could have a relative width. Then this wouldn't work.

Google maps Places API V3 autocomplete - select first option on enter

I had the same issue when implementing autocomplete on a site I worked on recently. This is the solution I came up with:

$("input").focusin(function () {
    $(document).keypress(function (e) {
        if (e.which == 13) {
            var firstResult = $(".pac-container .pac-item:first").text();

            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({"address":firstResult }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    var lat = results[0].geometry.location.lat(),
                        lng = results[0].geometry.location.lng(),
                        placeName = results[0].address_components[0].long_name,
                        latlng = new google.maps.LatLng(lat, lng);

                        $(".pac-container .pac-item:first").addClass("pac-selected");
                        $(".pac-container").css("display","none");
                        $("#searchTextField").val(firstResult);
                        $(".pac-container").css("visibility","hidden");

                    moveMarker(placeName, latlng);

                }
            });
        } else {
            $(".pac-container").css("visibility","visible");
        }

    });
});

http://jsfiddle.net/dodger/pbbhH/

How to plot vectors in python using matplotlib

This may also be achieved using matplotlib.pyplot.quiver, as noted in the linked answer;

plt.quiver([0, 0, 0], [0, 0, 0], [1, -2, 4], [1, 2, -7], angles='xy', scale_units='xy', scale=1)
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()

mpl output

Undo scaffolding in Rails

First, if you have already run the migrations generated by the scaffold command, you have to perform a rollback first.

rake db:rollback

You can create scaffolding using:

rails generate scaffold MyFoo 

(or similar), and you can destroy/undo it using

rails destroy scaffold MyFoo

That will delete all the files created by generate, but not any additional changes you may have made manually.

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

Could fix this by adding

compile 'com.android.support:support-v4:18.0.0'

to the dependencies in the vertretungsplan build.gradle, compile and then remove this line and compile again.

now it works

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

enumerate() for dictionary in python

The first column of output is the index of each item in enumm and the second one is its keys. If you want to iterate your dictionary then use .items():

for k, v in enumm.items():
    print(k, v)

And the output should look like:

0 1
1 2
2 3
4 4 
5 5
6 6
7 7

Where should I put the log4j.properties file?

As already stated, log4j.properties should be in a directory included in the classpath, I want to add that in a mavenized project a good place can be src/main/resources/log4j.properties

Get user info via Google API

I'm using PHP and solved this by using version 1.1.4 of google-api-php-client

Assuming the following code is used to redirect a user to the Google authentication page:

 $client = new Google_Client();
 $client->setAuthConfigFile('/path/to/config/file/here');
 $client->setRedirectUri('https://redirect/url/here');
 $client->setAccessType('offline'); //optional
 $client->setScopes(['profile']); //or email
 $auth_url = $client->createAuthUrl();
 header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
 exit();

Assuming a valid authentication code is returned to the redirect_url, the following will generate a token from the authentication code as well as provide basic profile information:

 //assuming a successful authentication code is return
 $authentication_code = 'code-returned-by-google';
 $client = new Google_Client();
 //.... configure $client object code goes here
 $client->authenticate($authentication_code);
 $token_data = $client->getAccessToken();

 //get user email address
 $google_oauth =new Google_Service_Oauth2($client);
 $google_account_email = $google_oauth->userinfo->get()->email;
 //$google_oauth->userinfo->get()->familyName;
 //$google_oauth->userinfo->get()->givenName;
 //$google_oauth->userinfo->get()->name;
 //$google_oauth->userinfo->get()->gender;
 //$google_oauth->userinfo->get()->picture; //profile picture

However, location is not returned. New YouTube accounts don't have YouTube specific usernames

How do I set a textbox's text to bold at run time?

Here is an example for toggling bold, underline, and italics.

   protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
   {
      if ( ActiveControl is RichTextBox r )
      {
         if ( keyData == ( Keys.Control | Keys.B ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Bold ); // XOR will toggle
            return true;
         }
         if ( keyData == ( Keys.Control | Keys.U ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Underline ); // XOR will toggle
            return true;
         }
         if ( keyData == ( Keys.Control | Keys.I ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Italic ); // XOR will toggle
            return true;
         }
      }
      return base.ProcessCmdKey( ref msg, keyData );
   }

css with background image without repeating the image

Instead of

background-repeat-x: no-repeat;
background-repeat-y: no-repeat;

which is not correct, use

background-repeat: no-repeat;

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

Some good answers, but the problem with all solutions I have tried is that the images doesn´t fade into each other. Instead the first one fades completely out and than the next one fades in.

After a few hours of testing a found this sollution. Thx to http://www.1squarepear.com/adding-a-responsive-bootstrap-image-carousel-that-fades-instead-of-slides/

  1. In the HTML code change from .slide to .fade on the .carousel element
  2. Add this in the css:

    .carousel.fade { opacity: 1; } .carousel.fade .item { transition: opacity ease-out .7s; left: 0; opacity: 0; /* hide all slides */ top: 0; position: absolute; width: 100%; display: block; } .carousel.fade .item:first-child { top: auto; opacity: 1; /* show first slide */ position: relative; } .carousel.fade .item.active { opacity: 1; }

Descending order by date filter in AngularJs

_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.filter("toArray", function () {_x000D_
    return function (obj) {_x000D_
        var result = [];_x000D_
        angular.forEach(obj, function (val, key) {_x000D_
            result.push(val);_x000D_
        });_x000D_
        return result;_x000D_
    };_x000D_
});_x000D_
_x000D_
_x000D_
myApp.controller("mainCtrl", function ($scope) {_x000D_
_x000D_
  $scope.logData = [_x000D_
              { event: 'Payment', created_at: '10/10/2019 6:47 PM PST' },_x000D_
              { event: 'Payment', created_at: '20/10/2019 12:47 AM PST' },_x000D_
              { event: 'Payment', created_at: '30/10/2019 1:50 PM PST' }_x000D_
          ]; _x000D_
        _x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="mainCtrl">_x000D_
_x000D_
  <h4>Descending</h4>_x000D_
  <ul>_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':true" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_
    </li>_x000D_
  </ul>_x000D_
  _x000D_
  <br>_x000D_
  _x000D_
  _x000D_
  <h4>Ascending</h4>_x000D_
  <ul>_x000D_
    <li ng-repeat="logs in logData | toArray | orderBy:'created_at':false" >_x000D_
          {{logs.event}} - Date : {{logs.created_at}}_x000D_
    </li>_x000D_
  </ul>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the purpose of the "final" keyword in C++11 for functions?

"final" also allows a compiler optimization to bypass the indirect call:

class IAbstract
{
public:
  virtual void DoSomething() = 0;
};

class CDerived : public IAbstract
{
  void DoSomething() final { m_x = 1 ; }

  void Blah( void ) { DoSomething(); }

};

with "final", the compiler can call CDerived::DoSomething() directly from within Blah(), or even inline. Without it, it has to generate an indirect call inside of Blah() because Blah() could be called inside a derived class which has overridden DoSomething().

How do you detect Credit card type based on number?

follow Luhn’s algorithm

 private  boolean validateCreditCardNumber(String str) {

        int[] ints = new int[str.length()];
        for (int i = 0; i < str.length(); i++) {
            ints[i] = Integer.parseInt(str.substring(i, i + 1));
        }
        for (int i = ints.length - 2; i >= 0; i = i - 2) {
            int j = ints[i];
            j = j * 2;
            if (j > 9) {
                j = j % 10 + 1;
            }
            ints[i] = j;
        }
        int sum = 0;
        for (int i = 0; i < ints.length; i++) {
            sum += ints[i];
        }
        if (sum % 10 == 0) {
           return true;
        } else {
            return false;
        }


    }

then call this method

Edittext mCreditCardNumberEt;

 mCreditCardNumberEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

             int cardcount=   s.toString().length();
                 if(cardcount>=16) {
                    boolean cardnumbervalid=   validateCreditCardNumber(s.toString());
                    if(cardnumbervalid) {
                        cardvalidtesting.setText("Valid Card");
                        cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.green));
                    }
                    else {
                        cardvalidtesting.setText("Invalid Card");
                        cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.red));
                    }
                }
               else if(cardcount>0 &&cardcount<16) {
                     cardvalidtesting.setText("Invalid Card");
                     cardvalidtesting.setTextColor(ContextCompat.getColor(context,R.color.red));
                }

                else {
                    cardvalidtesting.setText("");

                }


                }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

Array formula on Excel for Mac

This doesn't seem to work in Mac Excel 2016. After a bit of digging, it looks like the key combination for entering the array formula has changed from ?+RETURN to CTRL+SHIFT+RETURN.

Function Pointers in Java

You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.

public interface IFunction {
  public void execute(Object o);
}

This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).

public static void doFunc(Collection c, IFunction f) {
   for (Object o : c) {
      f.execute(o);
   }
}

As an example say we have a collection of numbers and you would like to add 1 to every element.

CollectionUtils2.doFunc(List numbers, new IFunction() {
    public void execute(Object o) {
       Integer anInt = (Integer) o;
       anInt++;
    }
});

What is MVC and what are the advantages of it?

Main advantage of MVC architecture is differentiating the layers of a project in Model,View and Controller for the Re-usability of code, easy to maintain code and maintenance. The best thing is the developer feels good to add some code in between the project maintenance.

Here you can see the some more points on Main Advantages of MVC Architecture.

Elegant way to create empty pandas DataFrame with NaN of type float

Simply pass the desired value as first argument, like 0, math.inf or, here, np.nan. The constructor then initializes and fills the value array to the size specified by arguments index and columns:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame(np.nan, index=[0, 1, 2, 3], columns=['A', 'B'])

>>> df.dtypes
A    float64
B    float64
dtype: object

>>> df.values
array([[nan, nan],
       [nan, nan],
       [nan, nan],
       [nan, nan]])

How to change font size on part of the page in LaTeX?

To add exact fontsize you can use following. Worked for me since in my case predefined ranges (Large, tiny) are not match with the font size required to me.

\fontsize{10}{12}\selectfont This is the text you need to be in 10px

More info: https://tug.org/TUGboat/tb33-3/tb105thurnherr.pdf

How do I determine the dependencies of a .NET application?

Try compiling your .NET assembly with the option --staticlink:"Namespace.Assembly" . This forces the compiler to pull in all the dependencies at compile time. If it comes across a dependency that's not referenced it will give a warning or error message usually with the name of that assembly.

Namespace.Assembly is the assembly you suspect as having the dependency problem. Typically just statically linking this assembly will reference all dependencies transitively.

Why is list initialization (using curly braces) better than the alternatives?

It only safer as long as you don't build with -Wno-narrowing like say Google does in Chromium. If you do, then it is LESS safe. Without that flag the only unsafe cases will be fixed by C++20 though.

Note: A) Curly brackets are safer because they don't allow narrowing. B) Curly brackers are less safe because they can bypass private or deleted constructors, and call explicit marked constructors implicitly.

Those two combined means they are safer if what is inside is primitive constants, but less safe if they are objects (though fixed in C++20)

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Umair R's answer is mostly the right move to solve the problem, as this error used to be caused by the missing links between opencv libs and the programme. so there is the need to specify the ld_libraty_path configuration. ps. the usual library path is suppose to be:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

I have tried this and it worked well.

Angular2 handling http response

Update alpha 47

As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows

http
  .get('Some Url')
  .map(res => res.json())
  .subscribe(
    (data) => this.data = data,
    (err) => this.error = err); // Reach here if fails

Alpha 46 and below

You can handle the response in the map(...), before the subscribe.

http
  .get('Some Url')
  .map(res => {
    // If request fails, throw an Error that will be caught
    if(res.status < 200 || res.status >= 300) {
      throw new Error('This request has failed ' + res.status);
    } 
    // If everything went fine, return the response
    else {
      return res.json();
    }
  })
  .subscribe(
    (data) => this.data = data, // Reach here if res.status >= 200 && <= 299
    (err) => this.error = err); // Reach here if fails

Here's a plnkr with a simple example.

Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.

Using getResources() in non-activity class

in your MainActivity :

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(ResourcesHelper.resources == null){
             ResourcesHelper.resources = getResources();
        }
    }
}

ResourcesHelper :

public class ResourcesHelper {
    public static Resources resources;
}

then use it everywhere

String s = ResourcesHelper.resources.getString(R.string.app_name);

Time calculation in php (add 10 hours)?

$date = date('h:i:s A', strtotime($today . " +10 hours"));

An error occurred while updating the entries. See the inner exception for details

Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.

enter image description here

How can I find where I will be redirected using cURL?

Sometimes you need to get HTTP headers but at the same time you don't want return those headers.**

This skeleton takes care of cookies and HTTP redirects using recursion. The main idea here is to avoid return HTTP headers to the client code.

You can build a very strong curl class over it. Add POST functionality, etc.

<?php

class curl {

  static private $cookie_file            = '';
  static private $user_agent             = '';  
  static private $max_redirects          = 10;  
  static private $followlocation_allowed = true;

  function __construct()
  {
    // set a file to store cookies
    self::$cookie_file = 'cookies.txt';

    // set some general User Agent
    self::$user_agent = 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)';

    if ( ! file_exists(self::$cookie_file) || ! is_writable(self::$cookie_file))
    {
      throw new Exception('Cookie file missing or not writable.');
    }

    // check for PHP settings that unfits
    // correct functioning of CURLOPT_FOLLOWLOCATION 
    if (ini_get('open_basedir') != '' || ini_get('safe_mode') == 'On')
    {
      self::$followlocation_allowed = false;
    }    
  }

  /**
   * Main method for GET requests
   * @param  string $url URI to get
   * @return string      request's body
   */
  static public function get($url)
  {
    $process = curl_init($url);    

    self::_set_basic_options($process);

    // this function is in charge of output request's body
    // so DO NOT include HTTP headers
    curl_setopt($process, CURLOPT_HEADER, 0);

    if (self::$followlocation_allowed)
    {
      // if PHP settings allow it use AUTOMATIC REDIRECTION
      curl_setopt($process, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($process, CURLOPT_MAXREDIRS, self::$max_redirects); 
    }
    else
    {
      curl_setopt($process, CURLOPT_FOLLOWLOCATION, false);
    }

    $return = curl_exec($process);

    if ($return === false)
    {
      throw new Exception('Curl error: ' . curl_error($process));
    }

    // test for redirection HTTP codes
    $code = curl_getinfo($process, CURLINFO_HTTP_CODE);
    if ($code == 301 || $code == 302)
    {
      curl_close($process);

      try
      {
        // go to extract new Location URI
        $location = self::_parse_redirection_header($url);
      }
      catch (Exception $e)
      {
        throw $e;
      }

      // IMPORTANT return 
      return self::get($location);
    }

    curl_close($process);

    return $return;
  }

  static function _set_basic_options($process)
  {

    curl_setopt($process, CURLOPT_USERAGENT, self::$user_agent);
    curl_setopt($process, CURLOPT_COOKIEFILE, self::$cookie_file);
    curl_setopt($process, CURLOPT_COOKIEJAR, self::$cookie_file);
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
    // curl_setopt($process, CURLOPT_VERBOSE, 1);
    // curl_setopt($process, CURLOPT_SSL_VERIFYHOST, false);
    // curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
  }

  static function _parse_redirection_header($url)
  {
    $process = curl_init($url);    

    self::_set_basic_options($process);

    // NOW we need to parse HTTP headers
    curl_setopt($process, CURLOPT_HEADER, 1);

    $return = curl_exec($process);

    if ($return === false)
    {
      throw new Exception('Curl error: ' . curl_error($process));
    }

    curl_close($process);

    if ( ! preg_match('#Location: (.*)#', $return, $location))
    {
      throw new Exception('No Location found');
    }

    if (self::$max_redirects-- <= 0)
    {
      throw new Exception('Max redirections reached trying to get: ' . $url);
    }

    return trim($location[1]);
  }

}

Programmatically scroll a UIScrollView

I'm amazed that this topic is 9 years old and the actual straightforward answer is not here!

What you're looking for is scrollRectToVisible(_:animated:).

Example:

extension SignUpView: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        scrollView.scrollRectToVisible(textField.frame, animated: true)
    }
}

What it does is exactly what you need, and it's far better than hacky contentOffset

This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.

From: https://developer.apple.com/documentation/uikit/uiscrollview/1619439-scrollrecttovisible

How to implement private method in ES6 class with Traceur

You can use Symbol

var say = Symbol()

function Cat(){
  this[say]() // call private methos
}

Cat.prototype[say] = function(){ alert('im a private') }

P.S. alexpods is not correct. he get protect rather than private, since inheritance is a name conflict

Actually you can use var say = String(Math.random()) instead Symbol

IN ES6:

var say = Symbol()

class Cat {

  constructor(){
    this[say]() // call private
  }

  [say](){
    alert('im private')
  }

}

How to add a hook to the application context initialization event?

I had a single page application on entering URL it was creating a HashMap (used by my webpage) which contained data from multiple databases. I did following things to load everything during server start time-

1- Created ContextListenerClass

public class MyAppContextListener implements ServletContextListener
    @Autowired

    private  MyDataProviderBean myDataProviderBean; 

    public MyDataProviderBean getMyDataProviderBean() {

        return MyDataProviderBean;

    }

    public void setMyDataProviderBean(MyDataProviderBean MyDataProviderBean) {

        this.myDataProviderBean = MyDataProviderBean;

    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

        System.out.println("ServletContextListener destroyed");

    }


    @Override

    public void contextInitialized(ServletContextEvent context) {

        System.out.println("ServletContextListener started");

        ServletContext sc = context.getServletContext();

        WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(sc);

        MyDataProviderBean MyDataProviderBean = (MyDataProviderBean)springContext.getBean("myDataProviderBean");

        Map<String, Object> myDataMap = MyDataProviderBean.getDataMap();

        sc.setAttribute("myMap", myDataMap);

    }

2- Added below entry in web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 
<listener>
    <listener-class>com.context.listener.MyAppContextListener</listener-class>
</listener>

3- In my Controller Class updated code to first check for Map in servletContext

    @RequestMapping(value = "/index", method = RequestMethod.GET)
        public String index(@ModelAttribute("model") ModelMap model) {

            Map<String, Object> myDataMap = new HashMap<String, Object>();
            if (context != null && context.getAttribute("myMap")!=null)
            {

                myDataMap=(Map<String, Object>)context.getAttribute("myMap");
            }

            else
            {

                myDataMap = myDataProviderBean.getDataMap();
            }

            for (String key : myDataMap.keySet())
            {
                model.addAttribute(key, myDataMap.get(key));
            }
            return "myWebPage";

        }

With this much change when I start my tomcat it loads dataMap during startTime and puts everything in servletContext which is then used by Controller Class to get results from already populated servletContext .

std::wstring VS std::string

string? wstring?

std::string is a basic_string templated on a char, and std::wstring on a wchar_t.

char vs. wchar_t

char is supposed to hold a character, usually an 8-bit character.
wchar_t is supposed to hold a wide character, and then, things get tricky:
On Linux, a wchar_t is 4 bytes, while on Windows, it's 2 bytes.

What about Unicode, then?

The problem is that neither char nor wchar_t is directly tied to unicode.

On Linux?

Let's take a Linux OS: My Ubuntu system is already unicode aware. When I work with a char string, it is natively encoded in UTF-8 (i.e. Unicode string of chars). The following code:

#include <cstring>
#include <iostream>

int main(int argc, char* argv[])
{
   const char text[] = "olé" ;


   std::cout << "sizeof(char)    : " << sizeof(char) << std::endl ;
   std::cout << "text            : " << text << std::endl ;
   std::cout << "sizeof(text)    : " << sizeof(text) << std::endl ;
   std::cout << "strlen(text)    : " << strlen(text) << std::endl ;

   std::cout << "text(ordinals)  :" ;

   for(size_t i = 0, iMax = strlen(text); i < iMax; ++i)
   {
      std::cout << " " << static_cast<unsigned int>(
                              static_cast<unsigned char>(text[i])
                          );
   }

   std::cout << std::endl << std::endl ;

   // - - - 

   const wchar_t wtext[] = L"olé" ;

   std::cout << "sizeof(wchar_t) : " << sizeof(wchar_t) << std::endl ;
   //std::cout << "wtext           : " << wtext << std::endl ; <- error
   std::cout << "wtext           : UNABLE TO CONVERT NATIVELY." << std::endl ;
   std::wcout << L"wtext           : " << wtext << std::endl;

   std::cout << "sizeof(wtext)   : " << sizeof(wtext) << std::endl ;
   std::cout << "wcslen(wtext)   : " << wcslen(wtext) << std::endl ;

   std::cout << "wtext(ordinals) :" ;

   for(size_t i = 0, iMax = wcslen(wtext); i < iMax; ++i)
   {
      std::cout << " " << static_cast<unsigned int>(
                              static_cast<unsigned short>(wtext[i])
                              );
   }

   std::cout << std::endl << std::endl ;

   return 0;
}

outputs the following text:

sizeof(char)    : 1
text            : olé
sizeof(text)    : 5
strlen(text)    : 4
text(ordinals)  : 111 108 195 169

sizeof(wchar_t) : 4
wtext           : UNABLE TO CONVERT NATIVELY.
wtext           : ol?
sizeof(wtext)   : 16
wcslen(wtext)   : 3
wtext(ordinals) : 111 108 233

You'll see the "olé" text in char is really constructed by four chars: 110, 108, 195 and 169 (not counting the trailing zero). (I'll let you study the wchar_t code as an exercise)

So, when working with a char on Linux, you should usually end up using Unicode without even knowing it. And as std::string works with char, so std::string is already unicode-ready.

Note that std::string, like the C string API, will consider the "olé" string to have 4 characters, not three. So you should be cautious when truncating/playing with unicode chars because some combination of chars is forbidden in UTF-8.

On Windows?

On Windows, this is a bit different. Win32 had to support a lot of application working with char and on different charsets/codepages produced in all the world, before the advent of Unicode.

So their solution was an interesting one: If an application works with char, then the char strings are encoded/printed/shown on GUI labels using the local charset/codepage on the machine. For example, "olé" would be "olé" in a French-localized Windows, but would be something different on an cyrillic-localized Windows ("ol?" if you use Windows-1251). Thus, "historical apps" will usually still work the same old way.

For Unicode based applications, Windows uses wchar_t, which is 2-bytes wide, and is encoded in UTF-16, which is Unicode encoded on 2-bytes characters (or at the very least, the mostly compatible UCS-2, which is almost the same thing IIRC).

Applications using char are said "multibyte" (because each glyph is composed of one or more chars), while applications using wchar_t are said "widechar" (because each glyph is composed of one or two wchar_t. See MultiByteToWideChar and WideCharToMultiByte Win32 conversion API for more info.

Thus, if you work on Windows, you badly want to use wchar_t (unless you use a framework hiding that, like GTK+ or QT...). The fact is that behind the scenes, Windows works with wchar_t strings, so even historical applications will have their char strings converted in wchar_t when using API like SetWindowText() (low level API function to set the label on a Win32 GUI).

Memory issues?

UTF-32 is 4 bytes per characters, so there is no much to add, if only that a UTF-8 text and UTF-16 text will always use less or the same amount of memory than an UTF-32 text (and usually less).

If there is a memory issue, then you should know than for most western languages, UTF-8 text will use less memory than the same UTF-16 one.

Still, for other languages (chinese, japanese, etc.), the memory used will be either the same, or slightly larger for UTF-8 than for UTF-16.

All in all, UTF-16 will mostly use 2 and occassionally 4 bytes per characters (unless you're dealing with some kind of esoteric language glyphs (Klingon? Elvish?), while UTF-8 will spend from 1 to 4 bytes.

See http://en.wikipedia.org/wiki/UTF-8#Compared_to_UTF-16 for more info.

Conclusion

  1. When I should use std::wstring over std::string?

    On Linux? Almost never (§).
    On Windows? Almost always (§).
    On cross-platform code? Depends on your toolkit...

    (§) : unless you use a toolkit/framework saying otherwise

  2. Can std::string hold all the ASCII character set including special characters?

    Notice: A std::string is suitable for holding a 'binary' buffer, where a std::wstring is not!

    On Linux? Yes.
    On Windows? Only special characters available for the current locale of the Windows user.

    Edit (After a comment from Johann Gerell):
    a std::string will be enough to handle all char-based strings (each char being a number from 0 to 255). But:

    1. ASCII is supposed to go from 0 to 127. Higher chars are NOT ASCII.
    2. a char from 0 to 127 will be held correctly
    3. a char from 128 to 255 will have a signification depending on your encoding (unicode, non-unicode, etc.), but it will be able to hold all Unicode glyphs as long as they are encoded in UTF-8.
  3. Is std::wstring supported by almost all popular C++ compilers?

    Mostly, with the exception of GCC based compilers that are ported to Windows.
    It works on my g++ 4.3.2 (under Linux), and I used Unicode API on Win32 since Visual C++ 6.

  4. What is exactly a wide character?

    On C/C++, it's a character type written wchar_t which is larger than the simple char character type. It is supposed to be used to put inside characters whose indices (like Unicode glyphs) are larger than 255 (or 127, depending...).

HTML anchor tag with Javascript onclick event

From what I understand you do not want to redirect when the link is clicked. You can do :

<a href='javascript:;' onclick='show_more_menu();'>More ></a>

What does it mean when Statement.executeUpdate() returns -1?

I haven't seen this anywhere, either, but my instinct would be that this means that the IF prevented the whole statement from executing.

Try to run the statement with a database where the IF passes.

Also check if there are any triggers involved which might change the result.

[EDIT] When the standard says that this function should never return -1, that doesn't enforce this. Java doesn't have pre and post conditions. A JDBC driver could return a random number and there was no way to stop it.

If it's important to know why this happens, run the statement against different database until you have tried all execution paths (i.e. one where the IF returns false and one where it returns true).

If it's not that important, mark it off as a "clever trick" by a Microsoft engineer and remember how much you liked it when you feel like being clever yourself next time.

Check if value is zero or not null in python

Zero and None both treated as same for if block, below code should work fine.

if number or number==0:
    return True

Python: How to ignore an exception and proceed?

Generic answer

The standard "nop" in Python is the pass statement:

try:
    do_something()
except Exception:
    pass

Using except Exception instead of a bare except avoid catching exceptions like SystemExit, KeyboardInterrupt etc.

Python 2

Because of the last thrown exception being remembered in Python 2, some of the objects involved in the exception-throwing statement are being kept live indefinitely (actually, until the next exception). In case this is important for you and (typically) you don't need to remember the last thrown exception, you might want to do the following instead of pass:

try:
    do_something()
except Exception:
    sys.exc_clear()

This clears the last thrown exception.

Python 3

In Python 3, the variable that holds the exception instance gets deleted on exiting the except block. Even if the variable held a value previously, after entering and exiting the except block it becomes undefined again.

How to change color of Toolbar back button in Android?

You don't have to change style for it. After setting up your toolbar as actionbar, You can code like this

android.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
android.getSupportActionBar().setHomeAsUpIndicator(R.drawable.back);
//here back is your drawable image

But You cannot change color of back arrow by this method

og:type and valid values : constantly being parsed as og:type=website

bar is deprecated. Please check ogp.me for the current docs.

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

How to change background Opacity when bootstrap modal is open

After a day of struggling I figured out setting height :100% to .modal-backdrop.in class worked. height : 100% made opacity to show up whole page.

Matplotlib 2 Subplots, 1 Colorbar

This solution does not require manual tweaking of axes locations or colorbar size, works with multi-row and single-row layouts, and works with tight_layout(). It is adapted from a gallery example, using ImageGrid from matplotlib's AxesGrid Toolbox.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

# Set up figure and image grid
fig = plt.figure(figsize=(9.75, 3))

grid = ImageGrid(fig, 111,          # as in plt.subplot(111)
                 nrows_ncols=(1,3),
                 axes_pad=0.15,
                 share_all=True,
                 cbar_location="right",
                 cbar_mode="single",
                 cbar_size="7%",
                 cbar_pad=0.15,
                 )

# Add data to image grid
for ax in grid:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

# Colorbar
ax.cax.colorbar(im)
ax.cax.toggle_label(True)

#plt.tight_layout()    # Works, but may still require rect paramater to keep colorbar labels visible
plt.show()

image grid

How do I use LINQ Contains(string[]) instead of Contains(string)

Try the following.

string input = "someString";
string[] toSearchFor = GetSearchStrings();
var containsAll = toSearchFor.All(x => input.Contains(x));

C++ undefined reference to defined function

The declaration and definition of insertLike are different

In your header file:

void insertLike(const char sentence[], const int lengthTo, const int length, const char writeTo[]);

In your 'function file':

void insertLike(const char sentence[], const int lengthTo, const int length,char writeTo[]);

C++ allows function overloading, where you can have multiple functions/methods with the same name, as long as they have different arguments. The argument types are part of the function's signature.

In this case, insertLike which takes const char* as its fourth parameter and insertLike which takes char * as its fourth parameter are different functions.

Spring RestTemplate GET with parameters

If your url is http://localhost:8080/context path?msisdn={msisdn}&email={email}

then

Map<String,Object> queryParams=new HashMap<>();
queryParams.put("msisdn",your value)
queryParams.put("email",your value)

works for resttemplate exchange method as described by you

jQuery - select the associated label element of a input field

There are two ways to specify label for element:

  1. Setting label's "for" attribute to element's id
  2. Placing element inside label

So, the proper way to find element's label is

   var $element = $( ... )

   var $label = $("label[for='"+$element.attr('id')+"']")
   if ($label.length == 0) {
     $label = $element.closest('label')
   }

   if ($label.length == 0) {
     // label wasn't found
   } else {
     // label was found
   }

Add params to given URL in Python

python3, self explanatory I guess

from urllib.parse import urlparse, urlencode, parse_qsl

url = 'https://www.linkedin.com/jobs/search?keywords=engineer'

parsed = urlparse(url)
current_params = dict(parse_qsl(parsed.query))
new_params = {'location': 'United States'}
merged_params = urlencode({**current_params, **new_params})
parsed = parsed._replace(query=merged_params)

print(parsed.geturl())
# https://www.linkedin.com/jobs/search?keywords=engineer&location=United+States

How do I remove a MySQL database?

drop database <db_name>;
FLUSH PRIVILEGES;

What is the difference between prefix and postfix operators?

Let's keep this as simple as possible.

let i = 1
console.log('A', i)    // 1
console.log('B', ++i)  // 2
console.log('C', i++)  // 2
console.log('D', i)    // 3

A) Prints the value of i. B) First i is incremented then the console.log is run with i as it's new value. C) Console.log is run with i at its current value, then i will get incemented. D) Prints the value of i.

In short if you use the pre-shorthand i.e(++i) i will get updated before the line is executed. If you use the post-shorthand i.e(i++) the current line will run as if i had not been updated yet then i gets increased so ther next time your interpreter comes accross i it will have been increrased.

How to get these two divs side-by-side?

I found the below code very useful, it might help anyone who comes searching here

_x000D_
_x000D_
<html>_x000D_
<body>_x000D_
    <div style="width: 50%; height: 50%; background-color: green; float:left;">-</div>_x000D_
    <div style="width: 50%; height: 50%; background-color: blue; float:right;">-</div>_x000D_
    <div style="width: 100%; height: 50%; background-color: red; clear:both">-</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Create database from command line

Change the user to postgres :

su - postgres

Create User for Postgres

$ createuser testuser

Create Database

$ createdb testdb

Acces the postgres Shell

psql ( enter the password for postgressql)

Provide the privileges to the postgres user

$ alter user testuser with encrypted password 'qwerty';
$ grant all privileges on database testdb to testuser;

Difference between app.use and app.get in express.js

app.use is the "lower level" method from Connect, the middleware framework that Express depends on.

Here's my guideline:

  • Use app.get if you want to expose a GET method.
  • Use app.use if you want to add some middleware (a handler for the HTTP request before it arrives to the routes you've set up in Express), or if you'd like to make your routes modular (for example, expose a set of routes from an npm module that other web applications could use).

Android OnClickListener - identify a button

If you don't want to save instances of the 2 button in the class code, follow this BETTER way (this is more clear and fast!!) :

public void buttonPress(View v) {
  switch (v.getId()) {
    case R.id.button_one:
        // do something
        break;
    case R.id.button_two:
        // do something else
        break;
    case R.id.button_three:
        // i'm lazy, do nothing
        break;
  }
}

Add primary key to existing table

-- create new primary key constraint
ALTER TABLE dbo.persion 
ADD CONSTRAINT PK_persionId PRIMARY KEY NONCLUSTERED (pmid, persionId);

is a better solution because you have control over the naming of the primary_key.


It's better than just using

ALTER TABLE Persion ADD PRIMARY KEY(persionId,Pname,PMID)

which yeilds randomized names and can cause problems when scripting out or comparing databases

Difference between partition key, composite key and clustering key in Cassandra?

In cassandra , the difference between primary key,partition key,composite key, clustering key always makes some confusion.. So I am going to explain below and co relate to each others. We use CQL (Cassandra Query Language) for Cassandra database access. Note:- Answer is as per updated version of Cassandra. Primary Key :-

In cassandra there are 2 different way to use primary Key .

CREATE TABLE Cass (
    id int PRIMARY KEY,
    name text 
);

Create Table Cass (
   id int,
   name text,
   PRIMARY KEY(id) 
);

In CQL, the order in which columns are defined for the PRIMARY KEY matters. The first column of the key is called the partition key having property that all the rows sharing the same partition key (even across table in fact) are stored on the same physical node. Also, insertion/update/deletion on rows sharing the same partition key for a given table are performed atomically and in isolation. Note that it is possible to have a composite partition key, i.e. a partition key formed of multiple columns, using an extra set of parentheses to define which columns forms the partition key.

Partitioning and Clustering The PRIMARY KEY definition is made up of two parts: the Partition Key and the Clustering Columns. The first part maps to the storage engine row key, while the second is used to group columns in a row.

CREATE TABLE device_check (
  device_id   int,
  checked_at  timestamp,
  is_power    boolean,
  is_locked   boolean,
  PRIMARY KEY (device_id, checked_at)
);

Here device_id is partition key and checked_at is cluster_key.

We can have multiple cluster key as well as partition key too which depends on declaration.

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • MySQL DELETE FROM with subquery as condition

    You need to refer to the alias again in the delete statement, like:

    DELETE th FROM term_hierarchy AS th
    ....
    

    As outlined here in MySQL docs.

    What is default color for text in textview?

    There is no default color. It means that every device can have own.

    How to test enum types?

    I agree with aberrant80.

    For enums, I test them only when they actually have methods in them. If it's a pure value-only enum like your example, I'd say don't bother.

    But since you're keen on testing it, going with your second option is much better than the first. The problem with the first is that if you use an IDE, any renaming on the enums would also rename the ones in your test class.

    I would expand on it by adding that unit testings an Enum can be very useful. If you work in a large code base, build time starts to mount up and a unit test can be a faster way to verify functionality (tests only build their dependencies). Another really big advantage is that other developers cannot change the functionality of your code unintentionally (a huge problem with very large teams).

    And with all Test Driven Development, tests around an Enums Methods reduce the number of bugs in your code base.

    Simple Example

    public enum Multiplier {
        DOUBLE(2.0),
        TRIPLE(3.0);
    
        private final double multiplier;
    
        Multiplier(double multiplier) {
            this.multiplier = multiplier;
        }
    
        Double applyMultiplier(Double value) {
            return multiplier * value;
        }
    
    }
    
    public class MultiplierTest {
    
        @Test
        public void should() {
            assertThat(Multiplier.DOUBLE.applyMultiplier(1.0), is(2.0));
            assertThat(Multiplier.TRIPLE.applyMultiplier(1.0), is(3.0));
        }
    }
    

    What's the difference between lists and tuples?

    List is mutable and tuples is immutable. The main difference between mutable and immutable is memory usage when you are trying to append an item.

    When you create a variable, some fixed memory is assigned to the variable. If it is a list, more memory is assigned than actually used. E.g. if current memory assignment is 100 bytes, when you want to append the 101th byte, maybe another 100 bytes will be assigned (in total 200 bytes in this case).

    However, if you know that you are not frequently add new elements, then you should use tuples. Tuples assigns exactly size of the memory needed, and hence saves memory, especially when you use large blocks of memory.

    Rename specific column(s) in pandas

    There are at least five different ways to rename specific columns in pandas, and I have listed them below along with links to the original answers. I also timed these methods and found them to perform about the same (though YMMV depending on your data set and scenario). The test case below is to rename columns A M N Z to A2 M2 N2 Z2 in a dataframe with columns A to Z containing a million rows.

    # Import required modules
    import numpy as np
    import pandas as pd
    import timeit
    
    # Create sample data
    df = pd.DataFrame(np.random.randint(0,9999,size=(1000000, 26)), columns=list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
    
    # Standard way - https://stackoverflow.com/a/19758398/452587
    def method_1():
        df_renamed = df.rename(columns={'A': 'A2', 'M': 'M2', 'N': 'N2', 'Z': 'Z2'})
    
    # Lambda function - https://stackoverflow.com/a/16770353/452587
    def method_2():
        df_renamed = df.rename(columns=lambda x: x + '2' if x in ['A', 'M', 'N', 'Z'] else x)
    
    # Mapping function - https://stackoverflow.com/a/19758398/452587
    def rename_some(x):
        if x=='A' or x=='M' or x=='N' or x=='Z':
            return x + '2'
        return x
    def method_3():
        df_renamed = df.rename(columns=rename_some)
    
    # Dictionary comprehension - https://stackoverflow.com/a/58143182/452587
    def method_4():
        df_renamed = df.rename(columns={col: col + '2' for col in df.columns[
            np.asarray([i for i, col in enumerate(df.columns) if 'A' in col or 'M' in col or 'N' in col or 'Z' in col])
        ]})
    
    # Dictionary comprehension - https://stackoverflow.com/a/38101084/452587
    def method_5():
        df_renamed = df.rename(columns=dict(zip(df[['A', 'M', 'N', 'Z']], ['A2', 'M2', 'N2', 'Z2'])))
    
    print('Method 1:', timeit.timeit(method_1, number=10))
    print('Method 2:', timeit.timeit(method_2, number=10))
    print('Method 3:', timeit.timeit(method_3, number=10))
    print('Method 4:', timeit.timeit(method_4, number=10))
    print('Method 5:', timeit.timeit(method_5, number=10))
    

    Output:

    Method 1: 3.650640267
    Method 2: 3.163998427
    Method 3: 2.998530871
    Method 4: 2.9918436889999995
    Method 5: 3.2436501520000007
    

    Use the method that is most intuitive to you and easiest for you to implement in your application.

    jQuery remove special characters from string and more

    Assuming by "special" you mean non-word characters, then that is pretty easy.

    str = str.replace(/[_\W]+/g, "-")
    

    How to tell if tensorflow is using gpu acceleration from inside python shell?

    With the recent updates of Tensorflow, you can check it as follow :

    tf.test.is_gpu_available( cuda_only=False, min_cuda_compute_capability=None)
    

    This will return True if GPU is being used by Tensorflow, and return False otherwise.

    If you want device device_name you can type : tf.test.gpu_device_name(). Get more details from here

    Create a folder inside documents folder in iOS apps

    I don't like "[paths objectAtIndex:0]" because if Apple adds a new folder starting with "A", "B" oder "C", the "Documents"-folder isn't the first folder in the directory.

    Better:

    NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MyFolder"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
    

    SSIS cannot convert because a potential loss of data

    When you first set up this package, I am guessing that either a one or two digit number was the first value in the ShipTo column. Your package reading from the Excel picked a numeric type for that input field and the word "ALL" fails the package since the input spec for that field is numeric. There are several ways to fix this beforehand, but to fix it after the fact, the easiest way is to right click the Excel Source and choose Show Advanced Editor... From there, choose the tab that says Input and Output Properties. In the topmost part of the inputs and outputs section of that dialog box, find the column ShipTo. You will have to drill down to find it. Set the DataType to "string [DT_STR]" and the length to 20.

    Click OK then attempt to run your package again.

    Launch Pycharm from command line (terminal)

    After installing on kubuntu, I found that my pycharm script in ~/bin/pycharm was just a desktop entry:

    [Desktop Entry]                                                                                                                                                                                                 
    Version=1.0
    Type=Application
    Name=PyCharm Community Edition
    Icon=/snap/pycharm-community/79/bin/pycharm.png
    Exec=env BAMF_DESKTOP_FILE_HINT=/var/lib/snapd/desktop/applications/pycharm-community_pycharm-community.desktop /snap/bin/pycharm-community %f
    Comment=Python IDE for Professional Developers
    Categories=Development;IDE;
    Terminal=false
    StartupWMClass=jetbrains-pycharm-ce
    

    Obviously, I could not use this to open anything from the command line:

    $ pycharm setup.py
    /home/eldond/bin/pycharm_old: line 1: [Desktop: command not found
    /home/eldond/bin/pycharm_old: line 4: Community: command not found
    

    But there's a hint in the desktop entry file. Looking in /snap/pycharm-community/, I found /snap/pycharm-community/current/bin/pycharm.sh. I removed ~/bin/pycharm (actually renamed it to have a backup) and then did

    ln -s /snap/pycharm-community/current/bin/pycharm.sh pycharm
    

    where again, I found the start of the path by inspecting the desktop entry script I had to start with.

    Now I can open files with pycharm from the command line. I don't know what I messed up during install this time; the last two times I've done fresh installs, it's had no trouble.

    Self Join to get employee manager name

    Try this one.

    SELECT Employee.emp_id, Employee.emp_name,Manager.emp_id as Mgr_Id, Manager.emp_name as Mgr_Name 
    FROM tblEmployeeDetails Employee 
    LEFT JOIN tblEmployeeDetails Manager ON Employee.emp_mgr_id = Manager.emp_id
    

    Redirecting exec output to a buffer or file

    You could also use the linux sh command and pass it a command that includes the redirection:

    string cmd = "/bin/ls > " + filepath;
    
    execl("/bin/sh", "sh", "-c", cmd.c_str(), 0);
    

    How to List All Redis Databases?

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

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

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

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

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

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

    For instance:

    *2
    $4
    INFO
    $8
    keyspace
    
    $79
    # Keyspace
    db0:keys=10,expires=0
    db1:keys=1,expires=0
    db3:keys=1,expires=0
    

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

    Call a child class method from a parent class object

    NOTE: Though this is possible, it is not at all recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.

    However.. you should be able to do it like:

    void calculate(Person p) {
        ((Student)p).method();
    }
    

    a safe way would be:

    void calculate(Person p) {
        if(p instanceof Student) ((Student)p).method();
    }
    

    How to do an array of hashmaps?

    You can't have an array of a generic type. Use List instead.

    Convert bytes to bits in python

    Operations are much faster when you work at the integer level. In particular, converting to a string as suggested here is really slow.

    If you want bit 7 and 8 only, use e.g.

    val = (byte >> 6) & 3
    

    (this is: shift the byte 6 bits to the right - dropping them. Then keep only the last two bits 3 is the number with the first two bits set...)

    These can easily be translated into simple CPU operations that are super fast.

    in iPhone App How to detect the screen resolution of the device

    For iOS 8 we can just use this [UIScreen mainScreen].nativeBounds , like that:

    - (NSInteger)resolutionX
    {
        return CGRectGetWidth([UIScreen mainScreen].nativeBounds);
    }
    
    - (NSInteger)resolutionY
    {
        return CGRectGetHeight([UIScreen mainScreen].nativeBounds);
    }
    

    Executable directory where application is running from?

    You can write the following:

    Path.Combine(Path.GetParentDirectory(GetType(MyClass).Assembly.Location), "Images\image.jpg")
    

    Generate C# class from XML

    You can use xsd as suggested by Darin.

    In addition to that it is recommended to edit the test.xsd-file to create a more reasonable schema.

    type="xs:string" can be changed to type="xs:int" for integer values
    minOccurs="0" can be changed to minOccurs="1" where the field is required
    maxOccurs="unbounded" can be changed to maxOccurs="1" where only one item is allowed

    You can create more advanced xsd-s if you want to validate your data further, but this will at least give you reasonable data types in the generated c#.

    $(...).datepicker is not a function - JQuery - Bootstrap

    Need to include jquery-ui too:

    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    

    What is Linux’s native GUI API?

    The closest thing to Win32 in linux would be the libc, as you mention not only the UI but events and "other os stuff"

    UnsatisfiedDependencyException: Error creating bean with name

    According to documentation you should set XML configuration:

    <jpa:repositories base-package="com.kopylov.repository" />
    

    Why does Google prepend while(1); to their JSON responses?

    As this is a High traffic post i hope to provide here an answer slightly more undetermined to the original question and thus to provide further background on a JSON Hijacking attack and its consequences

    JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:

    [{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"}, 
    {"id":"1002","ccnum":"5555555555554444","balance":"10345.00"}, 
    {"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]
    

    This attack can be achieved in 3 major steps:

    Step 1: Get an authenticated user to visit a malicious page. Step 2: The malicious page will try and access sensitive data from the application that the user is logged into.This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.

    <script src="http://<jsonsite>/json_server.php"></script>
    

    The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request. Step 3: At this point while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.

    Object.prototype.__defineSetter__('ccnum',function(obj){
    
    secrets =secrets.concat(" ", obj);
    
    });
    

    At this point the malicious site has successfully hijacked the sensitive financial data (ccnum) returned byjson_server.php JSON

    It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty There is also a variation of this attack that should work on all browsers where full named JavaScript (e.g. pi=3.14159) is returned instead of a JSON array.

    There are several ways in which JSON Hijacking can be prevented:

    • Since SCRIPT tags can only generate HTTP GET requests, only return JSON objects to POST requests.

    • Prevent the web browser from interpreting the JSON object as valid JavaScript code.

    • Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.

    so as you can see While(1) comes under the last option. In the most simple terms, while(1) is an infinite loop which will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed.Alas, If you read the JSON block with a parser, the while(1) loop is ignored.

    So in conclusion, the while(1) loop can more easily visualised as a simple break statement cipher that google can use to control flow of data.

    However the key word in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has preventative measures embedded and the system is not crucial nor effective anymore. (part of this is the move away from JSON Hijacking to more fruitful datafarming techniques that i wont go into at present)

    *

    What is the worst programming language you ever worked with?

    I was going to bitch and moan about Java, but obviously it isn't THAT bad and that would have amounted to trolling, and besides, I just remembered something far worse:

    Magic II.

    It just barely qualified as a language. Really, it could be more accurately described as a pre-SQL database system with a data driven programming model. It was based on the astute observation that almost everything you ever do with database tables involves doing something before you start iterating on the data, then iterating on the data, and then maybe doing something after you're done.

    "Programming" Magic involves filling in fields in tables that describe those three phases of a program's life. It also had a text mode screen designer that tied in with this whole mess. A trained Magic user could knock out reports and data entry screens at a reasonably fast pace, which made management happy.

    The problem for me was that the language had very minimal abstraction facilities. You could define routines that you could call from other routines. That's it. No data structures other than database tables, no in-memory arrays (you could define new tables, though!)

    No hash tables, no way to organize variables (which the language did support) in any meaningful way. No lists. Nothing. Of course, no classes or anything resembling an object model, but honestly - I could live without that. And I did.

    Worse yet, the "program" had bits and pieces that were hidden away in fields that you had to zoom into to be able to see - certain expressions, etc. So you could never just read a screen of code and know what it did.

    This thing took data driven programming to its ultimate, sad apex. It's an obsession, manifested in a programming tool. I was glad to put that miserable piece of junk behind me.

    Recently, I met a former co-worker who worked with me while I was using Magic. It's been almost 20 years since I've done that, but she was all too happy to tell me how she was tasked with maintaining one of my projects, and that she declared defeat when she found a recursive procedure in there somewhere. She had never seen anyone implement recursion in Magic. No one ever has. It was uncharted territory. I don't think anyone realized the tool was capable of recursion.

    The project had to be rewritten in a hurry, before it caused someone's brain to explode.

    How can I check for an empty/undefined/null string in JavaScript?

    Try:

    if (str && str.trim().length) {  
        //...
    }
    

    No 'Access-Control-Allow-Origin' header in Angular 2 app

    Another simple way, without installing anything

    1. HTTP function

      authenticate(credentials) {
      
      let body = new URLSearchParams();
      body.set('username', credentials.username);
      body.set('password', credentials.password);
      
      return this.http.post(/rest/myEndpoint, body)
        .subscribe(
        data => this.loginResult = data,
        error => {
          console.log(error);
        },
        () => {
        // function to execute after successfull api call
        }
        );
       }
      
    2. Create a proxy.conf.json file

      {
       "/rest": {
      "target": "http://endpoint.com:8080/package/",
      "pathRewrite": {
        "^/rest": ""
      },
      "secure": false
      }
      }
      
    3. then ng serve --proxy-config proxy.conf.json (or) open package.json and replace

      "scripts": {
      "start": "ng serve --proxy-config proxy.conf.json",
       },
      

    and then npm start

    That's it.

    Check here https://webpack.github.io/docs/webpack-dev-server.html for more options

    Difference Between ViewResult() and ActionResult()

    ViewResult is a subclass of ActionResult. The View method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could change the method body to conditionally return a RedirectResult or something else without changing the method definition.

    How to get the current directory of the cmdlet being executed

    Yes, that should work. But if you need to see the absolute path, this is all you need:

    (Get-Item .).FullName
    

    What do the terms "CPU bound" and "I/O bound" mean?

    CPU Bound means the rate at which process progresses is limited by the speed of the CPU. A task that performs calculations on a small set of numbers, for example multiplying small matrices, is likely to be CPU bound.

    I/O Bound means the rate at which a process progresses is limited by the speed of the I/O subsystem. A task that processes data from disk, for example, counting the number of lines in a file is likely to be I/O bound.

    Memory bound means the rate at which a process progresses is limited by the amount memory available and the speed of that memory access. A task that processes large amounts of in memory data, for example multiplying large matrices, is likely to be Memory Bound.

    Cache bound means the rate at which a process progress is limited by the amount and speed of the cache available. A task that simply processes more data than fits in the cache will be cache bound.

    I/O Bound would be slower than Memory Bound would be slower than Cache Bound would be slower than CPU Bound.

    The solution to being I/O bound isn't necessarily to get more Memory. In some situations, the access algorithm could be designed around the I/O, Memory or Cache limitations. See Cache Oblivious Algorithms.

    Convert String to SecureString

    I'm agree with Spence (+1), but if you're doing it for learning or testing pourposes, you can use a foreach in the string, appending each char to the securestring using the AppendChar method.

    Regular expression negative lookahead

    A negative lookahead says, at this position, the following regex can not match.

    Let's take a simplified example:

    a(?!b(?!c))
    
    a      Match: (?!b) succeeds
    ac     Match: (?!b) succeeds
    ab     No match: (?!b(?!c)) fails
    abe    No match: (?!b(?!c)) fails
    abc    Match: (?!b(?!c)) succeeds
    

    The last example is a double negation: it allows a b followed by c. The nested negative lookahead becomes a positive lookahead: the c should be present.

    In each example, only the a is matched. The lookahead is only a condition, and does not add to the matched text.

    ES6 Class Multiple inheritance

    in javascript you cant give to a class (constructor function) 2 different prototype object and because inheritance in javascript work with prototype soo you cant do use more than 1 inheritance for one class but you can aggregate and join property of Prototype object and that main property inside a class manually with refactoring that parent classes and next extends that new version and joined class to your target class have code for your question :

    let Join = (...classList) => {
    
        class AggregatorClass {
    
            constructor() {
                classList.forEach((classItem, index) => {
    
                    let propNames = Object.getOwnPropertyNames(classItem.prototype);
    
                    propNames.forEach(name => {
                        if (name !== 'constructor') {
                            AggregatorClass.prototype[name] = classItem.prototype[name];
                        }
                    });
                });
    
                classList.forEach(constructor => {
                    Object.assign(AggregatorClass.prototype, new constructor())
                });
            }
        }
    
    
        return AggregatorClass
    
    };
    
    

    How to evaluate a math expression given in string form?

    You can also try the BeanShell interpreter:

    Interpreter interpreter = new Interpreter();
    interpreter.eval("result = (7+21*6)/(32-27)");
    System.out.println(interpreter.get("result"));
    

    std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

    They are not really same mutexes, lock_guard<muType> has nearly the same as std::mutex, with a difference that it's lifetime ends at the end of the scope (D-tor called) so a clear definition about these two mutexes :

    lock_guard<muType> has a mechanism for owning a mutex for the duration of a scoped block.

    And

    unique_lock<muType> is a wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.

    Here is an example implemetation :

    #include <iostream>
    #include <thread>
    #include <mutex>
    #include <condition_variable>
    #include <functional>
    #include <chrono>
    
    using namespace std::chrono;
    
    class Product{
    
       public:
    
           Product(int data):mdata(data){
           }
    
           virtual~Product(){
           }
    
           bool isReady(){
           return flag;
           }
    
           void showData(){
    
            std::cout<<mdata<<std::endl;
           }
    
           void read(){
    
             std::this_thread::sleep_for(milliseconds(2000));
    
             std::lock_guard<std::mutex> guard(mmutex);
    
             flag = true;
    
             std::cout<<"Data is ready"<<std::endl;
    
             cvar.notify_one();
    
           }
    
           void task(){
    
           std::unique_lock<std::mutex> lock(mmutex);
    
           cvar.wait(lock, [&, this]() mutable throw() -> bool{ return this->isReady(); });
    
           mdata+=1;
    
           }
    
       protected:
    
        std::condition_variable cvar;
        std::mutex mmutex;
        int mdata;
        bool flag = false;
    
    };
    
    int main(){
    
         int a = 0;
         Product product(a);
    
         std::thread reading(product.read, &product);
         std::thread setting(product.task, &product);
    
         reading.join();
         setting.join();
    
    
         product.showData();
        return 0;
    }
    

    In this example, i used the unique_lock<muType> with condition variable

    Python csv string to array

    Simple - the csv module works with lists, too:

    >>> a=["1,2,3","4,5,6"]  # or a = "1,2,3\n4,5,6".split('\n')
    >>> import csv
    >>> x = csv.reader(a)
    >>> list(x)
    [['1', '2', '3'], ['4', '5', '6']]
    

    Execute stored procedure with an Output parameter?

    First, declare the output variable:

    DECLARE @MyOutputParameter INT;
    

    Then, execute the stored procedure, and you can do it without parameter's names, like this:

    EXEC my_stored_procedure 'param1Value', @MyOutputParameter OUTPUT
    

    or with parameter's names:

    EXEC my_stored_procedure @param1 = 'param1Value', @myoutput = @MyOutputParameter OUTPUT
    

    And finally, you can see the output result by doing a SELECT:

    SELECT @MyOutputParameter 
    

    Regular expressions inside SQL Server

    stored value in DB is: 5XXXXXX [where x can be any digit]

    You don't mention data types - if numeric, you'll likely have to use CAST/CONVERT to change the data type to [n]varchar.

    Use:

    WHERE CHARINDEX(column, '5') = 1
      AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
      AND ISNUMERIC(column) = 1
    

    References:

    i have also different cases like XXXX7XX for example, so it has to be generic.

    Use:

    WHERE PATINDEX('%7%', column) = 5
      AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
      AND ISNUMERIC(column) = 1
    

    References:

    Regex Support

    SQL Server 2000+ supports regex, but the catch is you have to create the UDF function in CLR before you have the ability. There are numerous articles providing example code if you google them. Once you have that in place, you can use:

    • 5\d{6} for your first example
    • \d{4}7\d{2} for your second example

    For more info on regular expressions, I highly recommend this website.

    Custom UITableViewCell from nib in Swift

    Swift 4

    Register Nib

    override func viewDidLoad() {
        super.viewDidLoad()
        tblMissions.register(UINib(nibName: "MissionCell", bundle: nil), forCellReuseIdentifier: "MissionCell")
    }
    

    In TableView DataSource

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              guard let cell = tableView.dequeueReusableCell(withIdentifier: "MissionCell", for: indexPath) as? MissionCell else { return UITableViewCell() }
              return cell
        }
    

    Virtual/pure virtual explained

    "Virtual" means that the method may be overridden in subclasses, but has an directly-callable implementation in the base class. "Pure virtual" means it is a virtual method with no directly-callable implementation. Such a method must be overridden at least once in the inheritance hierarchy -- if a class has any unimplemented virtual methods, objects of that class cannot be constructed and compilation will fail.

    @quark points out that pure-virtual methods can have an implementation, but as pure-virtual methods must be overridden, the default implementation can't be directly called. Here is an example of a pure-virtual method with a default:

    #include <cstdio>
    
    class A {
    public:
        virtual void Hello() = 0;
    };
    
    void A::Hello() {
        printf("A::Hello\n");
    }
    
    class B : public A {
    public:
        void Hello() {
            printf("B::Hello\n");
            A::Hello();
        }
    };
    
    int main() {
        /* Prints:
               B::Hello
               A::Hello
        */
        B b;
        b.Hello();
        return 0;
    }
    

    According to comments, whether or not compilation will fail is compiler-specific. In GCC 4.3.3 at least, it won't compile:

    class A {
    public:
        virtual void Hello() = 0;
    };
    
    int main()
    {
        A a;
        return 0;
    }
    

    Output:

    $ g++ -c virt.cpp 
    virt.cpp: In function ‘int main()’:
    virt.cpp:8: error: cannot declare variable ‘a’ to be of abstract type ‘A’
    virt.cpp:1: note:   because the following virtual functions are pure within ‘A’:
    virt.cpp:3: note:   virtual void A::Hello()
    

    Connecting to local SQL Server database using C#

    If you use SQL authentication, use this:

    using System.Data.SqlClient;
    
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = 
         "Data Source=.\SQLExpress;" + 
         "User Instance=true;" + 
         "User Id=UserName;" + 
         "Password=Secret;" + 
         "AttachDbFilename=|DataDirectory|Database1.mdf;"
    conn.Open();
    

    If you use Windows authentication, use this:

    using System.Data.SqlClient;
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = 
         "Data Source=.\SQLExpress;" + 
         "User Instance=true;" + 
         "Integrated Security=true;" + 
         "AttachDbFilename=|DataDirectory|Database1.mdf;"
    conn.Open();
    

    Convert date to day name e.g. Mon, Tue, Wed

    Your code works for me

    $date = '15-12-2016';
    $nameOfDay = date('D', strtotime($date));
    echo $nameOfDay;
    

    Use l instead of D, if you prefer the full textual representation of the name

    How to run java application by .bat file

    • javac (.exe on Windows) binary path must be added into global PATH env. variable.

      javac MyProgram.java

    • or with java (.exe on Windows)

      java MyProgram.jar

    PySpark: withColumn() with two conditions and three outcomes

    There are a few efficient ways to implement this. Let's start with required imports:

    from pyspark.sql.functions import col, expr, when
    

    You can use Hive IF function inside expr:

    new_column_1 = expr(
        """IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
    )
    

    or when + otherwise:

    new_column_2 = when(
        col("fruit1").isNull() | col("fruit2").isNull(), 3
    ).when(col("fruit1") == col("fruit2"), 1).otherwise(0)
    

    Finally you could use following trick:

    from pyspark.sql.functions import coalesce, lit
    
    new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))
    

    With example data:

    df = sc.parallelize([
        ("orange", "apple"), ("kiwi", None), (None, "banana"), 
        ("mango", "mango"), (None, None)
    ]).toDF(["fruit1", "fruit2"])
    

    you can use this as follows:

    (df
        .withColumn("new_column_1", new_column_1)
        .withColumn("new_column_2", new_column_2)
        .withColumn("new_column_3", new_column_3))
    

    and the result is:

    +------+------+------------+------------+------------+
    |fruit1|fruit2|new_column_1|new_column_2|new_column_3|
    +------+------+------------+------------+------------+
    |orange| apple|           0|           0|           0|
    |  kiwi|  null|           3|           3|           3|
    |  null|banana|           3|           3|           3|
    | mango| mango|           1|           1|           1|
    |  null|  null|           3|           3|           3|
    +------+------+------------+------------+------------+
    

    Static variable inside of a function in C

    In C++11 at least, when the expression used to initialize a local static variable is not a 'constexpr' (cannot be evaluated by the compiler), then initialization must happen during the first call to the function. The simplest example is to directly use a parameter to intialize the local static variable. Thus the compiler must emit code to guess whether the call is the first one or not, which in turn requires a local boolean variable. I've compiled such example and checked this is true by seeing the assembly code. The example can be like this:

    void f( int p )
    {
      static const int first_p = p ;
      cout << "first p == " << p << endl ;
    }
    
    void main()
    {
       f(1); f(2); f(3);
    }
    

    of course, when the expresion is 'constexpr', then this is not required and the variable can be initialized on program load by using a value stored by the compiler in the output assembly code.

    Java - remove last known item from ArrayList

    The compiler complains that you are trying something of a list of ClientThread objects to a String. Either change the type of hey to ClientThread or clients to List<String>.

    In addition: Valid indices for lists are from 0 to size()-1.

    So you probably want to write

       String hey = clients.get(clients.size()-1);
    

    Multi-line bash commands in makefile

    What's wrong with just invoking the commands?

    foo:
           echo line1
           echo line2
           ....
    

    And for your second question, you need to escape the $ by using $$ instead, i.e. bash -c '... echo $$a ...'.

    EDIT: Your example could be rewritten to a single line script like this:

    gcc $(for i in `find`; do echo $i; done)
    

    Reading input files by line using read command in shell scripting skips last line

    read reads until it finds a newline character or the end of file, and returns a non-zero exit code if it encounters an end-of-file. So it's quite possible for it to both read a line and return a non-zero exit code.

    Consequently, the following code is not safe if the input might not be terminated by a newline:

    while read LINE; do
      # do something with LINE
    done
    

    because the body of the while won't be executed on the last line.

    Technically speaking, a file not terminated with a newline is not a text file, and text tools may fail in odd ways on such a file. However, I'm always reluctant to fall back on that explanation.

    One way to solve the problem is to test if what was read is non-empty (-n):

    while read -r LINE || [[ -n $LINE ]]; do
      # do something with LINE
    done
    

    Other solutions include using mapfile to read the file into an array, piping the file through some utility which is guaranteed to terminate the last line properly (grep ., for example, if you don't want to deal with blank lines), or doing the iterative processing with a tool like awk (which is usually my preference).

    Note that -r is almost certainly needed in the read builtin; it causes read to not reinterpret \-sequences in the input.

    SELECT where row value contains string MySQL

    SELECT * FROM Accounts WHERE Username LIKE '%$query%'
    

    but it's not suggested. use PDO

    Update query using Subquery in Sql Server

    you can join both tables even on UPDATE statements,

    UPDATE  a
    SET     a.marks = b.marks
    FROM    tempDataView a
            INNER JOIN tempData b
                ON a.Name = b.Name
    

    for faster performance, define an INDEX on column marks on both tables.

    using SUBQUERY

    UPDATE  tempDataView 
    SET     marks = 
            (
              SELECT marks 
              FROM tempData b 
              WHERE tempDataView.Name = b.Name
            )
    

    How do you produce a .d.ts "typings" definition file from an existing JavaScript library?

    Here is some PowerShell that creates a single TypeScript definition file a library that includes multiple *.js files with modern JavaScript.

    First, change all the extensions to .ts.

    Get-ChildItem | foreach { Rename-Item $_ $_.Name.Replace(".js", ".ts") }
    

    Second, use the TypeScript compiler to generate definition files. There will be a bunch of compiler errors, but we can ignore those.

    Get-ChildItem | foreach { tsc $_.Name  }
    

    Finally, combine all the *.d.ts files into one index.d.ts, removing the import statements and removing the default from each export statement.

    Remove-Item index.d.ts; 
    
    Get-ChildItem -Path *.d.ts -Exclude "Index.d.ts" | `
      foreach { Get-Content $_ } | `
      where { !$_.ToString().StartsWith("import") } | `
      foreach { $_.Replace("export default", "export") } | `
      foreach { Add-Content index.d.ts $_ }
    

    This ends with a single, usable index.d.ts file that includes many of the definitions.

    Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

    I found 3 ways to implement this:

    C# class:

    public class AddressInfo {
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
        public string Country { get; set; }
    }
    

    Action:

    [HttpPost]
    public ActionResult Check(AddressInfo addressInfo)
    {
        return Json(new { success = true });
    }
    

    JavaScript you can do it three ways:

    1) Query String:

    $.ajax({
        url: '/en/Home/Check',
        data: $('#form').serialize(),
        type: 'POST',
    });
    

    Data here is a string.

    "Address1=blah&Address2=blah&City=blah&State=blah&ZipCode=blah&Country=blah"

    2) Object Array:

    $.ajax({
        url: '/en/Home/Check',
        data: $('#form').serializeArray(),
        type: 'POST',
    });
    

    Data here is an array of key/value pairs :

    =[{name: 'Address1', value: 'blah'}, {name: 'Address2', value: 'blah'}, {name: 'City', value: 'blah'}, {name: 'State', value: 'blah'}, {name: 'ZipCode', value: 'blah'}, {name: 'Country', value: 'blah'}]
    

    3) JSON:

    $.ajax({
          url: '/en/Home/Check',
          data: JSON.stringify({ addressInfo:{//missing brackets
              Address1: $('#address1').val(),
              Address2: $('#address2').val(),
              City: $('#City').val(),
              State: $('#State').val(),
              ZipCode: $('#ZipCode').val()}}),
          type: 'POST',
          contentType: 'application/json; charset=utf-8'
    });
    

    Data here is a serialized JSON string. Note that the name has to match the parameter name in the server!!

    ='{"addressInfo":{"Address1":"blah","Address2":"blah","City":"blah","State":"blah", "ZipCode", "blah", "Country", "blah"}}'
    

    Count number of occurrences by month

    Recommend you use FREQUENCY rather than using COUNTIF.

    In your front sheet; enter 01/04/2014 into E5, 01/05/2014 into E6 etc.

    Select the range of adjacent cells you want to populate. Enter:

    =FREQUENCY(2013!!$A$2:$A$50,'2013 Metrics'!E5:EN)
    

    (where N is the final row reference in your range)

    Hit Ctrl + Shift + Enter

    python: order a list of numbers without built-in sort, min, max function

    Solution

    mylist = [1, 6, 7, 8, 1, 10, 15, 9]
    print(mylist)
    n = len(mylist)
    for i in range(n):
        for j in range(1, n-i):
            if mylist[j-1] > mylist[j]:
                 (mylist[j-1], mylist[j]) = (mylist[j], mylist[j-1])
    print(mylist)
    

    tsql returning a table from a function or store procedure

    You can't access Temporary Tables from within a SQL Function. You will need to use table variables so essentially:

    ALTER FUNCTION FnGetCompanyIdWithCategories()
    RETURNS  @rtnTable TABLE 
    (
        -- columns returned by the function
        ID UNIQUEIDENTIFIER NOT NULL,
        Name nvarchar(255) NOT NULL
    )
    AS
    BEGIN
    DECLARE @TempTable table (id uniqueidentifier, name nvarchar(255)....)
    
    insert into @myTable 
    select from your stuff
    
    --This select returns data
    insert into @rtnTable
    SELECT ID, name FROM @mytable 
    return
    END
    

    Edit

    Based on comments to this question here is my recommendation. You want to join the results of either a procedure or table-valued function in another query. I will show you how you can do it then you pick the one you prefer. I am going to be using sample code from one of my schemas, but you should be able to adapt it. Both are viable solutions first with a stored procedure.

    declare @table as table (id int, name nvarchar(50),templateid int,account nvarchar(50))
    
    insert into @table
    execute industry_getall
    
    select * 
    from @table 
    inner join [user] 
        on account=[user].loginname
    

    In this case, you have to declare a temporary table or table variable to store the results of the procedure. Now Let's look at how you would do this if you were using a UDF

    select *
    from fn_Industry_GetAll()
    inner join [user] 
        on account=[user].loginname
    

    As you can see the UDF is a lot more concise easier to read, and probably performs a little bit better since you're not using the secondary temporary table (performance is a complete guess on my part).

    If you're going to be reusing your function/procedure in lots of other places, I think the UDF is your best choice. The only catch is you will have to stop using #Temp tables and use table variables. Unless you're indexing your temp table, there should be no issue, and you will be using the tempDb less since table variables are kept in memory.

    Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

    Uninstall the old app from the device/emulator. It worked for me

    How do I find out where login scripts live?

    In addition from the command prompt run SET.

    This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

    Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

    How do I keep two side-by-side divs the same height?

    If you don't mind one of the divs being a master and dictating the height for both divs there is this:

    Fiddle

    No matter what, the div on the right will expand or squish&overflow to match the height of the div on the left.

    Both divs must be immediate children of a container, and have to specify their widths within it.

    Relevant CSS:

    .container {
        background-color: gray;
        display: table;
        width: 70%;
        position:relative;
    }
    
    .container .left{
        background-color: tomato;
        width: 35%;
    }
    
    .container .right{
        position:absolute;
        top:0px;
        left:35%;
        background-color: orange;
        width: 65%;
        height:100%;
        overflow-y: auto;
    }
    

    javascript object max size limit

    you have to put this in web.config :

    <system.web.extensions>
        <scripting>
          <webServices>
            <jsonSerialization maxJsonLength="50000000" />
          </webServices>
        </scripting>
      </system.web.extensions>
    

    Accessing elements of Python dictionary by index

    If the questions is, if I know that I have a dict of dicts that contains 'Apple' as a fruit and 'American' as a type of apple, I would use:

    myDict = {'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
              'Grapes':{'Arabian':'25','Indian':'20'} }
    
    
    print myDict['Apple']['American']
    

    as others suggested. If instead the questions is, you don't know whether 'Apple' as a fruit and 'American' as a type of 'Apple' exist when you read an arbitrary file into your dict of dict data structure, you could do something like:

    print [ftype['American'] for f,ftype in myDict.iteritems() if f == 'Apple' and 'American' in ftype]
    

    or better yet so you don't unnecessarily iterate over the entire dict of dicts if you know that only Apple has the type American:

    if 'Apple' in myDict:
        if 'American' in myDict['Apple']:
            print myDict['Apple']['American']
    

    In all of these cases it doesn't matter what order the dictionaries actually store the entries. If you are really concerned about the order, then you might consider using an OrderedDict:

    http://docs.python.org/dev/library/collections.html#collections.OrderedDict

    Import a custom class in Java

    I see the picture, and all your classes are in the same package. So you don't have to import, you can create a new instance without the import sentence.

    How to find sitemap.xml path on websites?

    According to protocol documentation there are at least three options website designers can use to inform sitemap.xml location to search engines:

    • Informing each search engine of the location through their provided interface
    • Adding url to the robots.txt file
    • Submiting url to search engines through http

    So, unless they have chosen to publish the sitemap location on their robots.txt file, you cannot really know where they have put their sitemap.xml files.

    Can't ignore UserInterfaceState.xcuserstate

    All Answer is great but here is the one will remove for every user if you work in different Mac (Home and office)

    git rm --cache */UserInterfaceState.xcuserstate
    git commit -m "Never see you again, UserInterfaceState"
    

    Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

    It was particular for me. I am sending a header named 'SESSIONHASH'. No problem for Chrome and Opera, but Firefox also wants this header in the list "Access-Control-Allow-Headers". Otherwise, Firefox will throw the CORS error.

    The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

    You do not need to use ORDER BY in inner query after WHERE clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC).

    SELECT 
        * 
    FROM (
        SELECT 
            Stockmain.VRNOA, 
            item.description as item_description, 
            party.name as party_name, 
            stockmain.vrdate, 
            stockdetail.qty, 
            stockdetail.rate, 
            stockdetail.amount, 
            ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum  --< ORDER BY
        FROM StockMain 
        INNER JOIN StockDetail 
            ON StockMain.stid = StockDetail.stid 
        INNER JOIN party 
            ON party.party_id = stockmain.party_id 
        INNER JOIN item 
            ON item.item_id = stockdetail.item_id 
        WHERE stockmain.etype='purchase' 
    ) AS MyDerivedTable
    WHERE 
        MyDerivedTable.RowNum BETWEEN 1 and 5 
    

    Select rows with same id but different value in another column

    Use this

    select * from (
     SELECT ARIDNR,LIEFNR,row_number() over 
         (partition by ARIDNR order by ARIDNR) as RowNum) a
    where a.RowNum >1
    

    Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

    This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

    EX:

    function test(){
        "use strict";
        let a = 1;
    } 
    

    How can I include null values in a MIN or MAX?

    It's a bit ugly but because the NULLs have a special meaning to you, this is the cleanest way I can think to do it:

    SELECT recordid, MIN(startdate),
       CASE WHEN MAX(CASE WHEN enddate IS NULL THEN 1 ELSE 0 END) = 0
            THEN MAX(enddate)
       END
    FROM tmp GROUP BY recordid
    

    That is, if any row has a NULL, we want to force that to be the answer. Only if no rows contain a NULL should we return the MIN (or MAX).

    How do I deploy Node.js applications as a single executable file?

    There are a number of steps you have to go through to create an installer and it varies for each Operating System. For Example:

    PHPMailer AddAddress()

    All answers are great. Here is an example use case for multiple add address: The ability to add as many email you want on demand with a web form:

    See it in action with jsfiddle here (except the php processor)

    ### Send unlimited email with a web form
    # Form for continuously adding e-mails:
    <button type="button" onclick="emailNext();">Click to Add Another Email.</button>
    <div id="addEmail"></div>
    <button type="submit">Send All Emails</button>
    # Script function:
    <script>
    function emailNext() {
        var nextEmail, inside_where;
        nextEmail = document.createElement('input');
        nextEmail.type = 'text';
        nextEmail.name = 'emails[]';
        nextEmail.className = 'class_for_styling';
        nextEmail.style.display = 'block';
        nextEmail.placeholder  = 'Enter E-mail Here';
        inside_where = document.getElementById('addEmail');
        inside_where.appendChild(nextEmail);
        return false;
    }
    </script>
    # PHP Data Processor:
    <?php
    // ...
    // Add the rest of your $mailer here...
    if ($_POST[emails]){
        foreach ($_POST[emails] AS $postEmail){
            if ($postEmail){$mailer->AddAddress($postEmail);}
        }
    } 
    ?>
    

    So what it does basically is to generate a new input text box on every click with the name "emails[]".

    The [] added at the end makes it an array when posted.

    Then we go through each element of the array with "foreach" on PHP side adding the:

        $mailer->AddAddress($postEmail);