Programs & Examples On #Windows security

How to get HttpClient to pass credentials along with the request?

You can configure HttpClient to automatically pass credentials like this:

var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

How to get user name using Windows authentication in asp.net?

You can read the Name from WindowsIdentity:

var user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
return Ok(user);

Android Design Support Library expandable Floating Action Button(FAB) menu

  • First create the menu layouts in the your Activity layout xml file. For e.g. a linear layout with horizontal orientation and include a TextView for label then a Floating Action Button beside the TextView.

  • Create the menu layouts as per your need and number.

  • Create a Base Floating Action Button and on its click of that change the visibility of the Menu Layouts.

Please check the below code for the reference and for more info checkout my project from github

Checkout project from Github

<android.support.constraint.ConstraintLayout
            android:id="@+id/activity_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context="com.app.fabmenu.MainActivity">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/baseFloatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                android:clickable="true"
                android:onClick="@{FabHandler::onBaseFabClick}"
                android:tint="@android:color/white"
                app:fabSize="normal"
                app:layout_constraintBottom_toBottomOf="@+id/activity_main"
                app:layout_constraintRight_toRightOf="@+id/activity_main"
                app:srcCompat="@drawable/ic_add_black_24dp" />

            <LinearLayout
                android:id="@+id/shareLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="12dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/createLayout"
                app:layout_constraintLeft_toLeftOf="@+id/createLayout"
                app:layout_constraintRight_toRightOf="@+id/activity_main">

                <TextView
                    android:id="@+id/shareLabelTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:background="@drawable/shape_fab_label"
                    android:elevation="2dp"
                    android:fontFamily="sans-serif"
                    android:padding="5dip"
                    android:text="Share"
                    android:textColor="@android:color/white"
                    android:typeface="normal" />


                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/shareFab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:onClick="@{FabHandler::onShareFabClick}"
                    android:tint="@android:color/white"
                    app:fabSize="mini"
                    app:srcCompat="@drawable/ic_share_black_24dp" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/createLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="24dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/baseFloatingActionButton"
                app:layout_constraintRight_toRightOf="@+id/activity_main">

                <TextView
                    android:id="@+id/createLabelTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:background="@drawable/shape_fab_label"
                    android:elevation="2dp"
                    android:fontFamily="sans-serif"
                    android:padding="5dip"
                    android:text="Create"
                    android:textColor="@android:color/white"
                    android:typeface="normal" />

                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/createFab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:onClick="@{FabHandler::onCreateFabClick}"
                    android:tint="@android:color/white"
                    app:fabSize="mini"
                    app:srcCompat="@drawable/ic_create_black_24dp" />

            </LinearLayout>

        </android.support.constraint.ConstraintLayout>

These are the animations-

Opening animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
    android:duration="300"
    android:fromXScale="0"
    android:fromYScale="0"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="1"
    android:toYScale="1" />
<alpha
    android:duration="300"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="1.0" />

</set>

Closing animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
    android:duration="300"
    android:fromXScale="1"
    android:fromYScale="1"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="0.0"
    android:toYScale="0.0" />
<alpha
    android:duration="300"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="0.0" />
</set>

Then in my Activity I've simply used the animations above to show and hide the FAB menu :

Show Fab Menu:

  private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabOpenAnimation);
    binding.shareLayout.startAnimation(fabOpenAnimation);
    binding.createFab.setClickable(true);
    binding.shareFab.setClickable(true);
    isFabMenuOpen = true;

}

Close Fab Menu:

private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabCloseAnimation);
    binding.shareLayout.startAnimation(fabCloseAnimation);
    binding.createFab.setClickable(false);
    binding.shareFab.setClickable(false);
    isFabMenuOpen = false;

}

Here is the the Activity class -

package com.app.fabmenu;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;

import com.app.fabmenu.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

private ActivityMainBinding binding;
private Animation fabOpenAnimation;
private Animation fabCloseAnimation;
private boolean isFabMenuOpen = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    binding = DataBindingUtil.setContentView(this,    R.layout.activity_main);
    binding.setFabHandler(new FabHandler());

    getAnimations();


}

private void getAnimations() {

    fabOpenAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_open);

    fabCloseAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_close);

}

private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabOpenAnimation);
    binding.shareLayout.startAnimation(fabOpenAnimation);
    binding.createFab.setClickable(true);
    binding.shareFab.setClickable(true);
    isFabMenuOpen = true;


}

private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabCloseAnimation);
    binding.shareLayout.startAnimation(fabCloseAnimation);
    binding.createFab.setClickable(false);
    binding.shareFab.setClickable(false);
    isFabMenuOpen = false;

}


public class FabHandler {

    public void onBaseFabClick(View view) {

        if (isFabMenuOpen)
            collapseFabMenu();
        else
            expandFabMenu();


    }

    public void onCreateFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Create FAB tapped", Snackbar.LENGTH_SHORT).show();

    }

    public void onShareFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Share FAB tapped", Snackbar.LENGTH_SHORT).show();

    }


}

@Override
public void onBackPressed() {

    if (isFabMenuOpen)
        collapseFabMenu();
    else
        super.onBackPressed();
}
}

Here are the screenshots

Floating Action Menu with Label Textview in new Cursive Font Family of Android

Floating Action Menu with Label Textview in new Roboto Font Family of Android

Format numbers to strings in Python

Python 2.6+

It is possible to use the format() function, so in your case you can use:

return '{:02d}:{:02d}:{:.2f} {}'.format(hours, minutes, seconds, ampm)

There are multiple ways of using this function, so for further information you can check the documentation.

Python 3.6+

f-strings is a new feature that has been added to the language in Python 3.6. This facilitates formatting strings notoriously:

return f'{hours:02d}:{minutes:02d}:{seconds:.2f} {ampm}'

How do I increase the RAM and set up host-only networking in Vagrant?

I could not get any of these answers to work. Here's what I ended up putting at the very top of my Vagrantfile, before the Vagrant::Config.run do block:

Vagrant.configure("2") do |config|
  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "1024"]
  end
end

I noticed that the shortcut accessor style, "vb.memory = 1024", didn't seem to work.

How to save public key from a certificate in .pem format

There are a couple ways to do this.

First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:

E:\> openssl x509 -pubkey -noout -in cert.pem  > pubkey.pem

If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.

openssl> x509 -pubkey -noout -in cert.pem

Output will look something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----

Change first commit of project with Git?

If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?

And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History

cat, grep and cut - translated to python

For Translating the command to python refer below:-

1)Alternative of cat command is open refer this. Below is the sample

>>> f = open('workfile', 'r')
>>> print f

2)Alternative of grep command refer this

3)Alternative of Cut command refer this

How to leave space in HTML

“Insensitive to space” is an oversimplification. A more accurate description is that consecutive whitespace characters (spaces, tabs, newlines) are equivalent to a single space, in normal content.

You make empty spaces between words using space characters: “hello world”. I you want more space, you should consider what you are doing, since in normal text content, that does not make sense. For spacing elements, use CSS margin properties.

To get useful example codes, you need to describe a specific problem, like markup and a description of desired rendering.

How to extend an existing JavaScript array with another array, without creating a new array

Super simple, does not count on spread operators or apply, if that's an issue.

b.map(x => a.push(x));

After running some performance tests on this, it's terribly slow, but answers the question in regards to not creating a new array. Concat is significantly faster, even jQuery's $.merge() whoops it.

https://jsperf.com/merge-arrays19b/1

How do I convert a byte array to Base64 in Java?

Java 8+

Encode or decode byte arrays:

byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded)    // Outputs "Hello"

For more info, see Base64.

Java < 8

Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.

For direct byte arrays:

Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = codec.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(codec.decodeBase64(encoded));
println(decoded)    // Outputs "Hello"

Spring

If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils class more ergonomic:

For direct byte arrays:

byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded))    // Outputs "SGVsbG8="

byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded))    // Outputs "Hello"

Android (with Java < 8)

If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64.

For direct byte arrays:

byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded))    // Outputs "SGVsbG8="

byte [] decoded = Base64.decode(encoded);
println(new String(decoded))    // Outputs "Hello"

Or if you just want the strings:

String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(Base64.decode(encoded));
println(decoded)    // Outputs "Hello"

Test if a vector contains a given element

You can use the %in% operator:

vec <- c(1, 2, 3, 4, 5)
1 %in% vec # true
10 %in% vec # false

What is the difference between UNION and UNION ALL?

Important! Difference between Oracle and Mysql: Let's say that t1 t2 don't have duplicate rows between them but they have duplicate rows individual. Example: t1 has sales from 2017 and t2 from 2018

SELECT T1.YEAR, T1.PRODUCT FROM T1

UNION ALL

SELECT T2.YEAR, T2.PRODUCT FROM T2

In ORACLE UNION ALL fetches all rows from both tables. The same will occur in MySQL.

However:

SELECT T1.YEAR, T1.PRODUCT FROM T1

UNION

SELECT T2.YEAR, T2.PRODUCT FROM T2

In ORACLE, UNION fetches all rows from both tables because there are no duplicate values between t1 and t2. On the other hand in MySQL the resultset will have fewer rows because there will be duplicate rows within table t1 and also within table t2!

Combining two expressions (Expression<Func<T, bool>>)

I needed to achieve the same results, but using something more generic (as the type was not known). Thanks to marc's answer I finally figured out what I was trying to achieve:

    public static LambdaExpression CombineOr(Type sourceType, LambdaExpression exp, LambdaExpression newExp) 
    {
        var parameter = Expression.Parameter(sourceType);

        var leftVisitor = new ReplaceExpressionVisitor(exp.Parameters[0], parameter);
        var left = leftVisitor.Visit(exp.Body);

        var rightVisitor = new ReplaceExpressionVisitor(newExp.Parameters[0], parameter);
        var right = rightVisitor.Visit(newExp.Body);

        var delegateType = typeof(Func<,>).MakeGenericType(sourceType, typeof(bool));
        return Expression.Lambda(delegateType, Expression.Or(left, right), parameter);
    }

Using ADB to capture the screen

To save to a file on Windows, OSX and Linux

adb exec-out screencap -p > screen.png

To copy to clipboard on Linux use

adb exec-out screencap -p | xclip -t image/png

Unnamed/anonymous namespaces vs. static functions

Putting methods in an anonymous namespace prevents you from accidentally violating the One Definition Rule, allowing you to never worry about naming your helper methods the same as some other method you may link in.

And, as pointed out by luke, anonymous namespaces are preferred by the standard over static members.

How do you create a yes/no boolean field in SQL server?

bit will be the simplest and also takes up the least space. Not very verbose compared to "Y/N" but I am fine with it.

Can I change the color of Font Awesome's icon color?

To change the font awesome icons color for your entire project use this in your css

.fa {
  color : red;
}

ASP.NET MVC3 - textarea with @Html.EditorFor

@Html.TextAreaFor(model => model.Text)

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

Apache Spark: The number of cores vs. the number of executors

I think one of the major reasons is locality. Your input file size is 165G, the file's related blocks certainly distributed over multiple DataNodes, more executors can avoid network copy.

Try to set executor num equal blocks count, i think can be faster.

Variably modified array at file scope

It is also possible to use enumeration.

typedef enum {
    typeNo1 = 1,
    typeNo2,
    typeNo3,
    typeNo4,
    NumOfTypes = typeNo4
}  TypeOfSomething;

What is a software framework?

Technically, you don't need a framework. If you're making a really really simple site (think of the web back in 1992), you can just do it all with hard-coded HTML and some CSS.

And if you want to make a modern webapp, you don't actually need to use a framework for that, either.

You can instead choose to write all of the logic you need yourself, every time. You can write your own data-persistence/storage layer, or - if you're too busy - just write custom SQL for every single database access. You can write your own authentication and session handling layers. And your own template rending logic. And your own exception-handling logic. And your own security functions. And your own unit test framework to make sure it all works fine. And your own... [goes on for quite a long time]

Then again, if you do use a framework, you'll be able to benefit from the good, usually peer-reviewed and very well tested work of dozens if not hundreds of other developers, who may well be better than you. You'll get to build what you want rapidly, without having to spend time building or worrying too much about the infrastructure items listed above.

You can get more done in less time, and know that the framework code you're using or extending is very likely to be done better than you doing it all yourself.

And the cost of this? Investing some time learning the framework. But - as virtually every web dev out there will attest - it's definitely worth the time spent learning to get massive (really, massive) benefits from using whatever framework you choose.

Sort ObservableCollection<string> through C#

I did a sort on a certain class field (distance).

public class RateInfo 
{
    public string begin { get; set; }
    public string end { get; set; }
    public string price { get; set; }
    public string comment { get; set; }
    public string phone { get; set; }
    public string ImagePath { get; set; }
    public string what { get; set; }
    public string distance { get; set; }
}    

public ObservableCollection<RateInfo> Phones { get; set; }

public List<RateInfo> LRate { get; set; }

public ObservableCollection<RateInfo> Phones { get; set; }

public List<RateInfo> LRate { get; set; }

......

foreach (var item in ph)
        {

            LRate.Add(new RateInfo { begin = item["begin"].ToString(), end = item["end"].ToString(), price = item["price"].ToString(), distance=kilom, ImagePath = "chel.png" });
        }

       LRate.Sort((x, y) => x.distance.CompareTo(y.distance));

        foreach (var item in LRate)
        {
            Phones.Add(item);
        }

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

Another way to do it is to make an empty section right before the one you want the header on and put your header on that section. Because the section is empty the header will scroll immediately.

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

Docker - alternative approach

Docker is some-kind of super-fast virtual machine which can be use to run tools like node (instead install them directly on mac-os). Advantages to do it are following

  • all stuff ('milions' node files) are install inside docker image/container (they encapsulated in few inner-docker files)

  • you can map your mac directory with project to your docker container and have access to node - but outside docker, mac-os sytem don't even know that node is installed. So you get some kind of 'virtual' console with available node commands which can works on real files

  • you can easily kill node by find it by docker ps and kill by docker rm -f name_or_num

  • you can easily uninstall docker image/containers by one command docker rmi ... and get free space - and install it again by run script (below)

  • your node is encapsulated inside docker and don't have access to whole system - only to folders you map to it

  • you can run node services and easily map they port to mac port and have access to it from web browser

  • you can run many node versions at the same time

  • in similar way you can install other tools like (in many versions in same time): php, databases, redis etc. - inside docker without any interaction with mac-os (which not notice such software at all). E.g. you can run at the same time 3 mysql db with different versions and 3 php application with different php version ... - so you can have many tools but clean system

  • TEAM WORK: such enviroment can be easily cloned into other machines (and even to windows/linux systems - with some modifications) and provide identical docker-level environment - so you can easily set up and reuse you scripts/dockerfiles, and setup environment for new team member in very fast way (he just need to install docker and create similar folder-structure and get copy of scripts - thats all). I work this way for 2 year and with my team - and we are very happy

Instruction

  • Install docker using e.g. this instructions

  • Prepare 'special' directory for work e.g. my directory is /Users/kamil/work (I will use this directory further - but it can be arbitrary) - this directory will be 'interface' between docker containers and your mac file ststem. Inside this dir create following dir structure:

    /Users/kamil/work/code - here you put your projects with code

    /Users/kamil/work/tools

    /Users/kamil/work/tools/docker-data - here we map containers output data like logs (or database files if someone ouse db etc.)

    /Users/kamil/work/tools/docker

    /Users/kamil/work/tools/docker/node-cmd - here we put docker node scripts

  • inside tools create file .env which will contain in one place global-paths used in other scripts

    _x000D_
    _x000D_
    toolspath="/Users/kamil/work/tools"
    codepath="/Users/kamil/work/code"
    workpath=/Users/kamil/work
    _x000D_
    _x000D_
    _x000D_

  • innside dir ../node-cmd create file dockerfile with following content

    _x000D_
    _x000D_
    # default  /var/www/html (mapped to .../code folder with projects)
    FROM node
    
    WORKDIR /work
    
    # Additional arbitrary tools (ng, gulp, bower)
    RUN npm install -g n @angular/cli bower gulp grunt
    
    CMD while true; do sleep 10000; done
    
    # below ports are arbitrary
    EXPOSE 3002 3003 3004 4200
    _x000D_
    _x000D_
    _x000D_

  • innside dir ../node-cmd create file run-container with following content (this file should be executable e.g. by chmod +x run-container) - (notice how we map port-s and directories form external 'world' to internal docker filesystem)

    _x000D_
    _x000D_
    set -e
    cd -- "$(dirname "$0")" # this script dir (not set on doubleclick)
    source ../../.env
    toolsdir=$toolspath/docker-data
    workdir=$workpath
    
    if [ ! "$(docker ps | grep node-cmd)" ] 
    then 
      docker build -t node-cmd .
      docker rm -f node-cmd |:
      docker run -d --name node-cmd -p 4200:4200 -p 4201:4201 -p 3002:3002 -p 3003:3003 -p 3004:3004 -v $toolsdir/node-cmd/logs:/root/.npm/_logs -v $workdir:/work node-cmd
    fi
    _x000D_
    _x000D_
    _x000D_

  • ok now you can add some project e.g. work/code/myProject and add to it following file 'run-cmd' (must be executable)

    _x000D_
    _x000D_
    cd -- "$(dirname "$0")"
    ../../tools/docker/node-cmd/run-container
    docker exec -it node-cmd bash -c "cd /work/code/myProject; bash"
    _x000D_
    _x000D_
    _x000D_

  • then if you run above script (by double-click), you will see console with available node commands in project directory e.g. npm install

  • to run project in background (e.g some serwice) e.g. run web-server angular-cli application you can use following script (named run-front -must be executable) - (you must also edit /etc/hosts file to add proper domain)

    _x000D_
    _x000D_
    cd -- "$(dirname "$0")"
    open "http://my-angular.local:3002"
    ../../tools/docker/node-cmd/run-container
    docker exec -it node-cmd  /bin/sh -c "cd /work/code/my-angular-project; npm start"
    cat         # for block script and wait for user ctrl+C
    _x000D_
    _x000D_
    _x000D_

How do I concatenate two strings in C?

Without GNU extension:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    const char str1[] = "First";
    const char str2[] = "Second";
    char *res;

    res = malloc(strlen(str1) + strlen(str2) + 1);
    if (!res) {
        fprintf(stderr, "malloc() failed: insufficient memory!\n");
        return EXIT_FAILURE;
    }

    strcpy(res, str1);
    strcat(res, str2);

    printf("Result: '%s'\n", res);
    free(res);
    return EXIT_SUCCESS;
}

Alternatively with GNU extension:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    const char str1[] = "First";
    const char str2[] = "Second";
    char *res;

    if (-1 == asprintf(&res, "%s%s", str1, str2)) {
        fprintf(stderr, "asprintf() failed: insufficient memory!\n");
        return EXIT_FAILURE;
    }

    printf("Result: '%s'\n", res);
    free(res);
    return EXIT_SUCCESS;
}

See malloc, free and asprintf for more details.

How to check if there exists a process with a given pid in Python?

Have a look at the psutil module:

psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network) in Python. [...] It currently supports Linux, Windows, OSX, FreeBSD and Sun Solaris, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.4 (users of Python 2.4 and 2.5 may use 2.1.3 version). PyPy is also known to work.

It has a function called pid_exists() that you can use to check whether a process with the given pid exists.

Here's an example:

import psutil
pid = 12345
if psutil.pid_exists(pid):
    print("a process with pid %d exists" % pid)
else:
    print("a process with pid %d does not exist" % pid)

For reference:

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

Shell Script: Execute a python program from within a shell script

This works for me:

  1. Create a new shell file job. So let's say: touch job.sh and add command to run python script (you can even add command line arguments to that python, I usually predefine my command line arguments).

    chmod +x job.sh

  2. Inside job.sh add the following py files, let's say:

    python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file.py"

    python_file1.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file1.py"

Output of job.sh should look like this:

Done with python_file.py

Done with python_file1.py

I use this usually when I have to run multiple python files with different arguments, pre defined.

Note: Just a quick heads up on what's going on here:

python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "completed with python_file.py" . 

  • Here shell script will run the file python_file.py and add multiple command-line arguments at run time to the python file.
  • This does not necessarily means, you have to pass command line arguments as well.
  • You can just use it like: python python_file.py, plain and simple. Next up, the >> will print and store the output of this .py file in the testpy-output.txt file.
  • && is a logical operator that will run only after the above is executed successfully and as an optional echo "completed with python_file.py" will be echoed on to your cli/terminal at run time.

Adding a collaborator to my free GitHub account?

Clear Instructions On How to Add A Collaborator - 2020 Update

Pictures are worth a thousand words. Let's put that to the test:

Picture Instructions (Click to Zoom in):

Picture Instructions

.......and videos/gifs are worth another thousand more:

Gif Instructions (Click to Zoom in):

Hopefully the pictures/gif make it easier for you to configure this!

enter image description here

Errors: Data path ".builders['app-shell']" should have required property 'class'

This happened to me when I installed Angular 8, there are some incompatibilities I couldn't solve. I had to downgrade because I went down the rabbit hole juggling around with every version until I found one that worked.

First, TypeScript was outdated, the default installation added a reference to TypeScript 3.1.6 and it requires 3.4 or greater.

npm install typescript@">=3.4 <3.5"

Second, using the devkit 0.800.1 or 0.800.1 always ended up in incompatibilities. I tried many combinations but I am not sure it's fully compatible yet, specially because I am using one bootstrap a bit older and I cannot upgrade yet.

Finally I tried to downgrade (go to package.json and find the devDependencies) until one of them worked.

@angular-devkit/build-angular": "0.13.4"

I am sure your problem is dependencies versions but I cannot tell you which one. Give it a try downgrading.

How to use enums as flags in C++?

The C++ standard explicitly talks about this, see section "17.5.2.1.3 Bitmask types":

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf

Given this "template" you get:

enum AnimalFlags : unsigned int
{
    HasClaws = 1,
    CanFly = 2,
    EatsFish = 4,
    Endangered = 8
};

constexpr AnimalFlags operator|(AnimalFlags X, AnimalFlags Y) {
    return static_cast<AnimalFlags>(
        static_cast<unsigned int>(X) | static_cast<unsigned int>(Y));
}

AnimalFlags& operator|=(AnimalFlags& X, AnimalFlags Y) {
    X = X | Y; return X;
}

And similar for the other operators. Also note the "constexpr", it is needed if you want the compiler to be able to execute the operators compile time.

If you are using C++/CLI and want to able assign to enum members of ref classes you need to use tracking references instead:

AnimalFlags% operator|=(AnimalFlags% X, AnimalFlags Y) {
    X = X | Y; return X;
}

NOTE: This sample is not complete, see section "17.5.2.1.3 Bitmask types" for a complete set of operators.

word-wrap break-word does not work in this example

Mozilla Firefox solution

Add:

display: inline-block;

to the style of your td.

Webkit based browsers (Google Chrome, Safari, ...) solution

Add:

display: inline-block;
word-break: break-word;

to the style of your td.

Note: Mind that, as for now, break-word is not part of the standard specification for webkit; therefore, you might be interested in employing the break-all instead. This alternative value provides a undoubtedly drastic solution; however, it conforms to the standard.

Opera solution

Add:

display: inline-block;
word-break: break-word;

to the style of your td.

The previous paragraph applies to Opera in a similar way.

SQL SELECT from multiple tables

select p.pid, p.cid, c1.name,c2.name
from product p
left outer join customer1 c1 on c1.cid=p.cid
left outer join customer2 c2 on c2.cid=p.cid

Using two values for one switch case statement

The fallthrough answers by others are good ones.

However another approach would be extract methods out of the contents of your case statements and then just call the appropriate method from each case.

In the example below, both case 'text1' and case 'text4' behave the same:

switch (name) {
        case text1: {
            method1();
            break;
        }
        case text2: {
            method2();
            break;
        }
        case text3: {
            method3();
            break;
        }
        case text4: {
            method1();
            break;
        }

I personally find this style of writing case statements more maintainable and slightly more readable, especially when the methods you call have good descriptive names.

How to Store Historical Data

Supporting historical data directly within an operational system will make your application much more complex than it would otherwise be. Generally, I would not recommend doing it unless you have a hard requirement to manipulate historical versions of a record within the system.

If you look closely, most requirements for historical data fall into one of two categories:

  • Audit logging: This is better off done with audit tables. It's fairly easy to write a tool that generates scripts to create audit log tables and triggers by reading metadata from the system data dictionary. This type of tool can be used to retrofit audit logging onto most systems. You can also use this subsystem for changed data capture if you want to implement a data warehouse (see below).

  • Historical reporting: Reporting on historical state, 'as-at' positions or analytical reporting over time. It may be possible to fulfil simple historical reporting requirements by quering audit logging tables of the sort described above. If you have more complex requirements then it may be more economical to implement a data mart for the reporting than to try and integrate history directly into the operational system.

    Slowly changing dimensions are by far the simplest mechanism for tracking and querying historical state and much of the history tracking can be automated. Generic handlers aren't that hard to write. Generally, historical reporting does not have to use up-to-the-minute data, so a batched refresh mechanism is normally fine. This keeps your core and reporting system architecture relatively simple.

If your requirements fall into one of these two categories, you are probably better off not storing historical data in your operational system. Separating the historical functionality into another subsystem will probably be less effort overall and produce transactional and audit/reporting databases that work much better for their intended purpose.

How to read appSettings section in the web.config file?

Here's the easy way to get access to the web.config settings anywhere in your C# project.

 Properties.Settings.Default

Use case:

litBodyText.Text = Properties.Settings.Default.BodyText;
litFootText.Text = Properties.Settings.Default.FooterText;
litHeadText.Text = Properties.Settings.Default.HeaderText;

Web.config file:

  <applicationSettings>
    <myWebSite.Properties.Settings> 
      <setting name="BodyText" serializeAs="String">
        <value>
          &lt;h1&gt;Hello World&lt;/h1&gt;
          &lt;p&gt;
      Ipsum Lorem
          &lt;/p&gt;
        </value>
      </setting>
      <setting name="HeaderText" serializeAs="String">
      My header text
        <value />
      </setting>
      <setting name="FooterText" serializeAs="String">
      My footer text
        <value />
      </setting>
    </myWebSite.Properties.Settings>
  </applicationSettings>

No need for special routines - everything is right there already. I'm surprised that no one has this answer for the best way to read settings from your web.config file.

Python Database connection Close

According to pyodbc documentation, connections to the SQL server are not closed by default. Some database drivers do not close connections when close() is called in order to save round-trips to the server.

To close your connection when you call close() you should set pooling to False:

import pyodbc

pyodbc.pooling = False

python catch exception and continue try block

While the other answers and the accepted one are correct and should be followed in real code, just for completeness and humor, you can try the fuckitpy ( https://github.com/ajalt/fuckitpy ) module.

Your code can be changed to the following:

@fuckitpy
def myfunc():
    do_smth1()
    do_smth2()

Then calling myfunc() would call do_smth2() even if there is an exception in do_smth1())

Note: Please do not try it in any real code, it is blasphemy

What is the difference between a URI, a URL and a URN?

In order to answer this I'll lean on an answer I modified to another question. A good example of a URI is how you identify an Amazon S3 resource. Let's take:

s3://www-example-com/index.html [fig. 1]

which I created as a cached copy of

http://www.example.com/index.html [fig. 2]

in Amazon's S3-US-West-2 datacenter.

Even if StackOverflow would allow me to hyperlink to the s3:// protocol scheme, it wouldn't do you any good in locating the resource. Because it Identifies a Resource, fig. 1 is a valid URI. It is also a valid URN, because Amazon requires that the bucket (their term for the authority portion of the URI) be unique across datacenters. It is helpful in locating it, but it does not indicate the datacenter. Therefore it does not work as a URL.

So, how do URI, URL, and URN differ in this case?

NOTE: RFC 3986 defines URIs as scheme://authority/path?query#fragment

Javascript for "Add to Home Screen" on iPhone?

This is also another good Home Screen script that support iphone/ipad, Mobile Safari, Android, Blackberry touch smartphones and Playbook .

https://github.com/h5bp/mobile-boilerplate/wiki/Mobile-Bookmark-Bubble

Export Postgresql table data using pgAdmin

Just right click on a table and select "backup". The popup will show various options, including "Format", select "plain" and you get plain SQL.

pgAdmin is just using pg_dump to create the dump, also when you want plain SQL.

It uses something like this:

pg_dump --user user --password --format=plain --table=tablename --inserts --attribute-inserts etc.

Maven: add a dependency to a jar by relative path

we switched to gradle and this works much better in gradle ;). we just specify a folder we can drop jars into for temporary situations like that. We still have most of our jars defined i the typicaly dependency management section(ie. the same as maven). This is just one more dependency we define.

so basically now we can just drop any jar we want into our lib dir for temporary testing if it is not a in maven repository somewhere.

Determining the path that a yum package installed to

Not in Linux at the moment, so can't double check, but I think it's:

rpm -ql ffmpeg

That should list all the files installed as part of the ffmpeg package.

How do I print part of a rendered HTML page in JavaScript?

Try this JavaScript code:

function printout() {

    var newWindow = window.open();
    newWindow.document.write(document.getElementById("output").innerHTML);
    newWindow.print();
}

Mock functions in Go

Personally, I don't use gomock (or any mocking framework for that matter; mocking in Go is very easy without it). I would either pass a dependency to the downloader() function as a parameter, or I would make downloader() a method on a type, and the type can hold the get_page dependency:

Method 1: Pass get_page() as a parameter of downloader()

type PageGetter func(url string) string

func downloader(pageGetterFunc PageGetter) {
    // ...
    content := pageGetterFunc(BASE_URL)
    // ...
}

Main:

func get_page(url string) string { /* ... */ }

func main() {
    downloader(get_page)
}

Test:

func mock_get_page(url string) string {
    // mock your 'get_page()' function here
}

func TestDownloader(t *testing.T) {
    downloader(mock_get_page)
}

Method2: Make download() a method of a type Downloader:

If you don't want to pass the dependency as a parameter, you could also make get_page() a member of a type, and make download() a method of that type, which can then use get_page:

type PageGetter func(url string) string

type Downloader struct {
    get_page PageGetter
}

func NewDownloader(pg PageGetter) *Downloader {
    return &Downloader{get_page: pg}
}

func (d *Downloader) download() {
    //...
    content := d.get_page(BASE_URL)
    //...
}

Main:

func get_page(url string) string { /* ... */ }

func main() {
    d := NewDownloader(get_page)
    d.download()
}

Test:

func mock_get_page(url string) string {
    // mock your 'get_page()' function here
}

func TestDownloader() {
    d := NewDownloader(mock_get_page)
    d.download()
}

What's the proper value for a checked attribute of an HTML checkbox?

Strictly speaking, you should put something that makes sense - according to the spec here, the most correct version is:

<input name=name id=id type=checkbox checked=checked>

For HTML, you can also use the empty attribute syntax, checked="", or even simply checked (for stricter XHTML, this is not supported).

Effectively, however, most browsers will support just about any value between the quotes. All of the following will be checked:

<input name=name id=id type=checkbox checked>
<input name=name id=id type=checkbox checked="">
<input name=name id=id type=checkbox checked="yes">
<input name=name id=id type=checkbox checked="blue">
<input name=name id=id type=checkbox checked="false">

And only the following will be unchecked:

<input name=name id=id type=checkbox>

See also this similar question on disabled="disabled".

HTML image not showing in Gmail

Try to add title and alt properties to your image.... Gmail and some others blocks images without some attributes.. and it is also a logic to include your email to be read as spam.

JavaScript property access: dot notation vs. brackets?

An example where the dot notation fails

json = { 
   "value:":4,
   'help"':2,
   "hello'":32,
   "data+":2,
   "":'',
   "a[]":[ 
      2,
      2
   ]
};

// correct
console.log(json['value:']);
console.log(json['help"']);
console.log(json["help\""]);
console.log(json['hello\'']);
console.log(json["hello'"]);
console.log(json["data+"]);
console.log(json[""]);
console.log(json["a[]"]);

// wrong
console.log(json.value:);
console.log(json.help");
console.log(json.hello');
console.log(json.data+);
console.log(json.);
console.log(json.a[]);

The property names shouldn't interfere with the syntax rules of javascript for you to be able to access them as json.property_name

Why can't static methods be abstract in Java?

Because abstract is a keyword which is applied over Abstract methods do not specify a body. And If we talk about static keyword it belongs to class area.

How do I create/edit a Manifest file?

In Visual Studio 2010 (until 2019 and possibly future versions) you can add the manifest file to your project.

Right click your project file on the Solution Explorer, select Add, then New item (or CTRL+SHIFT+A). There you can find Application Manifest File.

The file name is app.manifest.

C# Collection was modified; enumeration operation may not execute

As others have pointed out, you are modifying a collection that you are iterating over and that's what's causing the error. The offending code is below:

foreach (KeyValuePair<int, int> kvp in rankings)
{
    .....

    if((double)(similarModules/modules.Count)>0.6)
    {
        rankings[kvp.Key] = rankings[kvp.Key] + 4;  // <--- This line is the problem
    }
    .....

What may not be obvious from the code above is where the Enumerator comes from. In a blog post from a few years back about Eric Lippert provides an example of what a foreach loop gets expanded to by the compiler. The generated code will look something like:

{
    IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator(); // <-- This
                                                       // is where the Enumerator
                                                       // comes from.
    try
    { 
        int m; // OUTSIDE THE ACTUAL LOOP in C# 4 and before, inside the loop in 5
        while(e.MoveNext())
        {
            // loop code goes here
        }
    }
    finally
    { 
      if (e != null) ((IDisposable)e).Dispose();
    }
}

If you look up the MSDN documentation for IEnumerable (which is what GetEnumerator() returns) you will see:

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Which brings us back to what the error message states and the other answers re-state, you're modifying the underlying collection.

Finding the next available id in MySQL

If this is used in conjunction for INSERTING a new record you could use something like this.

(You've stated in your comments that the id is auto incrementing and the other table needs the next ID + 1)

INSERT INTO TABLE2 (id, field1, field2, field3, etc) 
VALUES(
   SELECT (MAX(id) + 1), field1, field2, field3, etc FROM TABLE1
   WHERE condition_here_if_needed
)

This is pseudocode but you get the idea

getting the screen density programmatically in android?

I am using following code to access DPI from modules (no need for having access to a context object):

(Resources.getSystem().getDisplayMetrics().xdpi
Resources.getSystem().getDisplayMetrics().ydpi)/2

Is it possible to capture the stdout from the sh DSL command in the pipeline

A short version would be:

echo sh(script: 'ls -al', returnStdout: true).result

Proxy Basic Authentication in C#: HTTP 407 error

I had a similar problem due to a password protected proxy server and couldn't find much in the way of information out there - hopefully this helps someone. I wanted to pick up the credentials as used by the customer's browser. However, the CredentialCache.DefaultCredentials and DefaultNetworkCredentials aren't working when the proxy has it's own username and password even though I had entered these details to ensure thatInternet explorer and Edge had access.

The solution for me in the end was to use a nuget package called "CredentialManagement.Standard" and the below code:

using WebClient webClient = new WebClient();    
var request = WebRequest.Create("http://google.co.uk");
var proxy = request.Proxy.GetProxy(new Uri("http://google.co.uk"));

var cmgr = new CredentialManagement.Credential() { Target = proxy.Host };
if (cmgr.Load())
{
    var credentials = new NetworkCredential(cmgr.Username, cmgr.Password);
    webClient.Proxy.Credentials = credentials;
    webClient.Credentials = credentials;
}

This grabs credentials from 'Credentials Manager' - which can be found via Windows - click Start then search for 'Credentials Manager'. Credentials for the proxy that were manually entered when prompted by the browser will be in the Windows Credentials section.

Gradle failed to resolve library in Android Studio

i had the same problem, i added the following lines in build.gradle

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }

        maven {
            url 'http://dl.bintray.com/dev-fingerlinks/maven'
        }
        mavenCentral()
    }
}

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

I ran into this myself when I wanted to make a thor command under Windows.

To avoid having that message output everytime I ran my thor application I temporarily muted warnings while loading thor:

begin
  original_verbose = $VERBOSE
  $VERBOSE = nil
  require "thor"
ensure
  $VERBOSE = original_verbose
end

That saved me from having to edit third party source files.

Launch a shell command with in a python script, wait for the termination and return to the script

subprocess: The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

http://docs.python.org/library/subprocess.html

Usage:

import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode

Java decimal formatting using String.format?

NumberFormat and DecimalFormat are definitely what you want. Also, note the NumberFormat.setRoundingMode() method. You can use it to control how rounding or truncation is applied during formatting.

jquery: change the URL address without redirecting?

NOTE: history.pushState() is now supported - see other answers.

You cannot change the whole url without redirecting, what you can do instead is change the hash.

The hash is the part of the url that goes after the # symbol. That was initially intended to direct you (locally) to sections of your HTML document, but you can read and modify it through javascript to use it somewhat like a global variable.


If applied well, this technique is useful in two ways:

  1. the browser history will remember each different step you took (since the url+hash changed)
  2. you can have an address which links not only to a particular html document, but also gives your javascript a clue about what to do. That means you end up pointing to a state inside your web app.

To change the hash you can do:

document.location.hash = "show_picture";

To watch for hash changes you have to do something like:

window.onhashchange = function(){
    var what_to_do = document.location.hash;    
    if (what_to_do=="#show_picture")
        show_picture();
}

Of course the hash is just a string, so you can do pretty much what you like with it. For example you can put a whole object there if you use JSON to stringify it.

There are very good JQuery libraries to do advanced things with that.

Using Address Instead Of Longitude And Latitude With Google Maps API

Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.

Would this be what you are looking for: Contains sample code
https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests

"Failed to install the following Android SDK packages as some licences have not been accepted" error

I tried many solutions but didn't work for me. The below solution works for me.

locate the sdkmanager file in android SDK.

In my case : ~/Android/Sdk/tools/bin

go to that path : cd ~/Android/Sdk/tools/bin

Accept licenses manually : ./sdkmanager --licenses Enter Yes or y

How to select rows from a DataFrame based on column values

Faster results can be achieved using numpy.where.

For example, with unubtu's setup -

In [76]: df.iloc[np.where(df.A.values=='foo')]
Out[76]: 
     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

Timing comparisons:

In [68]: %timeit df.iloc[np.where(df.A.values=='foo')]  # fastest
1000 loops, best of 3: 380 µs per loop

In [69]: %timeit df.loc[df['A'] == 'foo']
1000 loops, best of 3: 745 µs per loop

In [71]: %timeit df.loc[df['A'].isin(['foo'])]
1000 loops, best of 3: 562 µs per loop

In [72]: %timeit df[df.A=='foo']
1000 loops, best of 3: 796 µs per loop

In [74]: %timeit df.query('(A=="foo")')  # slowest
1000 loops, best of 3: 1.71 ms per loop

How to create a numpy array of arbitrary length strings?

You could use the object data type:

>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)

Transform char array into String

Visit https://www.arduino.cc/en/Reference/StringConstructor to solve the problem easily.

This worked for me:

char yyy[6];

String xxx;

yyy[0]='h';

yyy[1]='e';

yyy[2]='l';

yyy[3]='l';

yyy[4]='o';

yyy[5]='\0';

xxx=String(yyy);

How to Generate a random number of fixed length using JavaScript?

I would go with this solution:

Math.floor(Math.random() * 899999 + 100000)

Basic example for sharing text or image with UIActivityViewController in Swift

I've used the implementation above and just now I came to know that it doesn't work on iPad running iOS 13. I had to add these lines before present() call in order to make it work

//avoiding to crash on iPad
if let popoverController = activityViewController.popoverPresentationController {
     popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
     popoverController.sourceView = self.view
     popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}

That's how it works for me

func shareData(_ dataToShare: [Any]){

        let activityViewController = UIActivityViewController(activityItems: dataToShare, applicationActivities: nil)

        //exclude some activity types from the list (optional)
        //activityViewController.excludedActivityTypes = [
            //UIActivity.ActivityType.postToFacebook
        //]

        //avoiding to crash on iPad
        if let popoverController = activityViewController.popoverPresentationController {
            popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
            popoverController.sourceView = self.view
            popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
        }

        self.present(activityViewController, animated: true, completion: nil)
    }

How do I print debug messages in the Google Chrome JavaScript Console?

Personally I use this, which is similar to tarek11011's:

// Use a less-common namespace than just 'log'
function myLog(msg)
{
    // Attempt to send a message to the console
    try
    {
        console.log(msg);
    }
    // Fail gracefully if it does not exist
    catch(e){}
}

The main point is that it's a good idea to at least have some practice of logging other than just sticking console.log() right into your JavaScript code, because if you forget about it, and it's on a production site, it can potentially break all of the JavaScript code for that page.

Run C++ in command prompt - Windows

  1. Download MinGW form : https://sourceforge.net/projects/mingw-w64/
  2. use notepad++ to write the C++ source code.
  3. using command line change the directory/folder where the source code is saved(using notepad++)
  4. compile: g++ file_name.cpp -o file_name.exe
  5. run the executable: file_name.exe

Google Chrome redirecting localhost to https

Another option would be to use something like https://github.com/rchampourlier/tunnelss

Sure it added another dependency / setup, but it also enables testing of https in dev, which could be nice.

I use RVM however to get tunnelss working I had to use sudo gem install tunnelss and sudo tunnelss

How to call javascript from a href?

JavaScript code is usually called from the onclick event of a link. For example, you could instead do:

In Head Section of HTML Document

<script type='text/javascript'>
function myFunction(){
//...script code
}
</script>

In Body of HTML Document

<a href="#" id="mylink" onclick="myFunction(); return false">Call JavaScript </a>

Alternatively, you can also attach your function to the link using the links' ID, and HTML DOM or a framework like JQuery.

For example:

In Head Section of HTML Document

<script type='text/javascript'>
document.getElementById("mylink").onclick = function myFunction(){ ...script code};
</script>

In Body of HTML Document

<a href="#" id="mylink">Call JavaScript </a>

Detect WebBrowser complete page loading

If you're using WPF there is a LoadCompleted event.

If it's Windows.Forms, the DocumentCompleted event should be the correct one. If the page you're loading has frames, your WebBrowser control will fire the DocumentCompleted event for each frame (see here for more details). I would suggest checking the IsBusy property each time the event is fired and if it is false then your page is fully done loading.

Difference between Python's Generators and Iterators

Adding an answer because none of the existing answers specifically address the confusion in the official literature.

Generator functions are ordinary functions defined using yield instead of return. When called, a generator function returns a generator object, which is a kind of iterator - it has a next() method. When you call next(), the next value yielded by the generator function is returned.

Either the function or the object may be called the "generator" depending on which Python source document you read. The Python glossary says generator functions, while the Python wiki implies generator objects. The Python tutorial remarkably manages to imply both usages in the space of three sentences:

Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed).

The first two sentences identify generators with generator functions, while the third sentence identifies them with generator objects.

Despite all this confusion, one can seek out the Python language reference for the clear and final word:

The yield expression is only used when defining a generator function, and can only be used in the body of a function definition. Using a yield expression in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of a generator function.

So, in formal and precise usage, "generator" unqualified means generator object, not generator function.

The above references are for Python 2 but Python 3 language reference says the same thing. However, the Python 3 glossary states that

generator ... Usually refers to a generator function, but may refer to a generator iterator in some contexts. In cases where the intended meaning isn’t clear, using the full terms avoids ambiguity.

Get difference between two lists

Try this:

temp3 = set(temp1) - set(temp2)

How to switch between python 2.7 to python 3 from command line?

For Windows 7, I just rename the python.exe from the Python 3 folder to python3.exe and add the path into the environment variables. Using that, I can execute python test_script.py and the script runs with Python 2.7 and when I do python3 test_script.py, it runs the script in Python 3.

To add Python 3 to the environment variables, follow these steps -

  1. Right Click on My Computer and go to Properties.
  2. Go to Advanced System Settings.
  3. Click on Environment Variables and edit PATH and add the path to your Python 3 installation directory.

For example,

enter image description here

Output data from all columns in a dataframe in pandas

you can use sequence slicing syntax i.e

paramdata[:5] # first five records
paramdata[-5:] # last five records
paramdata[:] # all records

sometimes the dataframe might not fit in the screen buffer in which case you are probably better off either printing a small subset or exporting it to something else, plot or (csv again)

Java: random long number in 0 <= x < n range

How about this:

public static long nextLong(@NonNull Random r, long min, long max) {
    if (min > max)
        throw new IllegalArgumentException("min>max");
    if (min == max)
        return min;
    long n = r.nextLong();
    //abs (use instead of Math.abs, which might return min value) :
    n = n == Long.MIN_VALUE ? 0 : n < 0 ? -n : n;
    //limit to range:
    n = n % (max - min);
    return min + n;
}

?

How to add item to the beginning of List<T>?

Use the Insert method:

ti.Insert(0, initialItem);

Avoid line break between html elements

If the <i> tag isn't displayed as a block and causing the probelm then this should work:

<td style="white-space:nowrap;"><i class="flag-bfh-ES"></i>&nbsp;+34&nbsp;666&nbsp;66&nbsp;66&nbsp;66</td>

Display loading image while post with ajax

make sure to change in ajax call

async: true,
type: "GET",
dataType: "html",

How to generate a random String in Java

You can also use UUID class from java.util package, which returns random uuid of 32bit characters String.

java.util.UUID.randomUUID().toString()

http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html

Package opencv was not found in the pkg-config search path

it seems that the ubuntu community has completed the documentation on installing openCV,

so all you have to do now is to download the installation script from here and execute it.

don't forget to make it executable:

chmod +x opencv_latest.sh

then

./opencv_latest.sh

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.

(The strange thing was that all ssh-* commands were valid, (bash could execute as program) but the openssh package wasn't installed.)

Python pandas insert list into a cell

df3.set_value(1, 'B', abc) works for any dataframe. Take care of the data type of column 'B'. Eg. a list can not be inserted into a float column, at that case df['B'] = df['B'].astype(object) can help.

Python datetime strptime() and strftime(): how to preserve the timezone information

Part of the problem here is that the strings usually used to represent timezones are not actually unique. "EST" only means "America/New_York" to people in North America. This is a limitation in the C time API, and the Python solution is… to add full tz features in some future version any day now, if anyone is willing to write the PEP.

You can format and parse a timezone as an offset, but that loses daylight savings/summer time information (e.g., you can't distinguish "America/Phoenix" from "America/Los_Angeles" in the summer). You can format a timezone as a 3-letter abbreviation, but you can't parse it back from that.

If you want something that's fuzzy and ambiguous but usually what you want, you need a third-party library like dateutil.

If you want something that's actually unambiguous, just append the actual tz name to the local datetime string yourself, and split it back off on the other end:

d = datetime.datetime.now(pytz.timezone("America/New_York"))
dtz_string = d.strftime(fmt) + ' ' + "America/New_York"

d_string, tz_string = dtz_string.rsplit(' ', 1)
d2 = datetime.datetime.strptime(d_string, fmt)
tz2 = pytz.timezone(tz_string)

print dtz_string 
print d2.strftime(fmt) + ' ' + tz_string

Or… halfway between those two, you're already using the pytz library, which can parse (according to some arbitrary but well-defined disambiguation rules) formats like "EST". So, if you really want to, you can leave the %Z in on the formatting side, then pull it off and parse it with pytz.timezone() before passing the rest to strptime.

Git 'fatal: Unable to write new index file'

IF YOU GET THIS DURING A REBASE:

This is most likely caused by some software locking the index file of your repo, such as backup software, anti-viruses, IDEs or other git clients.

In most cases the lock is just for a brief moment and so it just happens out of bad-timing and bad luck.

However, git rebase --continue will complain about the next command being an empty commit:

The previous cherry-pick is now empty, possibly due to conflict resolution.
If you wish to commit it anyway, use:

    git commit --allow-empty

To fix this, just run git reset and try git rebase --continue again.

cannot find module "lodash"

Reinstall 'browser-sync' :

rm -rf node_modules/browser-sync
npm install browser-sync --save

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

function printr($data)
{
   echo "<pre>";
      print_r($data);
   echo "</pre>";
}

And call your function on the page you need, don't forget to include the file where you put your function in for example: functions.php

include('functions.php');

printr($data);

How to get all options of a select using jQuery?

$("#id option").each(function()
{
    $(this).prop('selected', true);
});

Although, the CORRECT way is to set the DOM property of the element, like so:

$("#id option").each(function(){
    $(this).attr('selected', true);
});

Django - makemigrations - No changes detected

I forgot to put correct arguments:

class LineInOffice(models.Model):   # here
    addressOfOffice = models.CharField("???????? ???",max_length= 200)   #and here
    ...

in models.py and then it started to drop that annoying

No changes detected in app 'myApp '

how to import csv data into django models

The Python csv library can do your parsing and your code can translate them into Products().

How to update and order by using ms sql

I have to offer this as a better approach - you don't always have the luxury of an identity field:

UPDATE m
SET [status]=10
FROM (
  Select TOP (10) *
  FROM messages
  WHERE [status]=0
  ORDER BY [priority] DESC
) m

You can also make the sub-query as complicated as you want - joining multiple tables, etc...

Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages table. It can be used to update the top N rows from any table, even if that table has no unique key at all.

How can I encode a string to Base64 in Swift?

Swift

import Foundation

extension String {

    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else {
            return nil
        }

        return String(data: data, encoding: .utf8)
    }

    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    }

}

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

I was using spring-web version 4.3.7

Changing it to a working 4.1.7 immediately solved it.

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.1.7.RELEASE</version>
    </dependency>

Skip first entry in for loop in python?

If cars is a sequence you can just do

for car in cars[1:-1]:
    pass

Fit Image in ImageButton in Android

It worked well in my case. First, you download an image and rename it as iconimage, locates it in the drawable folder. You can change the size by setting android:layout_width or android:layout_height. Finally, we have

 <ImageButton
        android:id="@+id/answercall"
        android:layout_width="120dp"
        android:layout_height="80dp"
        android:src="@drawable/iconimage"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:scaleType="fitCenter" />

How to format Joda-Time DateTime to only mm/dd/yyyy?

UPDATED:

You can: create a constant:

private static final DateTimeFormatter DATE_FORMATTER_YYYY_MM_DD =
          DateTimeFormat.forPattern("yyyy-MM-dd"); // or whatever pattern that you need.

This DateTimeFormat is importing from: (be careful with that)

import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter;

Parse the Date with:

DateTime.parse(dateTimeScheduled.toString(), DATE_FORMATTER_YYYY_MM_DD);

Before:
DateTime.parse("201711201515",DateTimeFormat.forPattern("yyyyMMddHHmm")).toString("yyyyMMdd");

if want datetime:

DateTime.parse("201711201515", DateTimeFormat.forPattern("yyyyMMddHHmm")).withTimeAtStartOfDay();

Settings to Windows Firewall to allow Docker for Windows to share drive

Even after ensuring that the inbound firewall rule is set up properly and even after uninstalling and reinstalling the File and Printing Sharing Service it didn't work for me.

Solution: on top of that I also had to do a third thing. I had to deactivate the checkbox Prevent incoming connections when on a public network in the specific firewall settings for public networks. After doing that it started working for me as well. See screenshots attached at the end of this message.

Don't know how long this option has been there already. I'm currently working on Win 10 Pro 1709 16299.402.


1. Open specific firewall settings for public networks Open specific firewall settings for public networks

2. Uncheck this checkbox Uncheck this checkbox

List of phone number country codes

There is an Excel file with regexps here. You can easily "convert" it to XML and you will be able to determine country by the full phone number.

UPD: The file that I referenced 4 years ago is no longer accessible. I would recommend using Google's libphonenumber.

The answer to Extract code country from phone number [libphonenumber] will show you the proper way to receive country code from a phone number.

What's the best way to dedupe a table?

SELECT DISTINCT <insert all columns but the PK here> FROM foo. Create a temp table using that query (the syntax varies by RDBMS but there's typically a SELECT … INTO or CREATE TABLE AS pattern available), then blow away the old table and pump the data from the temp table back into it.

JavaScript chop/slice/trim off last character in string

Performance

Today 2020.05.13 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6.

Conclusions

  • the slice(0,-1)(D) is fast or fastest solution for short and long strings and it is recommended as fast cross-browser solution
  • solutions based on substring (C) and substr(E) are fast
  • solutions based on regular expressions (A,B) are slow/medium fast
  • solutions B, F and G are slow for long strings
  • solution F is slowest for short strings, G is slowest for long strings

enter image description here

Details

I perform two tests for solutions A, B, C, D, E(ext), F, G(my)

  • for 8-char short string (from OP question) - you can run it HERE
  • for 1M long string - you can run it HERE

Solutions are presented in below snippet

_x000D_
_x000D_
function A(str) {
  return str.replace(/.$/, '');
}

function B(str) {
  return str.match(/(.*).$/)[1];
}

function C(str) {
  return str.substring(0, str.length - 1);
}

function D(str) {
  return str.slice(0, -1); 
}

function E(str) {
  return str.substr(0, str.length - 1);
}

function F(str) {
  let s= str.split("");
  s.pop();
  return s.join("");
}

function G(str) {
  let s='';
  for(let i=0; i<str.length-1; i++) s+=str[i];
  return s;
 }



// ---------
// TEST
// ---------

let log = (f)=>console.log(`${f.name}: ${f("12345.00")}`);

[A,B,C,D,E,F,G].map(f=>log(f));
_x000D_
This snippet only presents soutions
_x000D_
_x000D_
_x000D_

Here are example results for Chrome for short string

enter image description here

How to use JUnit to test asynchronous processes

One method I've found pretty useful for testing asynchronous methods is injecting an Executor instance in the object-to-test's constructor. In production, the executor instance is configured to run asynchronously while in test it can be mocked to run synchronously.

So suppose I'm trying to test the asynchronous method Foo#doAsync(Callback c),

class Foo {
  private final Executor executor;
  public Foo(Executor executor) {
    this.executor = executor;
  }

  public void doAsync(Callback c) {
    executor.execute(new Runnable() {
      @Override public void run() {
        // Do stuff here
        c.onComplete(data);
      }
    });
  }
}

In production, I would construct Foo with an Executors.newSingleThreadExecutor() Executor instance while in test I would probably construct it with a synchronous executor that does the following --

class SynchronousExecutor implements Executor {
  @Override public void execute(Runnable r) {
    r.run();
  }
}

Now my JUnit test of the asynchronous method is pretty clean --

@Test public void testDoAsync() {
  Executor executor = new SynchronousExecutor();
  Foo objectToTest = new Foo(executor);

  Callback callback = mock(Callback.class);
  objectToTest.doAsync(callback);

  // Verify that Callback#onComplete was called using Mockito.
  verify(callback).onComplete(any(Data.class));

  // Assert that we got back the data that we expected.
  assertEquals(expectedData, callback.getData());
}

How to compare two columns in Excel and if match, then copy the cell next to it

It might be easier with vlookup. Try this:

=IFERROR(VLOOKUP(D2,G:H,2,0),"")

The IFERROR() is for no matches, so that it throws "" in such cases.

VLOOKUP's first parameter is the value to 'look for' in the reference table, which is column G and H.

VLOOKUP will thus look for D2 in column G and return the value in the column index 2 (column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.

The last parameter is 0 (or equivalently FALSE) to mean an exact match. That's what you need as opposed to approximate match.

Create a new line in Java's FileWriter

Try:

String.format("%n");

See this question for more details.

Importing the private-key/public-certificate pair in the Java KeyStore

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

Can I use library that used android support with Androidx projects.

API 29.+ usage AndroidX libraries. If you are using API 29.+, then you cannot remove these. If you want to remove AndroidX, then you need to remove the entire 29.+ API from your SDK:

SDK Settings

This will work fine.

How to use sbt from behind proxy?

I found an item on the FAQ section of Lightbend Activator useful. I am using Activator, which in turn uses SBT, so not sure if this helps users with just SBT, but if you use Activator, like me, and are behind a proxy, follow the instructions in the "Behind A Proxy" section of the FAQ:

https://www.lightbend.com/activator/docs

Just in case the content disappears, here's a copy-paste:

When running activator behind a proxy, some additional configuration is needed. First, open the activator configuration file, found in your user home directory under ~/.activator/activatorconfig.txt. Note that this file may not exist. Add the following lines (one option per line):

-Dhttp.proxyHost=PUT YOUR PROXY HOST HERE
-Dhttp.proxyPort=PUT YOUR PROXY PORT HERE
-Dhttp.nonProxyHosts="localhost|127.0.0.1"
-Dhttps.proxyHost=PUT YOUR HTTPS PROXY HOST HERE
-Dhttps.proxyPort=PUT YOUR HTTPS PROXY PORT HERE
-Dhttps.nonProxyHosts="localhost|127.0.0.1"

How to assign a heredoc value to a variable in Bash?

Thanks to dimo414's answer, this shows how his great solution works, and shows that you can have quotes and variables in the text easily as well:

example output

$ ./test.sh

The text from the example function is:
  Welcome dev: Would you "like" to know how many 'files' there are in /tmp?

  There are "      38" files in /tmp, according to the "wc" command

test.sh

#!/bin/bash

function text1()
{
  COUNT=$(\ls /tmp | wc -l)
cat <<EOF

  $1 Would you "like" to know how many 'files' there are in /tmp?

  There are "$COUNT" files in /tmp, according to the "wc" command

EOF
}

function main()
{
  OUT=$(text1 "Welcome dev:")
  echo "The text from the example function is: $OUT"
}

main

Google Play app description formatting

Title, Short Description and Developer Name

  • HTML formatting is not supported in these fields, but you can include UTF-8 symbols and Emoji: ??

Full Description and What’s New:

  • For the Long Description and What’s New Section, there is a wider variety of HTML codes you can apply to format and structure your text. However, they will look slightly different in Google Play Store app and web.
  • Here is a table with codes that you can use for formatting Description and What’s New fields for your app on Google Play (originally appeared on ASO Stack blog):

enter image description here

Also you can refer this..

https://thetool.io/2020/html-emoji-google-play

How to align entire html body to the center?

If I have one thing that I love to share with respect to CSS, it's MY FAVE WAY OF CENTERING THINGS ALONG BOTH AXES!!!

Advantages of this method:

  1. Full compatibility with browsers that people actually use
  2. No tables required
  3. Highly reusable for centering any other elements inside their parent
  4. Accomodates parents and children with dynamic (changing) dimensions!

I always do this by using 2 classes: One to specify the parent element, whose content will be centered (.centered-wrapper), and the 2nd one to specify which child of the parent is centered (.centered-content). This 2nd class is useful in the case where the parent has multiple children, but only 1 needs to be centered). In this case, body will be the .centered-wrapper, and an inner div will be .centered-content.

<html>
    <head>...</head>
    <body class="centered-wrapper">
        <div class="centered-content">...</div>
    </body>
</html>

The idea for centering will now be to make .centered-content an inline-block. This will easily facilitate horizontal centering, through text-align: center;, and also allows for vertical centering as you shall see.

.centered-wrapper {
    position: relative;
    text-align: center;
}
.centered-wrapper:before {
    content: "";
    position: relative;
    display: inline-block;
    width: 0; height: 100%;
    vertical-align: middle;
}
.centered-content {
    display: inline-block;
    vertical-align: middle;
}

This gives you 2 really reusable classes for centering any child inside of any parent! Just add the .centered-wrapper and .centered-content classes.

So, what's up with that :before element? It facilitates vertical-align: middle; and is necessary because vertical alignment isn't relative to the height of the parent - vertical alignment is relative to the height of the tallest sibling!!!. Therefore, by ensuring that there is a sibling whose height is the parent's height (100% height, 0 width to make it invisible), we know that vertical alignment will be with respect to the parent's height.

One last thing: You need to ensure that your html and body tags are the size of the window so that centering to them is the same as centering to the browser!

html, body {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}

Fiddle: https://jsfiddle.net/gershy/g121g72a/

How do I change Bootstrap 3 column order on mobile layout?

This is quite easy with jQuery using insertAfter() or insertBefore():

<div class="left">content</div>
<div class="right">sidebar</div>

_x000D_
_x000D_
<script>
$('.right').insertBefore('left');
</script>
_x000D_
_x000D_
_x000D_

If you want to to set o condition for mobile devices you can make it like this:

_x000D_
_x000D_
<script>
  var $iW = $(window).innerWidth();
  if ($iW < 992){
     $('.right').insertBefore('.left');
  }else{
     $('.right').insertAfter('.left');
  }
</script>
_x000D_
_x000D_
_x000D_

example https://jsfiddle.net/w9n27k23/

phpmyadmin "no data received to import" error, how to fix?

I had the same problem on Windows. Turns out it was caused by the temporary directory PHP uses for uploads. By default this is C:\Windows\Temp, which is not writable for PHP.

In php.ini, add:

upload_tmp_dir = C:\inetpub\temp

Make sure to remove any other upload_tmp_dir settings. Set permissions on C:\inetpub\temp so IUSR and IIS_IUSRS have write permission. Restart the web server and you should be fine.

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Using either a float or a double value in a C expression will result in a value that is a double anyway, so printf can't tell the difference. Whereas a pointer to a double has to be explicitly signalled to scanf as distinct from a pointer to float, because what the pointer points to is what matters.

How to create a JavaScript callback for knowing when an image is loaded?

.complete + callback

This is a standards compliant method without extra dependencies, and waits no longer than necessary:

var img = document.querySelector('img')

function loaded() {
  alert('loaded')
}

if (img.complete) {
  loaded()
} else {
  img.addEventListener('load', loaded)
  img.addEventListener('error', function() {
      alert('error')
  })
}

Source: http://www.html5rocks.com/en/tutorials/es6/promises/

Creating a textarea with auto-resize

For those who want the textarea to be auto resized on both width and height:

HTML:

<textarea class='textbox'></textarea>
<div>
  <span class='tmp_textbox'></span>
</div>

CSS:

.textbox,
.tmp_textbox {
  font-family: 'Arial';
  font-size: 12px;
  resize: none;
  overflow:hidden;
}

.tmp_textbox {
  display: none;
}

jQuery:

$(function(){
  //alert($('.textbox').css('padding'))
  $('.textbox').on('keyup change', checkSize)
  $('.textbox').trigger('keyup')

  function checkSize(){
    var str = $(this).val().replace(/\r?\n/g, '<br/>');
    $('.tmp_textbox').html( str )
    console.log($(this).val())

    var strArr = str.split('<br/>')
    var row = strArr.length
    $('.textbox').attr('rows', row)
    $('.textbox').width( $('.tmp_textbox').width() + parseInt($('.textbox').css('padding')) * 2 + 10 )
  }
})

Codepen:

http://codepen.io/anon/pen/yNpvJJ

Cheers,

INSERT INTO...SELECT for all MySQL columns

The correct syntax is described in the manual. Try this:

INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';

If the id columns is an auto-increment column and you already have some data in both tables then in some cases you may want to omit the id from the column list and generate new ids instead to avoid insert an id that already exists in the original table. If your target table is empty then this won't be an issue.

java Arrays.sort 2d array

import java.util.*;

public class Arrays2
{
    public static void main(String[] args)
    {
        int small, row = 0, col = 0, z;
        int[][] array = new int[5][5];

        Random rand = new Random();
        for(int i = 0; i < array.length; i++)
        {
            for(int j = 0; j < array[i].length; j++)
            {
                array[i][j] = rand.nextInt(100);
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }

        System.out.println("\n");


        for(int k = 0; k < array.length; k++)
        {
            for(int p = 0; p < array[k].length; p++)
            {
                small = array[k][p];
                for(int i = k; i < array.length; i++)
                {
                    if(i == k)
                        z = p + 1;
                    else
                        z = 0;
                    for(;z < array[i].length; z++)
                    {
                        if(array[i][z] <= small)
                        {
                            small = array[i][z];
                            row = i;
                            col = z;
                        }
                    }
                }
            array[row][col] = array[k][p];
            array[k][p] = small;
            System.out.print(array[k][p] + " ");
            }
            System.out.println();
        }
    }
}

Good Luck

Can I export a variable to the environment from a bash script without sourcing it?

Found an interesting and neat way to export environment variables from a file:

in env.vars:

foo=test

test script:

eval `cat env.vars`
echo $foo         # => test
sh -c 'echo $foo' # => 

export eval `cat env.vars`
echo $foo         # => test
sh -c 'echo $foo' # => test

# a better one. "--" stops processing options, 
# key=value list given as params
export -- `cat env.vars`
echo $foo         # => test
sh -c 'echo $foo' # => test

Which versions of SSL/TLS does System.Net.WebRequest support?

When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use this. You can see more details on how this works here:

http://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake

If the server doesn't support TLS it will fallback to SSL, therefore it could potentially fallback to SSL3. You can see all of the versions that .NET 4.5 supports here:

http://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx

In order to prevent your application being vulnerable to POODLE, you can disable SSL3 on the machine that your application is running on by following this explanation:

https://serverfault.com/questions/637207/on-iis-how-do-i-patch-the-ssl-3-0-poodle-vulnerability-cve-2014-3566

Build query string for System.Net.HttpClient get

TL;DR: do not use accepted version as It's completely broken in relation to handling unicode characters, and never use internal API

I've actually found weird double encoding issue with the accepted solution:

So, If you're dealing with characters which need to be encoded, accepted solution leads to double encoding:

  • query parameters are auto encoded by using NameValueCollection indexer (and this uses UrlEncodeUnicode, not regular expected UrlEncode(!))
  • Then, when you call uriBuilder.Uri it creates new Uri using constructor which does encoding one more time (normal url encoding)
  • That cannot be avoided by doing uriBuilder.ToString() (even though this returns correct Uri which IMO is at least inconsistency, maybe a bug, but that's another question) and then using HttpClient method accepting string - client still creates Uri out of your passed string like this: new Uri(uri, UriKind.RelativeOrAbsolute)

Small, but full repro:

var builder = new UriBuilder
{
    Scheme = Uri.UriSchemeHttps,
    Port = -1,
    Host = "127.0.0.1",
    Path = "app"
};

NameValueCollection query = HttpUtility.ParseQueryString(builder.Query);

query["cyrillic"] = "????????";

builder.Query = query.ToString();
Console.WriteLine(builder.Query); //query with cyrillic stuff UrlEncodedUnicode, and that's not what you want

var uri = builder.Uri; // creates new Uri using constructor which does encode and messes cyrillic parameter even more
Console.WriteLine(uri);

// this is still wrong:
var stringUri = builder.ToString(); // returns more 'correct' (still `UrlEncodedUnicode`, but at least once, not twice)
new HttpClient().GetStringAsync(stringUri); // this creates Uri object out of 'stringUri' so we still end up sending double encoded cyrillic text to server. Ouch!

Output:

?cyrillic=%u043a%u0438%u0440%u0438%u043b%u0438%u0446%u044f

https://127.0.0.1/app?cyrillic=%25u043a%25u0438%25u0440%25u0438%25u043b%25u0438%25u0446%25u044f

As you may see, no matter if you do uribuilder.ToString() + httpClient.GetStringAsync(string) or uriBuilder.Uri + httpClient.GetStringAsync(Uri) you end up sending double encoded parameter

Fixed example could be:

var uri = new Uri(builder.ToString(), dontEscape: true);
new HttpClient().GetStringAsync(uri);

But this uses obsolete Uri constructor

P.S on my latest .NET on Windows Server, Uri constructor with bool doc comment says "obsolete, dontEscape is always false", but actually works as expected (skips escaping)

So It looks like another bug...

And even this is plain wrong - it send UrlEncodedUnicode to server, not just UrlEncoded what server expects

Update: one more thing is, NameValueCollection actually does UrlEncodeUnicode, which is not supposed to be used anymore and is incompatible with regular url.encode/decode (see NameValueCollection to URL Query?).

So the bottom line is: never use this hack with NameValueCollection query = HttpUtility.ParseQueryString(builder.Query); as it will mess your unicode query parameters. Just build query manually and assign it to UriBuilder.Query which will do necessary encoding and then get Uri using UriBuilder.Uri.

Prime example of hurting yourself by using code which is not supposed to be used like this

How to push both key and value into an Array in Jquery

This code

var title = news.title;
var link = news.link;
arr.push({title : link});

is not doing what you think it does. What gets pushed is a new object with a single member named "title" and with link as the value ... the actual title value is not used. To save an object with two fields you have to do something like

arr.push({title:title, link:link});

or with recent Javascript advances you can use the shortcut

arr.push({title, link}); // Note: comma "," and not colon ":"

If instead you want the key of the object to be the content of the variable title you can use

arr.push({[title]: link}); // Note that title has been wrapped in brackets

What is the best way to ensure only one instance of a Bash script is running?

from with your script:

ps -ef | grep $0 | grep $(whoami)

Locking pattern for proper use of .NET MemoryCache

This is my 2nd iteration of the code. Because MemoryCache is thread safe you don't need to lock on the initial read, you can just read and if the cache returns null then do the lock check to see if you need to create the string. It greatly simplifies the code.

const string CacheKey = "CacheKey";
static readonly object cacheLock = new object();
private static string GetCachedData()
{

    //Returns null if the string does not exist, prevents a race condition where the cache invalidates between the contains check and the retreival.
    var cachedString = MemoryCache.Default.Get(CacheKey, null) as string;

    if (cachedString != null)
    {
        return cachedString;
    }

    lock (cacheLock)
    {
        //Check to see if anyone wrote to the cache while we where waiting our turn to write the new value.
        cachedString = MemoryCache.Default.Get(CacheKey, null) as string;

        if (cachedString != null)
        {
            return cachedString;
        }

        //The value still did not exist so we now write it in to the cache.
        var expensiveString = SomeHeavyAndExpensiveCalculation();
        CacheItemPolicy cip = new CacheItemPolicy()
                              {
                                  AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
                              };
        MemoryCache.Default.Set(CacheKey, expensiveString, cip);
        return expensiveString;
    }
}

EDIT: The below code is unnecessary but I wanted to leave it to show the original method. It may be useful to future visitors who are using a different collection that has thread safe reads but non-thread safe writes (almost all of classes under the System.Collections namespace is like that).

Here is how I would do it using ReaderWriterLockSlim to protect access. You need to do a kind of "Double Checked Locking" to see if anyone else created the cached item while we where waiting to to take the lock.

const string CacheKey = "CacheKey";
static readonly ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
static string GetCachedData()
{
    //First we do a read lock to see if it already exists, this allows multiple readers at the same time.
    cacheLock.EnterReadLock();
    try
    {
        //Returns null if the string does not exist, prevents a race condition where the cache invalidates between the contains check and the retreival.
        var cachedString = MemoryCache.Default.Get(CacheKey, null) as string;

        if (cachedString != null)
        {
            return cachedString;
        }
    }
    finally
    {
        cacheLock.ExitReadLock();
    }

    //Only one UpgradeableReadLock can exist at one time, but it can co-exist with many ReadLocks
    cacheLock.EnterUpgradeableReadLock();
    try
    {
        //We need to check again to see if the string was created while we where waiting to enter the EnterUpgradeableReadLock
        var cachedString = MemoryCache.Default.Get(CacheKey, null) as string;

        if (cachedString != null)
        {
            return cachedString;
        }

        //The entry still does not exist so we need to create it and enter the write lock
        var expensiveString = SomeHeavyAndExpensiveCalculation();
        cacheLock.EnterWriteLock(); //This will block till all the Readers flush.
        try
        {
            CacheItemPolicy cip = new CacheItemPolicy()
            {
                AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
            };
            MemoryCache.Default.Set(CacheKey, expensiveString, cip);
            return expensiveString;
        }
        finally 
        {
            cacheLock.ExitWriteLock();
        }
    }
    finally
    {
        cacheLock.ExitUpgradeableReadLock();
    }
}

Python, print all floats to 2 decimal places in output

Format String Syntax.

https://docs.python.org/3/library/string.html#formatstrings

from math import pi
var1, var2, var3, var4 = pi, pi*2, pi*3, pi*4
'{:0.2f}, kg={:0.2f}, lb={:0.2f}, gal={:0.2f}'.format(var1, var2, var3, var4)

The output would be:

'3.14, kg=6.28, lb=9.42, gal=12.57'

Java SSL: how to disable hostname verification

In case you're using apache's http-client 4:

SSLConnectionSocketFactory sslConnectionSocketFactory = 
    new SSLConnectionSocketFactory(sslContext,
             new String[] { "TLSv1.2" }, null, new HostnameVerifier() {
                    public boolean verify(String arg0, SSLSession arg1) {
                            return true;
            }
      });

Check if value exists in dataTable?

you could set the database as IEnumberable and use linq to check if the values exist. check out this link

LINQ Query on Datatable to check if record exists

the example given is

var dataRowQuery= myDataTable.AsEnumerable().Where(row => ...

you could supplement where with any

How to debug an apache virtual host configuration?

First check out config files for syntax errors with apachectl configtest and then look into apache error logs.

What are .NET Assemblies?

In addition to the accepted answer, I want to give you an example!

For instance, we all use

System.Console.WriteLine()

But Where is the code for System.Console.WriteLine!?
which is the code that actually puts the text on the console?

If you look at the first page of the documentation for the Console class, you‘ll see near the top the following: Assembly: mscorlib (in mscorlib.dll) This indicates that the code for the Console class is located in an assem-bly named mscorlib. An assembly can consist of multiple files, but in this case it‘s only one file, which is the dynamic link library mscorlib.dll.

The mscorlib.dll file is very important in .NET, It is the main DLL for class libraries in .NET, and it contains all the basic .NET classes and structures.

if you know C or C++, generally you need a #include directive at the top that references a header file. The include file provides function prototypes to the compiler. on the contrast The C# compiler does not need header files. During compilation, the C# compiler access the mscorlib.dll file directly and obtains information from metadata in that file concerning all the classes and other types defined therein.

The C# compiler is able to establish that mscorlib.dll does indeed contain a class named Console in a namespace named System with a method named WriteLine that accepts a single argument of type string.

The C# compiler can determine that the WriteLine call is valid, and the compiler establishes a reference to the mscorlib assembly in the executable.

by default The C# compiler will access mscorlib.dll, but for other DLLs, you‘ll need to tell the compiler the assembly in which the classes are located. These are known as references.

I hope that it's clear now!

From DotNetBookZero Charles pitzold

In Linux, how to tell how much memory processes are using?

You can use pmap + awk.

Most likely, we're interested in the RSS memory which is the 3rd column in the last line of the example pmap output below (82564).

$ pmap -x <pid>

Address           Kbytes     RSS   Dirty Mode   Mapping

....

00007f9caf3e7000       4       4       4 r----  ld-2.17.so
00007f9caf3e8000       8       8       8 rw---  ld-2.17.so
00007fffe8931000     132      12      12 rw---    [ stack ]
00007fffe89fe000       8       8       0 r-x--    [ anon ]
ffffffffff600000       4       0       0 r-x--    [ anon ]
----------------  ------  ------  ------
total kB          688584   82564    9592

Awk is then used to extract that value.

$ pmap -x <pid> | awk '/total/ { print $4 "K" }'

The pmap values are in kilobytes. If we wanted it in megabytes, we could do something like this.

$ pmap -x <pid> | awk '/total/ { print $4 / 1024 "M" }'

Eloquent - where not equal to

For where field not empty this worked for me:

->where('table_name.field_name', '<>', '')

How to order results with findBy() in Doctrine

$ens = $em->getRepository('AcmeBinBundle:Marks')
              ->findBy(
                 array(), 
                 array('id' => 'ASC')
               );

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

Put this near the top of your jupyter notebook. Comment out what you don't need.

# confirm TensorFlow sees the GPU
from tensorflow.python.client import device_lib
assert 'GPU' in str(device_lib.list_local_devices())

# confirm Keras sees the GPU (for TensorFlow 1.X + Keras)
from keras import backend
assert len(backend.tensorflow_backend._get_available_gpus()) > 0

# confirm PyTorch sees the GPU
from torch import cuda
assert cuda.is_available()
assert cuda.device_count() > 0
print(cuda.get_device_name(cuda.current_device()))

NOTE: With the release of TensorFlow 2.0, Keras is now included as part of the TF API.

Originally answerwed here.

How to Retrieve value from JTextField in Java Swing?

How do we retrieve a value from a text field?

mytestField.getText();

ActionListner example:

mytextField.addActionListener(this);

public void actionPerformed(ActionEvent evt) {
    String text = textField.getText();
    textArea.append(text + newline);
    textField.selectAll();
}

How to have multiple conditions for one if statement in python

Might be a bit odd or bad practice but this is one way of going about it.

(arg1, arg2, arg3) = (1, 2, 3)

if (arg1 == 1)*(arg2 == 2)*(arg3 == 3):
    print('Example.')

Anything multiplied by 0 == 0. If any of these conditions fail then it evaluates to false.

Sum all the elements java arraylist

I haven't tested it but it should work.

public double incassoMargherita()
{
    double sum = 0;
    for(int i = 0; i < m.size(); i++)
    {
        sum = sum + m.get(i);
    }
    return sum;
}

Always show vertical scrollbar in <select>

I guess you cant, this maybe a limitation or not included in the IE browser. I have tried your jsfiddle with IE6-8 and all of it doesn't show the scrollbar and not sure with IE9. While in FF and chrome the scrollbar is shown. I also want to see how to do it in IE if possible.

If you really want to show the scrollbar, you can add a fake scrollbar. If you are familiar with some of the js library which use in RIA. Like in jquery/dojo some of the select is editable, because it is a combination of textbox + select or it can also be a textbox + div.

As an example, see it here a JavaScript that make select like editable.

Function overloading in Python: Missing

As unwind noted, keyword arguments with default values can go a long way.

I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is.

Thus, if your method may accept a string or a tuple, you might do something like this:

def print_names(names):
    """Takes a space-delimited string or an iterable"""
    try:
        for name in names.split(): # string case
            print name
    except AttributeError:
        for name in names:
            print name

Then you could do either of these:

print_names("Ryan Billy")
print_names(("Ryan", "Billy"))

Although an API like that sometimes indicates a design problem.

Zoom in on a point (using scale and translate)

you can use scrollto(x,y) function to handle the position of scrollbar right to the point that you need to be showed after zooming.for finding the position of mouse use event.clientX and event.clientY. this will help you

Angular 4.3 - HttpClient set params

As far as I can see from the implementation at https://github.com/angular/angular/blob/master/packages/common/http/src/params.ts

You must provide values separately - You are not able to avoid your loop.

There is also a constructor which takes a string as a parameter, but it is in form param=value&param2=value2 so there is no deal for You (in both cases you will finish with looping your object).

You can always report an issue/feature request to angular, what I strongly advise: https://github.com/angular/angular/issues

PS: Remember about difference between set and append methods ;)

How to reset db in Django? I get a command 'reset' not found error

reset has been replaced by flush with Django 1.5, see:

python manage.py help flush

Best way to specify whitespace in a String.Split operation

Note that adjacent whitespace will NOT be treated as a single delimiter, even when using String.Split(null). If any of your tokens are separated with multiple spaces or tabs, you'll get empty strings returned in your array.

From the documentation:

Each element of separator defines a separate delimiter character. If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.

How do C++ class members get initialized if I don't do it explicitly?

First, let me explain what a mem-initializer-list is. A mem-initializer-list is a comma-separated list of mem-initializers, where each mem-initializer is a member name followed by (, followed by an expression-list, followed by a ). The expression-list is how the member is constructed. For example, in

static const char s_str[] = "bodacydo";
class Example
{
private:
    int *ptr;
    string name;
    string *pname;
    string &rname;
    const string &crname;
    int age;

public:
    Example()
        : name(s_str, s_str + 8), rname(name), crname(name), age(-4)
    {
    }
};

the mem-initializer-list of the user-supplied, no-arguments constructor is name(s_str, s_str + 8), rname(name), crname(name), age(-4). This mem-initializer-list means that the name member is initialized by the std::string constructor that takes two input iterators, the rname member is initialized with a reference to name, the crname member is initialized with a const-reference to name, and the age member is initialized with the value -4.

Each constructor has its own mem-initializer-list, and members can only be initialized in a prescribed order (basically the order in which the members are declared in the class). Thus, the members of Example can only be initialized in the order: ptr, name, pname, rname, crname, and age.

When you do not specify a mem-initializer of a member, the C++ standard says:

If the entity is a nonstatic data member ... of class type ..., the entity is default-initialized (8.5). ... Otherwise, the entity is not initialized.

Here, because name is a nonstatic data member of class type, it is default-initialized if no initializer for name was specified in the mem-initializer-list. All other members of Example do not have class type, so they are not initialized.

When the standard says that they are not initialized, this means that they can have any value. Thus, because the above code did not initialize pname, it could be anything.

Note that you still have to follow other rules, such as the rule that references must always be initialized. It is a compiler error to not initialize references.

Updating the list view when the adapter data changes

Change this line:

mMyListView.setAdapter(new ArrayAdapter<String>(this, 
                           android.R.layout.simple_list_item_1, 
                           listItems));

to:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                   android.R.layout.simple_list_item_1, 
                                   listItems)
mMyListView.setAdapter(adapter);

and after updating the value of a list item, call:

adapter.notifyDataSetChanged();

Unknown version of Tomcat was specified in Eclipse

This happened to me because Tomcat was still in the process of downloading (Download and Install). The message disappeared after a few minutes.

The eclipse window should really have some type of progress indicator showing download status.

Sending a file over TCP sockets in Python

Remove below code

s.send("Hello server!")

because your sending s.send("Hello server!") to server, so your output file is somewhat more in size.

How do I detect the Python version at runtime?

Just in case you want to see all of the gory details in human readable form, you can use:

import platform;

print(platform.sys.version);

Output for my system:

3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56) 
[GCC 7.2.0]

Something very detailed but machine parsable would be to get the version_info object from platform.sys, instead, and then use its properties to take a predetermined course of action. For example:

import platform;

print(platform.sys.version_info)

Output on my system:

sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)

How to get all table names from a database?

You need to iterate over your ResultSet calling next().

This is an example from java2s.com:

DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
  System.out.println(rs.getString(3));
}

Column 3 is the TABLE_NAME (see documentation of DatabaseMetaData::getTables).

Convert txt to csv python script

I suposse this is the output you need:

title,intro,tagline

2.9,Gardena,CA

It can be done with this changes to your code:

import csv
import itertools

with open('log.txt', 'r') as in_file:
    lines = in_file.read().splitlines()
    stripped = [line.replace(","," ").split() for line in lines]
    grouped = itertools.izip(*[stripped]*1)
    with open('log.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title', 'intro', 'tagline'))
        for group in grouped:
            writer.writerows(group)

What is fastest children() or find() in jQuery?

None of the other answers dealt with the case of using .children() or .find(">") to only search for immediate children of a parent element. So, I created a jsPerf test to find out, using three different ways to distinguish children.

As it happens, even when using the extra ">" selector, .find() is still a lot faster than .children(); on my system, 10x so.

So, from my perspective, there does not appear to be much reason to use the filtering mechanism of .children() at all.

jQuery get the id/value of <li> element after click function

If you change your html code a bit - remove the ids

<ul id='myid'>  
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>

Then the jquery code you want is...

$("#myid li").click(function() {
    alert($(this).prevAll().length+1);
});?

You don't need to place any ids, just keep on adding li items.

Take a look at demo

Useful links

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

Cross-Origin Read Blocking (CORB)

It's not clear from the question, but assuming this is something happening on a development or test client, and given that you are already using Fiddler you can have Fiddler respond with an allow response:

  • Select the problem request in Fiddler
  • Open the AutoResponder tab
  • Click Add Rule and edit the rule to:
    • Method:OPTIONS server url here, e.g. Method:OPTIONS http://localhost
    • *CORSPreflightAllow
  • Check Unmatched requests passthrough
  • Check Enable Rules

A couple notes:

  1. Obviously this is only a solution for development/testing where it isn't possible/practical to modify the API service
  2. Check that any agreements you have with the third-party API provider allow you to do this
  3. As others have noted, this is part of how CORS works, and eventually the header will need to be set on the API server. If you control that server, you can set the headers yourself. In this case since it is a third party service, I can only assume they have some mechanism via which you are able to provide them with the URL of the originating site and they will update their service accordingly to respond with the correct headers.

undefined reference to boost::system::system_category() when compiling

The boost library you are using depends on the boost_system library. (Not all of them do.)

Assuming you use gcc, try adding -lboost_system to your compiler command line in order to link against that library.

Running the new Intel emulator for Android

You have to download the Intel® Hardware Accelerated Execution Manager. Then you will get this message:

Starting emulator for AVD 'test' emulator: device fd:740 HAX is working and emulator runs in fast virt mode

GROUP BY with MAX(DATE)

I know I'm late to the party, but try this...

SELECT 
    `Train`, 
    `Dest`,
    SUBSTRING_INDEX(GROUP_CONCAT(`Time` ORDER BY `Time` DESC), ",", 1) AS `Time`
FROM TrainTable
GROUP BY Train;

Src: Group Concat Documentation

Edit: fixed sql syntax

Is it necessary to assign a string to a variable before comparing it to another?

You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:

NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];

How to upload images into MySQL database using PHP code

Just few more details:

  • Add mysql field

`image` blob

  • Get data from image

$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));

  • Insert image data into db

$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";

  • Show image to the web

<img src="data:image/png;base64,'.base64_encode($row['image']).'">

  • End

Verilog generate/genvar in an always block

If you do not mind having to compile/generate the file then you could use a pre processing technique. This gives you the power of the generate but results in a clean Verilog file which is often easier to debug and leads to less simulator issues.

I use RubyIt to generate verilog files from templates using ERB (Embedded Ruby).

parameter ROWBITS = <%= ROWBITS %> ;
always @(posedge sysclk) begin
  <% (0...ROWBITS).each do |addr| -%>
    temp[<%= addr %>] <= 1'b0;
  <% end -%>
end

Generating the module_name.v file with :

$ ruby_it --parameter ROWBITS=4 --outpath ./ --file ./module_name.rv

The generated module_name.v

parameter ROWBITS = 4 ;
always @(posedge sysclk) begin
  temp[0] <= 1'b0;
  temp[1] <= 1'b0;
  temp[2] <= 1'b0;
  temp[3] <= 1'b0;
end

APR based Apache Tomcat Native library was not found on the java.library.path?

I resolve this (On Eclipse IDE) by delete my old server and create the same again. This error is because you don't proper terminate Tomcat server and close Eclipse.

How do I change the font size of a UILabel in Swift?

We can set font as per our requirement like,

label.font = UIFont(name: "Avenir-Light", size: 15.0)
label.font = UIFont.boldSystemFontOfSize(15)
label.font = UIFont.italicSystemFontOfSize(15)
label.font = UIFont.systemFontOfSize(17)

Google Map API v3 ~ Simply Close an infowindow?

Or you can share/reuse the same infoWindow object. See this google demo for reference.

Same code from demo

var Demo = { map: null,  infoWindow: null
};

/**
 * Called when clicking anywhere on the map and closes the info window.
 */
Demo.closeInfoWindow = function() {
  Demo.infoWindow.close();
};

/**
 * Opens the shared info window, anchors it to the specified marker, and
 * displays the marker's position as its content.
 */
Demo.openInfoWindow = function(marker) {
  var markerLatLng = marker.getPosition();
  Demo.infoWindow.setContent([
    '<b>Marker position is:</b><br/>',
    markerLatLng.lat(),
    ', ',
    markerLatLng.lng()
  ].join(''));
  Demo.infoWindow.open(Demo.map, marker);
},

/**
 * Called only once on initial page load to initialize the map.
 */
Demo.init = function() {
  // Create single instance of a Google Map.
  var centerLatLng = new google.maps.LatLng(37.789879, -122.390442);
  Demo.map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 13,
    center: centerLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // Create a single instance of the InfoWindow object which will be shared
  // by all Map objects to display information to the user.
  Demo.infoWindow = new google.maps.InfoWindow();

  // Make the info window close when clicking anywhere on the map.
  google.maps.event.addListener(Demo.map, 'click', Demo.closeInfoWindow);

  // Add multiple markers in a few random locations around San Francisco.
  // First random marker
  var marker1 = new google.maps.Marker({
    map: Demo.map,
    position: centerLatLng
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker1, 'click', function() {
    Demo.openInfoWindow(marker1);
  });

  // Second random marker
  var marker2 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.787814,-122.40764),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker2, 'click', function() {
    Demo.openInfoWindow(marker2);
  });

  // Third random marker
  var marker3 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.767568,-122.391665),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker3, 'click', function() {
    Demo.openInfoWindow(marker3);
  });
}

How to remove duplicates from Python list and keep order?

If it's clarity you're after, rather than speed, I think this is very clear:

def sortAndUniq(input):
  output = []
  for x in input:
    if x not in output:
      output.append(x)
  output.sort()
  return output

It's O(n^2) though, with the repeated use of not in for each element of the input list.

How to sort an array of objects in Java?

import java.util.Collections;

import java.util.List;

import java.util.ArrayList;


public class Test {

public static void main(String[] args) {

   List<Student> str = new ArrayList<Student>();

   str.add(new Student(101, "aaa"));

   str.add(new Student(104, "bbb"));

   str.add(new Student(103, "ccc"));

   str.add(new Student(105, "ddd"));

   str.add(new Student(104, "eee"));

   str.add(new Student(102, "fff"));




   Collections.sort(str);
    for(Student student : str) {

        System.out.println(student);
    }

}
}

A potentially dangerous Request.Form value was detected from the client

You could also use JavaScript's escape(string) function to replace the special characters. Then server side use Server.URLDecode(string) to switch it back.

This way you don't have to turn off input validation and it will be more clear to other programmers that the string may have HTML content.

Bootstrap 3 breakpoints and media queries

The reference to 480px has been removed. Instead it says:

/* Extra small devices (phones, less than 768px) */
/* No media query since this is the default in Bootstrap */

There isn't a breakpoint below 768px in Bootstrap 3.

If you want to use the @screen-sm-min and other mixins then you need to be compiling with LESS, see http://getbootstrap.com/css/#grid-less

Here's a tutorial on how to use Bootstrap 3 and LESS: http://www.helloerik.com/bootstrap-3-less-workflow-tutorial

How can I use different certificates on specific connections?

I read through LOTS of places online to solve this thing. This is the code I wrote to make it work:

ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();

TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());

app.certificateString is a String that contains the Certificate, for example:

static public String certificateString=
        "-----BEGIN CERTIFICATE-----\n" +
        "MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
        "BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
        ... a bunch of characters...
        "5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
        "-----END CERTIFICATE-----";

I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line.

Get all directories within directory nodejs

If you need to use all async version. You can have something like this.

  1. Record the directory length, uses it as an indicator to tell if all async stat tasks are finished.

  2. If the async stat tasks are finished, all the file stat has been checked, so call the callback

This will only work as long as Node.js is single thread, because it assumes no two async tasks will increase the counter at the same time.

'use strict';

var fs = require("fs");
var path = require("path");
var basePath = "./";

function result_callback(results) {
    results.forEach((obj) => {
        console.log("isFile: " + obj.fileName);
        console.log("fileName: " + obj.isFile);
    });
};

fs.readdir(basePath, (err, files) => {
    var results = [];
    var total = files.length;
    var finished = 0;

    files.forEach((fileName) => {
        // console.log(fileName);
        var fullPath = path.join(basePath, fileName);

        fs.stat(fullPath, (err, stat) => {
            // this will work because Node.js is single thread
            // therefore, the counter will not increment at the same time by two callback
            finished++;

            if (stat.isFile()) {
                results.push({
                    fileName: fileName,
                    isFile: stat.isFile()
                });
            }

            if (finished == total) {
                result_callback(results);
            }
        });
    });
});

As you can see, this is a "depth first" approach, and this could result in callback hell, and it is not quite "functional" . People try to solve this problem with Promise, by wrapping the async task into an Promise object.

'use strict';

var fs = require("fs");
var path = require("path");
var basePath = "./";

function result_callback(results) {
    results.forEach((obj) => {
        console.log("isFile: " + obj.fileName);
        console.log("fileName: " + obj.isFile);
    });
};

fs.readdir(basePath, (err, files) => {
    var results = [];
    var total = files.length;
    var finished = 0;

    var promises = files.map((fileName) => {
        // console.log(fileName);
        var fullPath = path.join(basePath, fileName);

        return new Promise((resolve, reject) => {
            // try to replace fullPath wil "aaa", it will reject
            fs.stat(fullPath, (err, stat) => {
                if (err) {
                    reject(err);
                    return;
                }

                var obj = {
                    fileName: fileName,
                    isFile: stat.isFile()
                };

                resolve(obj);
            });
        });
    });

    Promise.all(promises).then((values) => {
        console.log("All the promise resolved");
        console.log(values);
        console.log("Filter out folder: ");
        values
            .filter((obj) => obj.isFile)
            .forEach((obj) => {
                console.log(obj.fileName);
            });
    }, (reason) => {
        console.log("Not all the promise resolved");
        console.log(reason);
    });
});

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

Using the currently latest version of the google gms services resolved it for me.

In the project level build.gradle:

buildscript {
    ...
    dependencies {
        classpath 'com.google.gms:google-services:3.2.1'
        ...  
    }
}

How to install OpenSSL in windows 10?

Either set the openssl present in Git as your default openssl and include that into your path in environmental variables (quick way)

OR

  1. Install the system-specific openssl from this link.
  2. set the following variable : set OPENSSL_CONF=LOCATION_OF_SSL_INSTALL\bin\openssl.cfg
  3. Update the path : set Path=...Other Values here...;LOCATION_OF_SSL_INSTALL\bin

Limiting Python input strings to certain characters and lengths

We can use assert here.

def _input(inp_str:str):
    try:
        assert len(inp_str)<=15,print('More than 15 characters present')
        assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
        return inp_str
    except Exception as e:
        pass

_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present

Why can't variables be declared in a switch statement?

newVal exists in the entire scope of the switch but is only initialised if the VAL limb is hit. If you create a block around the code in VAL it should be OK.

How do I iterate through the files in a directory in Java?

It's a tree, so recursion is your friend: start with the parent directory and call the method to get an array of child Files. Iterate through the child array. If the current value is a directory, pass it to a recursive call of your method. If not, process the leaf file appropriately.

Foreign keys in mongo?

You may be interested in using a ORM like Mongoid or MongoMapper.

http://mongoid.org/docs/relations/referenced/1-n.html

In a NoSQL database like MongoDB there are not 'tables' but collections. Documents are grouped inside Collections. You can have any kind of document – with any kind of data – in a single collection. Basically, in a NoSQL database it is up to you to decide how to organise the data and its relations, if there are any.

What Mongoid and MongoMapper do is to provide you with convenient methods to set up relations quite easily. Check out the link I gave you and ask any thing.

Edit:

In mongoid you will write your scheme like this:

class Student
  include Mongoid::Document

    field :name
    embeds_many :addresses
    embeds_many :scores    
end

class Address
  include Mongoid::Document

    field :address
    field :city
    field :state
    field :postalCode
    embedded_in :student
end

class Score
  include Mongoid::Document

    belongs_to :course
    field :grade, type: Float
    embedded_in :student
end


class Course
  include Mongoid::Document

  field :name
  has_many :scores  
end

Edit:

> db.foo.insert({group:"phones"})
> db.foo.find()                  
{ "_id" : ObjectId("4df6539ae90592692ccc9940"), "group" : "phones" }
{ "_id" : ObjectId("4df6540fe90592692ccc9941"), "group" : "phones" }
>db.foo.find({'_id':ObjectId("4df6539ae90592692ccc9940")}) 
{ "_id" : ObjectId("4df6539ae90592692ccc9940"), "group" : "phones" }

You can use that ObjectId in order to do relations between documents.

open read and close a file in 1 line of code

Using more_itertools.with_iter, it is possible to open, read, close and assign an equivalent output in one line (excluding the import statement):

import more_itertools as mit


output = "".join(line for line in mit.with_iter(open("pagehead.section.htm", "r")))

Although possible, I would look for another approach other than assigning the contents of a file to a variable, i.e. lazy iteration - this can be done using a traditional with block or in the example above by removing join() and iterating output.

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

I need a Nodejs scheduler that allows for tasks at different intervals

I have written a node module that provides a wrapper around setInterval using moment durations providing a declarative interface:

npm install every-moment

var every = require('every-moment');

var timer = every(5, 'seconds', function() {
    console.log(this.duration);
});

every(2, 'weeks', function() {
    console.log(this.duration);
    timer.stop();
    this.set(1, 'week');
    this.start();
});

https://www.npmjs.com/package/every-moment

https://github.com/raygerrard/every-moment

Why is $$ returning the same id as the parent process?

$$ is defined to return the process ID of the parent in a subshell; from the man page under "Special Parameters":

$ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell.

In bash 4, you can get the process ID of the child with BASHPID.

~ $ echo $$
17601
~ $ ( echo $$; echo $BASHPID )
17601
17634

What is time_t ultimately a typedef to?

It's a 32-bit signed integer type on most legacy platforms. However, that causes your code to suffer from the year 2038 bug. So modern C libraries should be defining it to be a signed 64-bit int instead, which is safe for a few billion years.

How to save username and password in Git?

From the comment by rifrol, on Linux Ubuntu, from this answer, here's how in Ubuntu:

sudo apt-get install libsecret-1-0 libsecret-1-dev
cd /usr/share/doc/git/contrib/credential/libsecret
sudo make
git config --global credential.helper /usr/share/doc/git/contrib/credential/libsecret/git-credential-libsecret

Some other distro's provide the binary so you don't have to build it.

In OS X it typically comes "built" with a default module of "osxkeychain" so you get it for free.

Write Array to Excel Range

This is an excerpt from method of mine, which converts a DataTable (the dt variable) into an array and then writes the array into a Range on a worksheet (wsh var). You can also change the topRow variable to whatever row you want the array of strings to be placed at.

object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];
for (int r = 0; r < dt.Rows.Count; r++)
{
    DataRow dr = dt.Rows[r];
    for (int c = 0; c < dt.Columns.Count; c++)
    {
        arr[r, c] = dr[c];
    }
}
Excel.Range c1 = (Excel.Range)wsh.Cells[topRow, 1];
Excel.Range c2 = (Excel.Range)wsh.Cells[topRow + dt.Rows.Count - 1, dt.Columns.Count];
Excel.Range range = wsh.get_Range(c1, c2);
range.Value = arr;

Of course you do not need to use an intermediate DataTable like I did, the code excerpt is just to demonstrate how an array can be written to worksheet in single call.

How to resolve Value cannot be null. Parameter name: source in linq?

System.ArgumentNullException: Value cannot be null. Parameter name: value

This error message is not very helpful!

You can get this error in many different ways. The error may not always be with the parameter name: value. It could be whatever parameter name is being passed into a function.

As a generic way to solve this, look at the stack trace or call stack:

Test method GetApiModel threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: value
    at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)

You can see that the parameter name value is the first parameter for DeserializeObject. This lead me to check my AutoMapper mapping where we are deserializing a JSON string. That string is null in my database.

You can change the code to check for null.

Credit card expiration dates - Inclusive or exclusive?

Have a look on one of your own credit cards. It'll have some text like EXPIRES END or VALID THRU above the date. So the card expires at the end of the given month.

How can I write to the console in PHP?

There is also a great Google Chrome extension, PHP Console, with a PHP library that allows you to:

  • See errors and exceptions in the Chrome JavaScript console and in the notification popups.
  • Dump any type of variable.
  • Execute PHP code remotely.
  • Protect access by password.
  • Group console logs by request.
  • Jump to error file:line in your text editor.
  • Copy error/debug data to the clipboard (for testers).

How to show text on image when hovering?

You can also use the title attribute in your image tag

<img src="content/assets/thumbnails/transparent_150x150.png" alt="" title="hover text" />

Service vs IntentService in the Android platform

An IntentService is an extension of a Service that is made to ease the execution of a task that needs to be executed in background and in a seperated thread.

IntentService starts, create a thread and runs its task in the thread. once done, it cleans everything. Only one instance of a IntentService can run at the same time, several calls are enqueued.

It is very simple to use and very convenient for a lot of uses, for instance downloading stuff. But it has limitations that can make you want to use instead the more basic (not simple) Service.

For example, a service connected to a xmpp server and bound by activities cannot be simply done using an IntentService. You'll end up ignoring or overriding IntentService stuffs.

Android: how to make an activity return results to the activity which calls it?

UPDATE Feb. 2021

As in Activity v1.2.0 and Fragment v1.3.0, the new Activity Result APIs have been introduced.

The Activity Result APIs provide components for registering for a result, launching the result, and handling the result once it is dispatched by the system.

So there is no need of using startActivityForResult and onActivityResult anymore.

In order to use the new API, you need to create an ActivityResultLauncher in your origin Activity, specifying the callback that will be run when the destination Activity finishes and returns the desired data:

private val intentLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->

        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.getStringExtra("streetkey")
            result.data?.getStringExtra("citykey")
            result.data?.getStringExtra("homekey")
        }
    }

and then, launching your intent whenever you need to:

intentLauncher.launch(Intent(this, YourActivity::class.java))

And to return data from the destination Activity, you just have to add an intent with the values to return to the setResult() method:

val data = Intent()
data.putExtra("streetkey", "streetname")
data.putExtra("citykey", "cityname")
data.putExtra("homekey", "homename")

setResult(Activity.RESULT_OK, data)
finish()

For any additional information, please refer to Android Documentation

How do you create a UIImage View Programmatically - Swift

First you create a UIImage from your image file, then create a UIImageView from that:

let imageName = "yourImage.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)

Finally you'll need to give imageView a frame and add it your view for it to be visible:

imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(imageView)

Preview an image before it is uploaded

TO PREVIEW MULTIPLE FILES using jquery

_x000D_
_x000D_
$(document).ready(function(){
    $('#image').change(function(){
        $("#frames").html('');
        for (var i = 0; i < $(this)[0].files.length; i++) {
            $("#frames").append('<img src="'+window.URL.createObjectURL(this.files[i])+'" width="100px" height="100px"/>');
        }
    });
});
_x000D_
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <input type="file" id="image" name="image[]" multiple /><br/>
    <div id="frames"></div>
</body>
_x000D_
_x000D_
_x000D_

Unix epoch time to Java Date object

java.time

Using the java.time framework built into Java 8 and later.

import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;

long epoch = Long.parseLong("1081157732");
Instant instant = Instant.ofEpochSecond(epoch);
ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); # ZonedDateTime = 2004-04-05T09:35:32Z[UTC]

In this case you should better use ZonedDateTime to mark it as date in UTC time zone because Epoch is defined in UTC in Unix time used by Java.

ZoneOffset contains a handy constant for the UTC time zone, as seen in last line above. Its superclass, ZoneId can be used to adjust into other time zones.

ZoneId zoneId = ZoneId.of( "America/Montreal" );

Random number in range [min - max] using PHP

A quicker faster version would use mt_rand:

$min=1;
$max=20;
echo mt_rand($min,$max);

Source: http://www.php.net/manual/en/function.mt-rand.php.

NOTE: Your server needs to have the Math PHP module enabled for this to work. If it doesn't, bug your host to enable it, or you have to use the normal (and slower) rand().

How to get HttpClient to pass credentials along with the request?

You can configure HttpClient to automatically pass credentials like this:

var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

jQuery UI dialog box not positioned center screen

To fix this issue I made sure my body height was set to 100%.

body { height:100% }

This also maintains the center position while the user scrolls.

WiX tricks and tips

Creating Custom Action for WIX written in managed code (C#) without Votive

http://www.codeproject.com/KB/install/wixcustomaction.aspx

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

connecting to phpMyAdmin database with PHP/MySQL

This (mysql_connect, mysql_...) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
(ref: http://php.net/manual/en/function.mysql-connect.php)

  • Object Oriented:

    $mysqli = new mysqli("host", "user", "password");
    $mysqli->select_db("db");
    
  • Procedural:

    $link = mysqli_connect("host","user","password") or die(mysqli_error($link)); 
    mysqli_select_db($link, "db");
    

Calculate mean and standard deviation from a vector of samples in C++ using Boost

Create your own container:

template <class T>
class statList : public std::list<T>
{
    public:
        statList() : std::list<T>::list() {}
        ~statList() {}
        T mean() {
           return accumulate(begin(),end(),0.0)/size();
        }
        T stddev() {
           T diff_sum = 0;
           T m = mean();
           for(iterator it= begin(); it != end(); ++it)
               diff_sum += ((*it - m)*(*it -m));
           return diff_sum/size();
        }
};

It does have some limitations, but it works beautifully when you know what you are doing.