Programs & Examples On #Netdatacontractserializer

How to specify a min but no max decimal using the range data annotation attribute?

I would put decimal.MaxValue.ToString() since this is the effective ceiling for the decmial type it is equivalent to not having an upper bound.

Remove the legend on a matplotlib figure

As of matplotlib v1.4.0rc4, a remove method has been added to the legend object.

Usage:

ax.get_legend().remove()

or

legend = ax.legend(...)
...
legend.remove()

See here for the commit where this was introduced.

Which characters are valid/invalid in a JSON key name?

Unicode codepoints U+D800 to U+DFFF must be avoided: they are invalid in Unicode because they are reserved for UTF-16 surrogate pairs. Some JSON encoders/decoders will replace them with U+FFFD. See for example how the Go language and its JSON library deals with them.

So avoid "\uD800" to "\uDFFF" alone (not in surrogate pairs).

Laravel 4: how to run a raw SQL?

In the Laravel 4 manual - it talks about doing raw commands like this:

DB::select(DB::raw('RENAME TABLE photos TO images'));

edit: I just found this in the Laravel 4 documentation which is probably better:

DB::statement('drop table users');

Update: In Laravel 4.1 (maybe 4.0 - I'm not sure) - you can also do this for a raw Where query:

$users = User::whereRaw('age > ? and votes = 100', array(25))->get();

Further Update If you are specifically looking to do a table rename - there is a schema command for that - see Mike's answer below for that.

Squash my last X commits together using Git

2020 Simple solution without rebase :

git reset --soft HEAD~2

git commit -m "new commit message"

git push -f

2 means the last two commits will be squashed. You can replace it by any number

How to get correct timestamp in C#

var timestamp = DateTime.Now.ToFileTime();

//output: 132260149842749745

This is an alternative way to individuate distinct transactions. It's not unix time, but windows filetime.

From the docs:

A Windows file time is a 64-bit value that represents the number of 100- 
nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 
A.D. (C.E.) Coordinated Universal Time (UTC).

Confirmation dialog on ng-click - AngularJS

Here is a clean and simple solution using angular promises $q, $window and native .confirm() modal:

angular.module('myApp',[])
  .controller('classicController', ( $q, $window ) => {
    this.deleteStuff = ( id ) => {
      $q.when($window.confirm('Are you sure ?'))
        .then(( confirm ) => {
          if ( confirm ) {
            // delete stuff
          }
        });
    };
  });

Here I'm using controllerAs syntax and ES6 arrow functions but it's also working in plain ol' ES5.

Git pull after forced update

To receive the new commits

git fetch

Reset

You can reset the commit for a local branch using git reset.

To change the commit of a local branch:

git reset origin/master --hard

Be careful though, as the documentation puts it:

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

If you want to actually keep whatever changes you've got locally - do a --soft reset instead. Which will update the commit history for the branch, but not change any files in the working directory (and you can then commit them).

Rebase

You can replay your local commits on top of any other commit/branch using git rebase:

git rebase -i origin/master

This will invoke rebase in interactive mode where you can choose how to apply each individual commit that isn't in the history you are rebasing on top of.

If the commits you removed (with git push -f) have already been pulled into the local history, they will be listed as commits that will be reapplied - they would need to be deleted as part of the rebase or they will simply be re-included into the history for the branch - and reappear in the remote history on the next push.

Use the help git command --help for more details and examples on any of the above (or other) commands.

Determine device (iPhone, iPod Touch) with iOS

Updated platform strings for iPad Air 2 and iPad mini 3:

- (NSString *)platformString
{
    NSString *platform = [self platform];

    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"])    return @"Verizon iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"])    return @"iPhone 5 (GSM)";
    if ([platform isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (GSM+CDMA)";
    if ([platform isEqualToString:@"iPhone5,3"])    return @"iPhone 5c (GSM)";
    if ([platform isEqualToString:@"iPhone5,4"])    return @"iPhone 5c (GSM+CDMA)";
    if ([platform isEqualToString:@"iPhone6,1"])    return @"iPhone 5s (GSM)";
    if ([platform isEqualToString:@"iPhone6,2"])    return @"iPhone 5s (GSM+CDMA)";
    if ([platform isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([platform isEqualToString:@"iPod5,1"])      return @"iPod Touch 5G";
    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"iPad2,4"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,5"])      return @"iPad Mini (WiFi)";
    if ([platform isEqualToString:@"iPad2,6"])      return @"iPad Mini (GSM)";
    if ([platform isEqualToString:@"iPad2,7"])      return @"iPad Mini (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
    if ([platform isEqualToString:@"iPad3,2"])      return @"iPad 3 (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad3,3"])      return @"iPad 3 (GSM)";
    if ([platform isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([platform isEqualToString:@"iPad3,5"])      return @"iPad 4 (GSM)";
    if ([platform isEqualToString:@"iPad3,6"])      return @"iPad 4 (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad4,1"])      return @"iPad Air (WiFi)";

    if ([platform isEqualToString:@"iPad4,2"])      return @"iPad Air (Cellular)";
    if ([platform isEqualToString:@"iPad4,4"])      return @"iPad mini 2G (WiFi)";
    if ([platform isEqualToString:@"iPad4,5"])      return @"iPad mini 2G (Cellular)";

    if ([platform isEqualToString:@"iPad4,7"])      return @"iPad mini 3 (WiFi)";
    if ([platform isEqualToString:@"iPad4,8"])      return @"iPad mini 3 (Cellular)";
    if ([platform isEqualToString:@"iPad4,9"])      return @"iPad mini 3 (China Model)";

    if ([platform isEqualToString:@"iPad5,3"])      return @"iPad Air 2 (WiFi)";
    if ([platform isEqualToString:@"iPad5,4"])      return @"iPad Air 2 (Cellular)";
    if ([platform isEqualToString:@"iPad6,8"])      return @"iPad Pro";

    if ([platform isEqualToString:@"i386"])         return @"Simulator";
    if ([platform isEqualToString:@"x86_64"])       return @"Simulator";

    return platform;
}

Cloning an array in Javascript/Typescript

Using map or other similar solution do not help to clone deeply an array of object. An easier way to do this without adding a new library is using JSON.stringfy and then JSON.parse.

In your case this should work :

this.backupData = JSON.parse(JSON.stringify(genericItems));

jQuery Form Validation before Ajax submit

I think submitHandler with jquery validation is good solution. Please get idea from this code. Inspired from @Darin Dimitrov

$('.calculate').validate({

                submitHandler: function(form) {
                    $.ajax({
                        url: 'response.php',
                        type: 'POST',
                        data: $(form).serialize(),
                        success: function(response) {
                            $('#'+form.id+' .ht-response-data').html(response);
                        }            
                    });
                }
            });

How does OkHttp get Json string?

I hope you managed to obtain the json data from the json string.

Well I think this will be of help

try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url(urls[0])
    .build();
Response responses = null;

try {
    responses = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}   

String jsonData = responses.body().string();

JSONObject Jobject = new JSONObject(jsonData);
JSONArray Jarray = Jobject.getJSONArray("employees");

//define the strings that will temporary store the data
String fname,lname;

//get the length of the json array
int limit = Jarray.length()

//datastore array of size limit
String dataStore[] = new String[limit];

for (int i = 0; i < limit; i++) {
    JSONObject object     = Jarray.getJSONObject(i);

    fname = object.getString("firstName");
    lname = object.getString("lastName");

    Log.d("JSON DATA", fname + " ## " + lname);

    //store the data into the array
    dataStore[i] = fname + " ## " + lname;
}

//prove that the data was stored in the array      
 for (String content ; dataStore ) {
        Log.d("ARRAY CONTENT", content);
    }

Remember to use AsyncTask or SyncAdapter(IntentService), to prevent getting a NetworkOnMainThreadException

Also import the okhttp library in your build.gradle

compile 'com.squareup.okhttp:okhttp:2.4.0'

How can I add 1 day to current date?

int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);

CodePen

_x000D_
_x000D_
var days = 2;_x000D_
var newDate = new Date(Date.now()+days*24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
_x000D_
_x000D_

How to increase the Java stack size?

Other posters have pointed out how to increase memory and that you could memoize calls. I'd suggest that for many applications, you can use Stirling's formula to approximate large n! very quickly with almost no memory footprint.

Take a gander at this post, which has some analysis of the function and code:

http://threebrothers.org/brendan/blog/stirlings-approximation-formula-clojure/

How to fill Matrix with zeros in OpenCV?

If You are more into programming with templates, You may also do it this way...

template<typename _Tp>
... some algo ...
cv::Mat mat = cv::Mat_<_Tp>::zeros(rows, cols);
mat.at<_Tp>(i, j) = val;

Initializing a member array in constructor initializer

How about

...
  C() : arr{ {1,2,3} }
{}
...

?

Compiles fine on g++ 4.8

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

Note: the solution in this and other answers involves disabling safety measures that are there to fix arbitrary code execution vulnerabilities. See for instance this ghostscript-related and this ubuntu-related announcement. Only go forward with these solutions if the input to convert comes from a trusted source.

I use ImageMagick in php (v.7.1) to slice PDF file to images.

First I got errors like:

Exception type: ImagickException

Exception message: not authorized ..... @ error/constitute.c/ReadImage/412

After some changes in /etc/ImageMagick-6/policy.xml I start getting erroes like:

Exception type: ImagickException

Exception message: unable to create temporary file ..... Permission denied @ error/pdf.c/ReadPDFImage/465

My fix:

In file /etc/ImageMagick-6/policy.xml (or /etc/ImageMagick/policy.xml)

  1. comment line

    <!-- <policy domain="coder" rights="none" pattern="MVG" /> -->
    
  2. change line

    <policy domain="coder" rights="none" pattern="PDF" />
    

    to

    <policy domain="coder" rights="read|write" pattern="PDF" />
    
  3. add line

    <policy domain="coder" rights="read|write" pattern="LABEL" />
    

Then restart your web server (nginx, apache).

Using awk to print all columns from the nth to the last

Awk examples looks complex here, here is simple Bash shell syntax:

command | while read -a cols; do echo ${cols[@]:1}; done

Where 1 is your nth column counting from 0.


Example

Given this content of file (in.txt):

c1
c1 c2
c1 c2 c3
c1 c2 c3 c4
c1 c2 c3 c4 c5

here is the output:

$ while read -a cols; do echo ${cols[@]:1}; done < in.txt 

c2
c2 c3
c2 c3 c4
c2 c3 c4 c5

How do you implement a circular buffer in C?

C style, simple ring buffer for integers. First use init than use put and get. If buffer does not contain any data it returns "0" zero.

//=====================================
// ring buffer address based
//=====================================
#define cRingBufCount   512
int     sRingBuf[cRingBufCount];    // Ring Buffer
int     sRingBufPut;                // Input index address
int     sRingBufGet;                // Output index address
Bool    sRingOverWrite;

void    GetRingBufCount(void)
{
int     r;
`       r= sRingBufPut - sRingBufGet;
        if ( r < cRingBufCount ) r+= cRingBufCount;
        return r; 
}

void    InitRingBuffer(void)
{
        sRingBufPut= 0;
        sRingBufGet= 0;
}       

void    PutRingBuffer(int d)
{
        sRingBuffer[sRingBufPut]= d;
        if (sRingBufPut==sRingBufGet)// both address are like ziro
        {
            sRingBufPut= IncRingBufferPointer(sRingBufPut);
            sRingBufGet= IncRingBufferPointer(sRingBufGet);
        }
        else //Put over write a data
        {
            sRingBufPut= IncRingBufferPointer(sRingBufPut);
            if (sRingBufPut==sRingBufGet)
            {
                sRingOverWrite= Ture;
                sRingBufGet= IncRingBufferPointer(sRingBufGet);
            }
        }
}

int     GetRingBuffer(void)
{
int     r;
        if (sRingBufGet==sRingBufPut) return 0;
        r= sRingBuf[sRingBufGet];
        sRingBufGet= IncRingBufferPointer(sRingBufGet);
        sRingOverWrite=False;
        return r;
}

int     IncRingBufferPointer(int a)
{
        a+= 1;
        if (a>= cRingBufCount) a= 0;
        return a;
}

Can I configure a subdomain to point to a specific port on my server

I... don't think so. You can redirect the subdomain (such as blah.something.com) to point to something.com:25566, but I don't think you can actually set up the subdomain to be on a different port like that. I could be wrong, but it'd probably be easier to use a simple .htaccess or something to check %{HTTP_HOST} and redirect according to the subdomain.

Best way to check for "empty or null value"

The expression stringexpression = '' yields:

TRUE   .. for '' (or for any string consisting of only spaces with the data type char(n))
NULL   .. for NULL
FALSE .. for anything else

So to check for: "stringexpression is either NULL or empty":

(stringexpression = '') IS NOT FALSE

Or the reverse approach (may be easier to read):

(stringexpression <> '') IS NOT TRUE

Works for any character type including char(n). The manual about comparison operators.

Or use your original expression without trim(), which is costly noise for char(n) (see below), or incorrect for other character types: strings consisting of only spaces would pass as empty string.

coalesce(stringexpression, '') = ''

But the expressions at the top are faster.

Asserting the opposite is even simpler: "stringexpression is neither NULL nor empty":

stringexpression <> ''

About char(n)

This is about the data type char(n), short for: character(n). (char / character are short for char(1) / character(1).) Its use is discouraged in Postgres:

In most situations text or character varying should be used instead.

Do not confuse char(n) with other, useful, character types varchar(n), varchar, text or "char" (with double-quotes).

In char(n) an empty string is not different from any other string consisting of only spaces. All of these are folded to n spaces in char(n) per definition of the type. It follows logically that the above expressions work for char(n) as well - just as much as these (which wouldn't work for other character types):

coalesce(stringexpression, '  ') = '  '
coalesce(stringexpression, '') = '       '

Demo

Empty string equals any string of spaces when cast to char(n):

SELECT ''::char(5) = ''::char(5)     AS eq1
     , ''::char(5) = '  '::char(5)   AS eq2
     , ''::char(5) = '    '::char(5) AS eq3;

Result:

 eq1 | eq2 | eq3
 ----+-----+----
 t   | t   | t

Test for "null or empty string" with char(n):

SELECT stringexpression 
     , stringexpression = ''                   AS base_test
     , (stringexpression = '')  IS NOT FALSE   AS test1
     , (stringexpression <> '') IS NOT TRUE    AS test2
     , coalesce(stringexpression, '') = ''     AS coalesce1
     , coalesce(stringexpression, '  ') = '  ' AS coalesce2
     , coalesce(stringexpression, '') = '  '   AS coalesce3
FROM  (
   VALUES
     ('foo'::char(5))
   , ('')
   , ('   ')                -- not different from '' in char(n)
   , (NULL)
   ) sub(stringexpression);

Result:

 stringexpression | base_test | test1 | test2 | coalesce1 | coalesce2 | coalesce3 
------------------+-----------+-------+-------+-----------+-----------+-----------
 foo              | f         | f     | f     | f         | f         | f
                  | t         | t     | t     | t         | t         | t
                  | t         | t     | t     | t         | t         | t
 null             | null      | t     | t     | t         | t         | t

Test for "null or empty string" with text:

SELECT stringexpression 
     , stringexpression = ''                   AS base_test
     , (stringexpression = '')  IS NOT FALSE   AS test1
     , (stringexpression <> '') IS NOT TRUE    AS test2
     , coalesce(stringexpression, '') = ''     AS coalesce1
     , coalesce(stringexpression, '  ') = '  ' AS coalesce2
     , coalesce(stringexpression, '') = '  '   AS coalesce3
FROM  (
   VALUES
     ('foo'::text)
   , ('')
   , ('   ')                -- different from '' in a sane character types
   , (NULL)
   ) sub(stringexpression);

Result:

 stringexpression | base_test | test1 | test2 | coalesce1 | coalesce2 | coalesce3 
------------------+-----------+-------+-------+-----------+-----------+-----------
 foo              | f         | f     | f     | f         | f         | f
                  | t         | t     | t     | t         | f         | f
                  | f         | f     | f     | f         | f         | f
 null             | null      | t     | t     | t         | t         | f

db<>fiddle here
Old sqlfiddle

Related:

How to convert 'binary string' to normal string in Python3?

Please, see oficial encode() and decode() documentation from codecs library. utf-8 is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1 or utf_32.

VBA (Excel) Initialize Entire Array without Looping

This function works with variables for size and initial value it combines tbur & Filipe responses.

Function ArrayIniValue(iSize As Integer, iValue As Integer)
Dim sIndex As String
sIndex = "INDEX(Row(1:" & iSize & "),)"
ArrayIniValue = Evaluate("=Transpose(" & sIndex & "-" & sIndex & "+" & iValue & ")")
End Function

Called this way:

myArray = ArrayIniValue(350, 13)

cannot find module "lodash"

Reinstall 'browser-sync' :

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

SMTPAuthenticationError when sending mail using gmail and python

Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct

EDIT: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:

Go to this link and select Turn On
https://www.google.com/settings/security/lesssecureapps

How can I get relative path of the folders in my android project?

With System.getProperty("user.dir") you get the "Base of non-absolute paths" look at

Java Library Description

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

I have tried many options and unsure as to why a few solutions suggested above work on one machine and not on others.

A solution that works and that is simple and can work per container is:

docker run --ulimit memlock=819200000:819200000 -h <docker_host_name> --name=current -v /home/user_home:/user_home -i -d -t docker_user_name/image_name

How to read barcodes with the camera on Android?

I had an issue with the parseActivityForResult arguments. I got this to work:

package JMA.BarCodeScanner;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class JMABarcodeScannerActivity extends Activity {

    Button captureButton;
    TextView tvContents;
    TextView tvFormat;
    Activity activity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        activity = this;
        captureButton = (Button)findViewById(R.id.capture);
        captureButton.setOnClickListener(listener);
        tvContents = (TextView)findViewById(R.id.tvContents);
        tvFormat = (TextView)findViewById(R.id.tvFormat);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) 
    {  
        switch (requestCode) 
        {
            case IntentIntegrator.REQUEST_CODE:
            if (resultCode == Activity.RESULT_OK) 
            {
                IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);

                if (intentResult != null) 
                {
                   String contents = intentResult.getContents();
                   String format = intentResult.getFormatName();
                   tvContents.setText(contents.toString());
                   tvFormat.setText(format.toString());

                   //this.elemQuery.setText(contents);
                   //this.resume = false;
                   Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
                } else {
                    Log.e("SEARCH_EAN", "IntentResult je NULL!");
                }
            } 
            else if (resultCode == Activity.RESULT_CANCELED) {
                Log.e("SEARCH_EAN", "CANCEL");
            }
        }
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             IntentIntegrator integrator = new IntentIntegrator(activity);
             integrator.initiateScan();
        }
    };
}

Latyout for Activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/capture"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Take a Picture"/>

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tvContents"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tvFormat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

How to Display blob (.pdf) in an AngularJS app

I faced difficulties using "window.URL" with Opera Browser as it would result to "undefined". Also, with window.URL, the PDF document never opened in Internet Explorer and Microsoft Edge (it would remain waiting forever). I came up with the following solution that works in IE, Edge, Firefox, Chrome and Opera (have not tested with Safari):

$http.post(postUrl, data, {responseType: 'arraybuffer'})
.success(success).error(failed);

function success(data) {
   openPDF(data.data, "myPDFdoc.pdf");
};

function failed(error) {...};

function openPDF(resData, fileName) {
    var ieEDGE = navigator.userAgent.match(/Edge/g);
    var ie = navigator.userAgent.match(/.NET/g); // IE 11+
    var oldIE = navigator.userAgent.match(/MSIE/g); 

    var blob = new window.Blob([resData], { type: 'application/pdf' });

    if (ie || oldIE || ieEDGE) {
       window.navigator.msSaveBlob(blob, fileName);
    }
    else {
       var reader = new window.FileReader();
       reader.onloadend = function () {
          window.location.href = reader.result;
       };
       reader.readAsDataURL(blob);
    }
}

Let me know if it helped! :)

C# "No suitable method found to override." -- but there is one

You cannot override a function with different parameters, only you are allowed to change the functionality of the overridden method.

//Compiler Microsoft (R) .NET Framework 4.5

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

//Overriding & overloading

namespace polymorpism
{
    public class Program
    {
        public static void Main(string[] args)
        {

            drowButn calobj = new drowButn();

            BtnOverride calobjOvrid = new BtnOverride();

            Console.WriteLine(calobj.btn(5.2, 6.6).ToString());

            //btn has compleately overrided inside this calobjOvrid object
            Console.WriteLine(calobjOvrid.btn(5.2, 6.6).ToString());
            //the overloaded function
            Console.WriteLine(calobjOvrid.btn(new double[] { 5.2, 6.6 }).ToString());

            Console.ReadKey();
        }
    }

    public class drowButn
    {

        //same add function overloading to add double type field inputs
        public virtual double btn(double num1, double num2)
        {

            return (num1 + num2);

        }


    }

    public class BtnOverride : drowButn
    {

        //same add function overrided and change its functionality 
        //(this will compleately replace the base class function
        public override double btn(double num1, double num2)
        {
            //do compleatly diffarant function then the base class
            return (num1 * num2);

        }

        //same function overloaded (no override keyword used) 
        // this will not effect the base class function

        public double btn(double[] num)
        {
            double cal = 0;

            foreach (double elmnt in num)
            {

                cal += elmnt;
            }
            return cal;

        }
    }
}

In C, how should I read a text file and print all strings

Instead just directly print the characters onto the console because the text file maybe very large and you may require a lot of memory.

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

int main() {

    FILE *f;
    char c;
    f=fopen("test.txt","rt");

    while((c=fgetc(f))!=EOF){
        printf("%c",c);
    }

    fclose(f);
    return 0;
}

Split long commands in multiple lines through Windows batch file

You can break up long lines with the caret ^ as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)

Example:

copy file1.txt file2.txt

would be written as:

copy file1.txt^
 file2.txt

Is there an arraylist in Javascript?

With javascript all arrays are flexible. You can simply do something like the following:

var myArray = [];

myArray.push(object);
myArray.push(anotherObject);
// ...

How to sort List of objects by some property

Guava's ComparisonChain:

Collections.sort(list, new Comparator<ActiveAlarm>(){
            @Override
            public int compare(ActiveAlarm a1, ActiveAlarm a2) {
                 return ComparisonChain.start()
                       .compare(a1.timestarted, a2.timestarted)
                       //...
                       .compare(a1.timeEnded, a1.timeEnded).result();
            }});

How to check whether the user uploaded a file in PHP?

I checked your code and think you should try this:

if(!file_exists($_FILES['fileupload']['tmp_name']) || !is_uploaded_file($_FILES['fileupload']['tmp_name'])) 
    {
        echo 'No upload';
    }   
    else
        echo 'upload';

Nested Git repositories?

Summary.

Can I nest git repositories?

Yes. However, by default git does not track the .git folder of the nested repository. Git has features designed to manage nested repositories (read on).

Does it make sense to git init/add the /project_root to ease management of everything locally or do I have to manage my_project and the 3rd party one separately?

It probably doesn't make sense as git has features to manage nested repositories. Git's built in features to manage nested repositories are submodule and subtree.

Here is a blog on the topic and here is a SO question that covers the pros and cons of using each.

Why does multiplication repeats the number several times?

You cannot multiply an integer by a string. To be sure, you could try using the int (short for integer which means whole number) command, like this for example -

firstNumber = int(9)
secondNumber = int(1)
answer = (firstNumber*secondNumber)

Hope that helped :)

How to do a JUnit assert on a message in a logger

I answered a similar question for log4j see how-can-i-test-with-junit-that-a-warning-was-logged-with-log4

This is newer and example with Log4j2 (tested with 2.11.2) and junit 5;

    package com.whatever.log;

    import org.apache.logging.log4j.Level;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.core.Logger;
    import org.apache.logging.log4j.core.*;
    import org.apache.logging.log4j.core.appender.AbstractAppender;
    import org.apache.logging.log4j.core.config.Configuration;
    import org.apache.logging.log4j.core.config.LoggerConfig;
    import org.apache.logging.log4j.core.config.plugins.Plugin;
    import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
    import org.apache.logging.log4j.core.config.plugins.PluginElement;
    import org.apache.logging.log4j.core.config.plugins.PluginFactory;
    import org.junit.jupiter.api.AfterEach;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.DisplayName;
    import org.junit.jupiter.api.Test;

    import java.util.ArrayList;
    import java.util.List;
    import static org.junit.Assert.*;

class TestLogger {

    private TestAppender testAppender;
    private LoggerConfig loggerConfig;
    private final Logger logger = (Logger)
            LogManager.getLogger(ClassUnderTest.class);

    @Test
    @DisplayName("Test Log Junit5 and log4j2")
    void test() {
        ClassUnderTest.logMessage();
        final LogEvent loggingEvent = testAppender.events.get(0);
        //asset equals 1 because log level is info, change it to debug and
        //the test will fail
        assertTrue(testAppender.events.size()==1,"Unexpected empty log");
        assertEquals(Level.INFO,loggingEvent.getLevel(),"Unexpected log level");
        assertEquals(loggingEvent.getMessage().toString()
                ,"Hello Test","Unexpected log message");
    }

    @BeforeEach
    private void setup() {
        testAppender = new TestAppender("TestAppender", null);

        final LoggerContext context = logger.getContext();
        final Configuration configuration = context.getConfiguration();

        loggerConfig = configuration.getLoggerConfig(logger.getName());
        loggerConfig.setLevel(Level.INFO);
        loggerConfig.addAppender(testAppender,Level.INFO,null);
        testAppender.start();
        context.updateLoggers();
    }

    @AfterEach
    void after(){
        testAppender.stop();
        loggerConfig.removeAppender("TestAppender");
        final LoggerContext context = logger.getContext();
        context.updateLoggers();
    }

    @Plugin( name = "TestAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE)
    static class TestAppender extends AbstractAppender {

        List<LogEvent> events = new ArrayList();

        protected TestAppender(String name, Filter filter) {
            super(name, filter, null);
        }

        @PluginFactory
        public static TestAppender createAppender(
                @PluginAttribute("name") String name,
                @PluginElement("Filter") Filter filter) {
            return new TestAppender(name, filter);
        }

        @Override
        public void append(LogEvent event) {
            events.add(event);
        }
    }

    static class ClassUnderTest {
        private static final Logger LOGGER =  (Logger) LogManager.getLogger(ClassUnderTest.class);
        public static void logMessage(){
            LOGGER.info("Hello Test");
            LOGGER.debug("Hello Test");
        }
    }
}

Using the following maven dependencies

 <dependency>
 <artifactId>log4j-core</artifactId>
  <packaging>jar</packaging>
  <version>2.11.2</version>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.5.0</version>
    <scope>test</scope>
</dependency>

Find the similarity metric between two strings

Solution #1: Python builtin

use SequenceMatcher from difflib

pros: native python library, no need extra package.
cons: too limited, there are so many other good algorithms for string similarity out there.

example :
>>> from difflib import SequenceMatcher
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75

Solution #2: jellyfish library

its a very good library with good coverage and few issues. it supports:
- Levenshtein Distance
- Damerau-Levenshtein Distance
- Jaro Distance
- Jaro-Winkler Distance
- Match Rating Approach Comparison
- Hamming Distance

pros: easy to use, gamut of supported algorithms, tested.
cons: not native library.

example:

>>> import jellyfish
>>> jellyfish.levenshtein_distance(u'jellyfish', u'smellyfish')
2
>>> jellyfish.jaro_distance(u'jellyfish', u'smellyfish')
0.89629629629629637
>>> jellyfish.damerau_levenshtein_distance(u'jellyfish', u'jellyfihs')
1

How to see my Eclipse version?

I believe you can find out Eclipse Platform version for every software product that is Eclipse-based.

  1. Open Installation Details:

    • Go to Help => About => Installation Details.
    • Or to Help => Install New Software... => click What is already installed? link.
  2. Choose Plug-ins tab => type org.eclipse.platform => check Version column.

  3. You can match version code and version name on https://wiki.eclipse.org/Older_Versions_Of_Eclipse

For example, check out GitEye (Git GUI client) GitEye Installation Details

Or checkout DBBeaver (DB manager):

enter image description here

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

I had the same problem, I used Public DNS instead of Public IP. It resolved now.

Adb install failure: INSTALL_CANCELED_BY_USER

Its a Xiaomi's issue If possible update MIUI to latest version then go to Settings > Additional Settings > Developer Options > Developer options: Check the Install via USB option.

This solved my issue hope it will also solve yours good luck!

How can I do a BEFORE UPDATED trigger with sql server?

All "normal" triggers in SQL Server are "AFTER ..." triggers. There are no "BEFORE ..." triggers.

To do something before an update, check out INSTEAD OF UPDATE Triggers.

How to scroll to the bottom of a UITableView on the iPhone before the view appears

For Swift 3 ( Xcode 8.1 ):

override func viewDidAppear(_ animated: Bool) {
    let numberOfSections = self.tableView.numberOfSections
    let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)

    let indexPath = IndexPath(row: numberOfRows-1 , section: numberOfSections-1)
    self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.middle, animated: true)
}

Why does Java have an "unreachable statement" compiler error?

There is no definitive reason why unreachable statements must be not be allowed; other languages allow them without problems. For your specific need, this is the usual trick:

if (true) return;

It looks nonsensical, anyone who reads the code will guess that it must have been done deliberately, not a careless mistake of leaving the rest of statements unreachable.

Java has a little bit support for "conditional compilation"

http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.21

if (false) { x=3; }

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

and then write code such as:

if (DEBUG) { x=3; }

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

How to get the URL without any parameters in JavaScript?

Use indexOf

var url = "http://mysite.com/somedir/somefile/?aa";

if (url.indexOf("?")>-1){
url = url.substr(0,url.indexOf("?"));
}

Percentage width in a RelativeLayout

Update

As pointed by @EmJiHash PercentRelativeLayout and PercentFrameLayout is deprecated in API level 26.0.0

Consider Using ConstraintLayout

Google introduced new API called android.support.percent

1)PercentRelativeLayout

2)PercentFrameLayout

Add compile dependency like

compile 'com.android.support:percent:23.1.1'

You can specify dimension in percentage so get both benefit of RelativeLayout and percentage

 <android.support.percent.PercentRelativeLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:app="http://schemas.android.com/apk/res-auto"
         android:layout_width="match_parent"
         android:layout_height="match_parent"/>
     <TextView
         app:layout_widthPercent="40%"
         app:layout_heightPercent="40%"
         app:layout_marginTopPercent="15%"
         app:layout_marginLeftPercent="15%"/>
 </android.support.percent.PercentRelativeLayout/>

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Difference between logger.info and logger.debug

I suggest you look at the article called "Short Introduction to log4j". It contains a short explanation of log levels and demonstrates how they can be used in practice. The basic idea of log levels is that you want to be able to configure how much detail the logs contain depending on the situation. For example, if you are trying to troubleshoot an issue, you would want the logs to be very verbose. In production, you might only want to see warnings and errors.

The log level for each component of your system is usually controlled through a parameter in a configuration file, so it's easy to change. Your code would contain various logging statements with different levels. When responding to an Exception, you might call Logger.error. If you want to print the value of a variable at any given point, you might call Logger.debug. This combination of a configurable logging level and logging statements within your program allow you full control over how your application will log its activity.

In the case of log4j at least, the ordering of log levels is:

DEBUG < INFO < WARN < ERROR < FATAL

Here is a short example from that article demonstrating how log levels work.

   // get a logger instance named "com.foo"
   Logger logger = Logger.getLogger("com.foo");

   // Now set its level. Normally you do not need to set the
   // level of a logger programmatically. This is usually done
   // in configuration files.
   logger.setLevel(Level.INFO);

   Logger barlogger = Logger.getLogger("com.foo.Bar");

   // This request is enabled, because WARN >= INFO.
   logger.warn("Low fuel level.");

   // This request is disabled, because DEBUG < INFO.
   logger.debug("Starting search for nearest gas station.");

   // The logger instance barlogger, named "com.foo.Bar",
   // will inherit its level from the logger named
   // "com.foo" Thus, the following request is enabled
   // because INFO >= INFO.
   barlogger.info("Located nearest gas station.");

   // This request is disabled, because DEBUG < INFO.
   barlogger.debug("Exiting gas station search");

To switch from vertical split to horizontal split fast in Vim

In VIM, take a look at the following to see different alternatives for what you might have done:

:help opening-window

For instance:

Ctrl-W s
Ctrl-W o
Ctrl-W v
Ctrl-W o
Ctrl-W s
...

How to give Jenkins more heap space when it´s started as a service under Windows?

In your Jenkins installation directory there is a jenkins.xml, where you can set various options. Add the parameter -Xmx with the size you want to the arguments-tag (or increase the size if its already there).

Changing .gitconfig location on Windows

If you set HOME to c:\my_configuration_files\, then git will locate .gitconfig there. Editing environment variables is described here. You need to set the HOME variable, then re-open any cmd.exe window. Use the "set" command to verify that HOME indeed points to the right value.

Changing HOME will, of course, also affect other applications. However, from reading git's source code, that appears to be the only way to change the location of these files without the need to adjust the command line. You should also consider Stefan's response: you can set the GIT_CONFIG variable. However, to give it the effect you desire, you need to pass the --global flag to all git invocations (plus any local .git/config files are ignored).

Bootstrap: adding gaps between divs

An alternative way to accomplish what you are asking, without having problems on the mobile version of your website, (Remember that the margin attribute will brake your responsive layout on mobile version thus you have to add on your element a supplementary attribute like @media (min-width:768px){ 'your-class'{margin:0}} to override the previous margin)

is to nest your class in your preferred div and then add on your class the margin option you want

like the following example: HTML

<div class="container">
  <div class="col-md-3 col-xs-12">
   <div class="events">
     <img src="..."  class="img-responsive" alt="...."/>
     <div class="figcaption">
       <h2>Event Title</h2>
       <p>Event Description.</p>
     </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
</div>

And on your CSS you just add the margin option on your class which in this example is "events" like:

.events{
margin: 20px 10px;
}

By this method you will have all the wanted space between your divs making sure you do not brake anything on your website's mobile and tablet versions.

geom_smooth() what are the methods available?

Sometimes it's asking the question that makes the answer jump out. The methods and extra arguments are listed on the ggplot2 wiki stat_smooth page.

Which is alluded to on the geom_smooth() page with:

"See stat_smooth for examples of using built in model fitting if you need some more flexible, this example shows you how to plot the fits from any model of your choosing".

It's not the first time I've seen arguments in examples for ggplot graphs that aren't specifically in the function. It does make it tough to work out the scope of each function, or maybe I am yet to stumble upon a magic explicit list that says what will and will not work within each function.

Get last field using awk substr

It should be a comment to the basename answer but I haven't enough point.

If you do not use double quotes, basename will not work with path where there is space character:

$ basename /home/foo/bar foo/bar.png
bar

ok with quotes " "

$ basename "/home/foo/bar foo/bar.png"
bar.png

file example

$ cat a
/home/parent/child 1/child 2/child 3/filename1
/home/parent/child 1/child2/filename2
/home/parent/child1/filename3

$ while read b ; do basename "$b" ; done < a
filename1
filename2
filename3

Automatically capture output of last command into a variable using Bash?

It's quite easy. Use back-quotes:

var=`find . -name foo.txt`

And then you can use that any time in the future

echo $var
mv $var /somewhere

get url content PHP

Use cURL,

Check if you have it via phpinfo();

And for the code:

function getHtml($url, $post = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    if(!empty($post)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    } 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

How to change font in ipython notebook

You can hover to .ipython folder (i.e. you can type $ ipython locate in your terminal/bash OR CMD.exe Prompt from your Anaconda Navigator to see where is your ipython is located)

Then, in .ipython, you will see profile_default directory which is the default one. This directory will have static/custom/custom.css file located.

You can now apply change to this custom.css file. There are a lot of styles in the custom.css file that you can use or search for. For example, you can see this link (which is my own customize custom.css file)

Basically, this custom.css file apply changes to your browser. You can use inspect elements in your ipython notebook to see which elements you want to change. Then, you can changes to the custom.css file. For example, you can add these chunk to change font in .CodeMirror pre to type Monaco

.CodeMirror pre {font-family: Monaco; font-size: 9pt;}

Note that now for Jupyter notebook version >= 4.1, the custom css file is moved to ~/.jupyter/custom/custom.css instead.

How do I get a TextBox to only accept numeric input in WPF?

I modified Rays answer to handle the highlighted text prior to checking the regular expression. I also adjusted the regular expression to only allow for two decimal places (currency).

private static readonly Regex _regex = new Regex(@"^[0-9]\d*(\.\d{0,2})?$");
private static bool IsTextAllowed(string text)
{
    return _regex.IsMatch(text);
}

private bool IsAllowed(TextBox tb, string text)
{
    bool isAllowed = true;
    if (tb != null)
    {
        string currentText = tb.Text;
        if (!string.IsNullOrEmpty(tb.SelectedText))
            currentText = currentText.Remove(tb.CaretIndex, tb.SelectedText.Length);
        isAllowed = IsTextAllowed(currentText.Insert(tb.CaretIndex, text));
    }
    return isAllowed;
}

private void Txt_PreviewCurrencyTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = !IsAllowed(sender as TextBox, e.Text);            
}


private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
    if (e.DataObject.GetDataPresent(typeof(String)))
    {
        String text = (String)e.DataObject.GetData(typeof(String));
        if (!IsAllowed(sender as TextBox, text))
            e.CancelCommand();
    }
    else
        e.CancelCommand();
}

And the xaml

<TextBox Name="Txt_Textbox" PreviewTextInput="Txt_PreviewCurrencyTextInput"  DataObject.Pasting="TextBoxPasting" />

Which characters need to be escaped in HTML?

If you're inserting text content in your document in a location where text content is expected1, you typically only need to escape the same characters as you would in XML. Inside of an element, this just includes the entity escape ampersand & and the element delimiter less-than and greater-than signs < >:

& becomes &amp;
< becomes &lt;
> becomes &gt;

Inside of attribute values you must also escape the quote character you're using:

" becomes &quot;
' becomes &#39;

In some cases it may be safe to skip escaping some of these characters, but I encourage you to escape all five in all cases to reduce the chance of making a mistake.

If your document encoding does not support all of the characters that you're using, such as if you're trying to use emoji in an ASCII-encoded document, you also need to escape those. Most documents these days are encoded using the fully Unicode-supporting UTF-8 encoding where this won't be necessary.

In general, you should not escape spaces as &nbsp;. &nbsp; is not a normal space, it's a non-breaking space. You can use these instead of normal spaces to prevent a line break from being inserted between two words, or to insert          extra        space       without it being automatically collapsed, but this is usually a rare case. Don't do this unless you have a design constraint that requires it.


1 By "a location where text content is expected", I mean inside of an element or quoted attribute value where normal parsing rules apply. For example: <p>HERE</p> or <p title="HERE">...</p>. What I wrote above does not apply to content that has special parsing rules or meaning, such as inside of a script or style tag, or as an element or attribute name. For example: <NOT-HERE>...</NOT-HERE>, <script>NOT-HERE</script>, <style>NOT-HERE</style>, or <p NOT-HERE="...">...</p>.

In these contexts, the rules are more complicated and it's much easier to introduce a security vulnerability. I strongly discourage you from ever inserting dynamic content in any of these locations. I have seen teams of competent security-aware developers introduce vulnerabilities by assuming that they had encoded these values correctly, but missing an edge case. There's usually a safer alternative, such as putting the dynamic value in an attribute and then handling it with JavaScript.

If you must, please read the Open Web Application Security Project's XSS Prevention Rules to help understand some of the concerns you will need to keep in mind.

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

This thread is a bit older but here something I just came across:

Try this code:

$date = new DateTime();
$arr = ['date' => $date];

echo $date->format('Ymd') . '<br>';
mytest($arr);
echo $date->format('Ymd') . '<br>';

function mytest($params = []) {
    if (isset($params['date'])) {
        $params['date']->add(new DateInterval('P1D'));
    }
}

http://codepad.viper-7.com/gwPYMw

Note there is no amp for the $params parameter and still it changes the value of $arr['date']. This doesn't really match with all the other explanations here and what I thought until now.

If I clone the $params['date'] object, the 2nd outputted date stays the same. If I just set it to a string it doesn't effect the output either.

Checking if a key exists in a JS object

That's not a jQuery object, it's just an object.

You can use the hasOwnProperty method to check for a key:

if (obj.hasOwnProperty("key1")) {
  ...
}

Is it possible to compile a program written in Python?

Python, as a dynamic language, cannot be "compiled" into machine code statically, like C or COBOL can. You'll always need an interpreter to execute the code, which, by definition in the language, is a dynamic operation.

You can "translate" source code in bytecode, which is just an intermediate process that the interpreter does to speed up the load of the code, It converts text files, with comments, blank spaces, words like 'if', 'def', 'in', etc in binary code, but the operations behind are exactly the same, in Python, not in machine code or any other language. This is what it's stored in .pyc files and it's also portable between architectures.

Probably what you need it's not "compile" the code (which it's not possible) but to "embed" an interpreter (in the right architecture) with the code to allow running the code without an external installation of the interpreter. To do that, you can use all those tools like py2exe or cx_Freeze.

Maybe I'm being a little pedantic on this :-P

System.Security.SecurityException when writing to Event Log

try below in web.config

 <system.web>

<trust level="Full"/>

</system.web>

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Android Open External Storage directory(sdcard) for storing file

yes, it may work in KITKAT.

above KITKAT+ it will go to internal storage:paths like(storage/emulated/0).

please think, how "Xender app" give permission to write in to external sd card.

So, Fortunately in Android 5.0 and later there is a new official way for apps to write to the external SD card. Apps must ask the user to grant write access to a folder on the SD card. They open a system folder chooser dialog. The user need to navigate into that specific folder and select it.

for more details, please refer https://metactrl.com/docs/sdcard-on-lollipop/

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

You can do the following to install java 8 on your machine. First get the link of tar that you want to install. You can do this by:

  1. go to java downloads page and find the appropriate download.
  2. Accept the license agreement and download it.
  3. In the download page in your browser right click and copy link address.

Then in your terminal:

$ cd /tmp
$ wget http://download.oracle.com/otn-pub/java/jdk/8u74-b02/jdk-8u74-linux-x64.tar.gz\?AuthParam\=1458001079_a6c78c74b34d63befd53037da604746c
$ tar xzf jdk-8u74-linux-x64.tar.gz?AuthParam=1458001079_a6c78c74b34d63befd53037da604746c
$ sudo mv jdk1.8.0_74 /opt
$ cd /opt/jdk1.8.0_74/
$ sudo update-alternatives --install /usr/bin/java java /opt/jdk1.8.0_91/bin/java 2
$ sudo update-alternatives --config java // select version
$ sudo update-alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_91/bin/jar 2
$ sudo update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_91/bin/javac 2
$ sudo update-alternatives --set jar /opt/jdk1.8.0_91/bin/jar
$ sudo update-alternatives --set javac /opt/jdk1.8.0_74/bin/javac
$ java -version // you should have the updated java

Why is __dirname not defined in node REPL?

If you are using Node.js modules, __dirname and __filename don't exist.

From the Node.js documentation:

No require, exports, module.exports, __filename, __dirname

These CommonJS variables are not available in ES modules.

require can be imported into an ES module using module.createRequire().

Equivalents of __filename and __dirname can be created inside of each file via import.meta.url:

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

https://nodejs.org/docs/latest-v15.x/api/esm.html#esm_no_filename_or_dirname

How can I clone a JavaScript object except for one key?

Here are my two cents, on Typescript, slightly derived from @Paul's answer and using reduce instead.

function objectWithoutKey(object: object, keys: string[]) {
    return keys.reduce((previousValue, currentValue) => {
        // @ts-ignore
        const {[currentValue]: undefined, ...clean} = previousValue;
        return clean
    }, object)
}

// usage
console.log(objectWithoutKey({a: 1, b: 2, c: 3}, ['a', 'b']))

"Unmappable character for encoding UTF-8" error

Thanks Michael Konietzka (https://stackoverflow.com/a/4996583/1019307) for your answer.

I did this in Eclipse / STS:

Preferences > General > Content Types > Selected "Text" 
    (which contains all types such as CSS, Java Source Files, ...)
Added "UTF-8" to the default encoding box down the bottom and hit 'Add'

Bingo, error gone!

How does DISTINCT work when using JPA and Hibernate

@Entity
@NamedQuery(name = "Customer.listUniqueNames", 
            query = "SELECT DISTINCT c.name FROM Customer c")
public class Customer {
        ...

        private String name;

        public static List<String> listUniqueNames() {
             return = getEntityManager().createNamedQuery(
                   "Customer.listUniqueNames", String.class)
                   .getResultList();
        }
}

Instantly detect client disconnection from server socket

Expanding on comments by mbargiel and mycelo on the accepted answer, the following can be used with a non-blocking socket on the server end to inform whether the client has shut down.

This approach does not suffer the race condition that affects the Poll method in the accepted answer.

// Determines whether the remote end has called Shutdown
public bool HasRemoteEndShutDown
{
    get
    {
        try
        {
            int bytesRead = socket.Receive(new byte[1], SocketFlags.Peek);

            if (bytesRead == 0)
                return true;
        }
        catch
        {
            // For a non-blocking socket, a SocketException with 
            // code 10035 (WSAEWOULDBLOCK) indicates no data available.
        }

        return false;
    }
}

The approach is based on the fact that the Socket.Receive method returns zero immediately after the remote end shuts down its socket and we've read all of the data from it. From Socket.Receive documentation:

If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.

If you are in non-blocking mode, and there is no data available in the protocol stack buffer, the Receive method will complete immediately and throw a SocketException.

The second point explains the need for the try-catch.

Use of the SocketFlags.Peek flag leaves any received data untouched for a separate receive mechanism to read.

The above will work with a blocking socket as well, but be aware that the code will block on the Receive call (until data is received or the receive timeout elapses, again resulting in a SocketException).

How to break lines at a specific character in Notepad++?

Let's assume ], is the character where we wanted to break at

  1. Open notePad++
  2. Open Find window Ctrl+F
  3. Switch to Replace Tab
  4. Choose Search Mode to Extended
  5. Type ], in Find What field
  6. Type \nin Replace with field
  7. Hit Replace All
  8. Boom

MomentJS getting JavaScript Date in UTC

Or simply:

Date.now

From MDN documentation:

The Date.now() method returns the number of milliseconds elapsed since January 1, 1970

Available since ECMAScript 5.1

It's the same as was mentioned above (new Date().getTime()), but more shortcutted version.

python global name 'self' is not defined

It should be something like:

class Person:
   def setavalue(self, name):         
      self.myname = name      
   def printaname(self):         
      print "Name", self.myname           

def main():
   p = Person()
   p.setavalue("harry")
   p.printaname()  

jquery if div id has children

if ( $('#myfav').children().length > 0 ) {
     // do something
}

This should work. The children() function returns a JQuery object that contains the children. So you just need to check the size and see if it has at least one child.

Notepad++ Regular expression find and delete a line

Provide the following in the search dialog:

Find What: ^$\r\n
Replace With: (Leave it empty)

Click Replace All

Unnamed/anonymous namespaces vs. static functions

A compiler specific difference between anonymous namespaces and static functions can be seen compiling the following code.

#include <iostream>

namespace
{
    void unreferenced()
    {
        std::cout << "Unreferenced";
    }

    void referenced()
    {
        std::cout << "Referenced";
    }
}

static void static_unreferenced()
{
    std::cout << "Unreferenced";
}

static void static_referenced()
{
    std::cout << "Referenced";
}

int main()
{
    referenced();
    static_referenced();
    return 0;
}

Compiling this code with VS 2017 (specifying the level 4 warning flag /W4 to enable warning C4505: unreferenced local function has been removed) and gcc 4.9 with the -Wunused-function or -Wall flag shows that VS 2017 will only produce a warning for the unused static function. gcc 4.9 and higher, as well as clang 3.3 and higher, will produce warnings for the unreferenced function in the namespace and also a warning for the unused static function.

Live demo of gcc 4.9 and MSVC 2017

Find and replace in file and overwrite file doesn't work, it empties the file

When the shell sees > index.html in the command line it opens the file index.html for writing, wiping off all its previous contents.

To fix this you need to pass the -i option to sed to make the changes inline and create a backup of the original file before it does the changes in-place:

sed -i.bak s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g index.html

Without the .bak the command will fail on some platforms, such as Mac OSX.

Randomize numbers with jQuery?

Others have answered the question, but just for the fun of it, here is a visual dice throwing example, using the Math.random javascript method, a background image and some recursive timeouts.

http://www.jsfiddle.net/zZUgF/3/

Can't connect to local MySQL server through socket homebrew

You'll need to run mysql_install_db - easiest way is if you're in the install directory:

$ cd /usr/local/Cellar/mysql/<version>/ 
$ mysql_install_db

Alternatively, you can feed mysql_install_db a basedir parameter like the following:

$ mysql_install_db --basedir="$(brew --prefix mysql)"

How to write a multidimensional array to a text file?

There exist special libraries to do just that. (Plus wrappers for python)

hope this helps

Twitter Bootstrap - borders

Another solution I ran across tonight, which worked for my needs, was to add box-sizing attributes:

-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;

These attributes force the border to be part of the box model's width and height and correct the issue as well.

According to caniuse.com » box-sizing, box-sizing is supported in IE8+.

If you're using LESS or Sass there is a Bootstrap mixin for this.

LESS:

.box-sizing(border-box);

Sass:

@include box-sizing(border-box);

How can you find out which process is listening on a TCP or UDP port on Windows?

The -b switch mentioned in most answers requires you to have administrative privileges on the machine. You don't really need elevated rights to get the process name!

Find the pid of the process running in the port number (e.g., 8080)

netstat -ano | findStr "8080"

Find the process name by pid

tasklist /fi "pid eq 2216"

find process by TCP/IP port

WAMP Cannot access on local network 403 Forbidden

If you are using WAMPServer 3 See bottom of answer

For WAMPServer versions <= 2.5

By default Wampserver comes configured as securely as it can, so Apache is set to only allow access from the machine running wamp. Afterall it is supposed to be a development server and not a live server.

Also there was a little error released with WAMPServer 2.4 where it used the old Apache 2.2 syntax instead of the new Apache 2.4 syntax for access rights.

You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf file.

Change this section from :

#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

To :

#   onlineoffline tag - don't remove
    Require local
    Require ip 192.168.0

The Require local allows access from these ip's 127.0.0.1 & localhost & ::1.

The statement Require ip 192.168.0 will allow you to access the Apache server from any ip on your internal network. Also it will allow access using the server mechines actual ip address from the server machine, as you are trying to do.

WAMPServer 3 has a different method

In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost so you have to make the access privilage amendements in the Virtual Host definition config file

First dont amend the httpd.conf file at all, leave it as you found it.

Using the menus, edit the httpd-vhosts.conf file.

enter image description here

It should look like this :

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

Amend it to

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Hopefully you will have created a Virtual Host for your project and not be using the wamp\www folder for your site. In that case leave the localhost definition alone and make the change only to your Virtual Host.

Dont forget to restart Apache after making this change

How to generate entire DDL of an Oracle schema (scriptable)?

To generate the DDL script for an entire SCHEMA i.e. a USER, you could use dbms_metadata.get_ddl.

Execute the following script in SQL*Plus created by Tim Hall:

Provide the username when prompted.

set long 20000 longchunksize 20000 pagesize 0 linesize 1000 feedback off verify off trimspool on
column ddl format a1000

begin
   dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'SQLTERMINATOR', true);
   dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'PRETTY', true);
end;
/

variable v_username VARCHAR2(30);

exec:v_username := upper('&1');

select dbms_metadata.get_ddl('USER', u.username) AS ddl
from   dba_users u
where  u.username = :v_username
union all
select dbms_metadata.get_granted_ddl('TABLESPACE_QUOTA', tq.username) AS ddl
from   dba_ts_quotas tq
where  tq.username = :v_username
and    rownum = 1
union all
select dbms_metadata.get_granted_ddl('ROLE_GRANT', rp.grantee) AS ddl
from   dba_role_privs rp
where  rp.grantee = :v_username
and    rownum = 1
union all
select dbms_metadata.get_granted_ddl('SYSTEM_GRANT', sp.grantee) AS ddl
from   dba_sys_privs sp
where  sp.grantee = :v_username
and    rownum = 1
union all
select dbms_metadata.get_granted_ddl('OBJECT_GRANT', tp.grantee) AS ddl
from   dba_tab_privs tp
where  tp.grantee = :v_username
and    rownum = 1
union all
select dbms_metadata.get_granted_ddl('DEFAULT_ROLE', rp.grantee) AS ddl
from   dba_role_privs rp
where  rp.grantee = :v_username
and    rp.default_role = 'YES'
and    rownum = 1
union all
select to_clob('/* Start profile creation script in case they are missing') AS ddl
from   dba_users u
where  u.username = :v_username
and    u.profile <> 'DEFAULT'
and    rownum = 1
union all
select dbms_metadata.get_ddl('PROFILE', u.profile) AS ddl
from   dba_users u
where  u.username = :v_username
and    u.profile <> 'DEFAULT'
union all
select to_clob('End profile creation script */') AS ddl
from   dba_users u
where  u.username = :v_username
and    u.profile <> 'DEFAULT'
and    rownum = 1
/

set linesize 80 pagesize 14 feedback on trimspool on verify on

Java SimpleDateFormat for time zone with a colon separator?

if you used the java 7, you could have used the following Date Time Pattern. Seems like this pattern is not supported in the Earlier version of java.

String dateTimeString  = "2010-03-01T00:00:00-08:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date date = df.parse(dateTimeString);

For More information refer to the SimpleDateFormat documentation.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

If you try to run 32-bit applications on IIS 7 (and/or 64-bit OS machine), you will get the same error. So, from the IIS 7, right click on the applications' application pool and go to "advanced settings" and change "Enable 32-Bit Applications" to "TRUE".

Restart your website and it should work.

enter image description here

html5 audio player - jquery toggle click play/pause?

Simply Use

$('audio').trigger('pause');

Now() function with time trim

DateValue(CStr(Now()))

That's the best I've found. If you have the date as a string already you can just do:

DateValue("12/04/2012 04:56:15")

or

DateValue(*DateStringHere*)

Hope this helps someone...

How to Save Console.WriteLine Output to Text File

do you want to write code for that or just use command-line feature 'command redirection' as follows:

app.exe >> output.txt

as demonstrated here: http://discomoose.org/2006/05/01/output-redirection-to-a-file-from-the-windows-command-line/ (Archived at archive.org)

EDIT: link dead, here's another example: http://pcsupport.about.com/od/commandlinereference/a/redirect-command-output-to-file.htm

Ignoring directories in Git repositories on Windows

Also in your \.git\info projects directory there is an exclude file that is effectively the same thing as .gitignore (I think). You can add files and directories to ignore in that.

How to set -source 1.7 in Android Studio and Gradle

Latest Android Studio 1.4.

Click File->Project Structure->SDK Location->JDK Location.

You could also set individual module JDK Version compatibility by going to the Module (below the SDK Location), and edit the Source Compatibility accordingly. (note, this only applies to Android Module).

How to print environment variables to the console in PowerShell?

In addition to Mathias answer.

Although not mentioned in OP, if you also need to see the Powershell specific/related internal variables, you need to use Get-Variable:

$ Get-Variable

Name                           Value
----                           -----
$                              name
?                              True
^                              gci
args                           {}
ChocolateyTabSettings          @{AllCommands=False}
ConfirmPreference              High
DebugPreference                SilentlyContinue
EnabledExperimentalFeatures    {}
Error                          {System.Management.Automation.ParseException: At line:1 char:1...
ErrorActionPreference          Continue
ErrorView                      NormalView
ExecutionContext               System.Management.Automation.EngineIntrinsics
false                          False
FormatEnumerationLimit         4
...

These also include stuff you may have set in your profile startup script.

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I found a faster way of embedding:

  • Just copy the link.
  • Paste the link and remove the "?s=19" part and add "/video/1"
  • That's it.

hibernate - get id after save object

By default, hibernate framework will immediately return id , when you are trying to save the entity using Save(entity) method. There is no need to do it explicitly.

In case your primary key is int you can use below code:

int id=(Integer) session.save(entity);

In case of string use below code:

String str=(String)session.save(entity);

Compare objects in Angular

I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.

BE MINDFUL, If you use angular.equals() on objects that have property obj.$something (property name starts with $) those properties will get ignored in comparison.

Example:

var obj1 = {
  $key0: "A",
  key1: "value1",
  key2: "value2",
  key3: {a: "aa", b: "bb"}
}

var obj2 = {
  $key0: "B"
  key2: "value2",
  key1: "value1",
  key3: {a: "aa", b: "bb"}
}

angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)

I need to learn Web Services in Java. What are the different types in it?

The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.

The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.

The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()

SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.

The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.

source http://java-success.blogspot.in/2012/02/java-web-services-interview-questions.html

How to find specified name and its value in JSON-string from Java?

Gson allows for one of the simplest possible solutions. Compared to similar APIs like Jackson or svenson, Gson by default doesn't even need the unused JSON elements to have bindings available in the Java structure. Specific to the question asked, here's a working solution.

import com.google.gson.Gson;

public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"name\":\"John\"," + 
      "\"age\":\"20\"," + 
      "\"address\":\"some address\"," + 
      "\"someobject\":" +
      "{" + 
        "\"field\":\"value\"" + 
      "}" + 
    "}";

  String age;

  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Foo thing = gson.fromJson(jsonInput, Foo.class);
    if (thing.age != null)
    {
      System.out.println("age is " + thing.age);
    }
    else
    {
      System.out.println("age element not present or value is null");
    }
  }
}

Selecting pandas column by location

You can access multiple columns by passing a list of column indices to dataFrame.ix.

For example:

>>> df = pandas.DataFrame({
             'a': np.random.rand(5),
             'b': np.random.rand(5),
             'c': np.random.rand(5),
             'd': np.random.rand(5)
         })

>>> df
          a         b         c         d
0  0.705718  0.414073  0.007040  0.889579
1  0.198005  0.520747  0.827818  0.366271
2  0.974552  0.667484  0.056246  0.524306
3  0.512126  0.775926  0.837896  0.955200
4  0.793203  0.686405  0.401596  0.544421

>>> df.ix[:,[1,3]]
          b         d
0  0.414073  0.889579
1  0.520747  0.366271
2  0.667484  0.524306
3  0.775926  0.955200
4  0.686405  0.544421

Change Volley timeout duration

Just to contribute with my approach. As already answered, RetryPolicy is the way to go. But if you need a policy different the than default for all your requests, you can set it in a base Request class, so you don't need to set the policy for all the instances of your requests.

Something like this:

public class BaseRequest<T> extends Request<T> {

    public BaseRequest(int method, String url, Response.ErrorListener listener) {
        super(method, url, listener);
        setRetryPolicy(getMyOwnDefaultRetryPolicy());
    }
}

In my case I have a GsonRequest which extends from this BaseRequest, so I don't run the risk of forgetting to set the policy for an specific request and you can still override it if some specific request requires to.

Adding click event for a button created dynamically using jQuery

Use

$(document).on("click", "#btn_a", function(){
  alert ('button clicked');
});

to add the listener for the dynamically created button.

alert($("#btn_a").val());

will give you the value of the button

Change application's starting activity

Follow to below instructions:

1:) Open your AndroidManifest.xml file.

2:) Go to the activity code which you want to make your main activity like below.

such as i want to make SplashScreen as main activity

<activity
    android:name=".SplashScreen"
    android:screenOrientation="sensorPortrait"
    android:label="City Retails">
</activity>

3:) Now copy the below code in between activity tags same as:

<activity
    android:name=".SplashScreen"
    android:screenOrientation="sensorPortrait"
    android:label="City Retails">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

and also check that newly added lines are not attached with other activity tags.

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

I encountered this issue with a misconfigured xcconfig file.

The Pods-generated xcconfig was not correctly #included in the customise xcconfig that I was using. This caused $PODS_ROOT to not be set resulting in the failure of diff "/../Podfile.lock" "/Manifest.lock", for obvious reasons, which Pods misinterprets as a sync issue.

How to terminate a thread when main program ends?

If you make your worker threads daemon threads, they will die when all your non-daemon threads (e.g. the main thread) have exited.

http://docs.python.org/library/threading.html#threading.Thread.daemon

String.Format for Hex

Translate composed UInt32 color Value to CSS in .NET

I know the question applies to 3 input values (red green blue). But there may be the situation where you already have a composed 32bit Value. It looks like you want to send the data to some HTML CSS renderer (because of the #HEX format). Actually CSS wants you to print 6 or at least 3 zero filled hex digits here. so #{0:X06} or #{0:X03} would be required. Due to some strange behaviour, this always prints 8 digits instead of 6.

Solve this by:

String.Format("#{0:X02}{1:X02}{2:X02}", (Value & 0x00FF0000) >> 16, (Value & 0x0000FF00) >> 8, (Value & 0x000000FF) >> 0)

Delete specific values from column with where condition?

You can also use REPLACE():

UPDATE Table
   SET Column = REPLACE(Column, 'Test123', 'Test')

How do I check whether an array contains a string in TypeScript?

You can use filter too

this.products = array_products.filter((x) => x.Name.includes("ABC"))

Exploitable PHP functions

You can find a continuously updated list of sensitive sinks (exploitable php functions) and their parameters in RIPS /config/sinks.php, a static source code analyser for vulnerabilities in PHP applications that also detects PHP backdoors.

Deep copy vs Shallow Copy

The quintessential example of this is an array of pointers to structs or objects (that are mutable).

A shallow copy copies the array and maintains references to the original objects.

A deep copy will copy (clone) the objects too so they bear no relation to the original. Implicit in this is that the object themselves are deep copied. This is where it gets hard because there's no real way to know if something was deep copied or not.

The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.

In order to read the details with complete examples and explanations you could see the article Constructors and destructors.

The default copy constructor is shallow. You can make your own copy constructors deep or shallow, as appropriate. See C++ Notes: OOP: Copy Constructors.

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

One missing difference is: std::unique_lock can be moved but std::lock_guard can't be moved.

Note: Both cant be copied.

"unrecognized import path" with go get

I had the same problem on MacOS 10.10. And I found that the problem caused by OhMyZsh shell. Then I switched back to bash everything went ok.

Here is my go env

bash-3.2$ go env
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/bis/go"
GORACE=""
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1

trying to align html button at the center of the my page

There are multiple ways to fix the same. PFB two of them -

1st Way using position: fixed - position: fixed; positions relative to the viewport, which means it always stays in the same place even if the page is scrolled. Adding the left and top value to 50% will place it into the middle of the screen.

 button {
   position: fixed;
   left: 50%;
   top:50%;
 }

2nd Way using margin: auto -margin: 0 auto; for horizontal centering, but margin: auto; has refused to work for vertical centering… until now! But actually absolute centering only requires a declared height and these styles:

button {
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 40px;
}

JavaScript and Threads

In raw Javascript, the best that you can do is using the few asynchronous calls (xmlhttprequest), but that's not really threading and very limited. Google Gears adds a number of APIs to the browser, some of which can be used for threading support.

Check whether variable is number or string in JavaScript

Try this,

<script>
var regInteger = /^-?\d+$/;

function isInteger( str ) {    
    return regInteger.test( str );
}

if(isInteger("1a11")) {
   console.log( 'Integer' );
} else {
   console.log( 'Non Integer' );
}
</script>

Inserting a PDF file in LaTeX

There is an option without additional packages that works under pdflatex

Adapt this code

\begin{figure}[h]
    \centering
    \includegraphics[width=\ScaleIfNeeded]{figuras/diagrama-spearman.pdf}
    \caption{Schematical view of Spearman's theory.}
\end{figure}

"diagrama-spearman.pdf" is a plot generated with TikZ and this is the code (it is another .tex file different from the .tex file where I want to insert a pdf)

\documentclass[border=3mm]{standalone}
\usepackage[applemac]{inputenc}
\usepackage[protrusion=true,expansion=true]{microtype}
\usepackage[bb=lucida,bbscaled=1,cal=boondoxo]{mathalfa}
\usepackage[stdmathitalics=true,math-style=iso,lucidasmallscale=true,romanfamily=bright]{lucimatx}
\usepackage{tikz}
\usetikzlibrary{intersections}
\newcommand{\at}{\makeatletter @\makeatother}

\begin{document}

\begin{tikzpicture}
\tikzset{venn circle/.style={draw,circle,minimum width=5cm,fill=#1,opacity=1}}
\node [venn circle = none, name path=A] (A) at (45:2cm) { };
\node [venn circle = none, name path=B] (B) at (135:2cm) { };
\node [venn circle = none, name path=C] (C) at (225:2cm) { };
\node [venn circle = none, name path=D] (D) at (315:2cm) { };
\node[above right] at (barycentric cs:A=1) {logical}; 
\node[above left] at (barycentric cs:B=1) {mechanical}; 
\node[below left] at (barycentric cs:C=1) {spatial}; 
\node[below right] at (barycentric cs:D=1) {arithmetical}; 
\node at (0,0) {G};    
\end{tikzpicture}

\end{document} 

This is the diagram I included

enter image description here

SQL SERVER: Get total days between two dates

You can try this MSDN link

DATEDIFF ( datepart , startdate , enddate )
SELECT DATEDIFF(DAY, '1/1/2011', '3/1/2011')

How to find the installed pandas version

Run

pip freeze

It works the same as above.

pip show pandas

Displays information about a specific package. For more information, check out pip help

How can I get the first two digits of a number?

You can convert your number to string and use list slicing like this:

int(str(number)[:2])

Output:

>>> number = 1520
>>> int(str(number)[:2])
15

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

Following are the steps that will definitely work:

  1. Open CMD : Press Windows+R from keyboard or just type "cmd" in windows search
  2. Type Following in cmd : netstat -aon | find ":8080" | find "LISTENING"
  3. See the last column : There will be some number like 2816 or similar.(It will differ from this)
  4. Now open Task Manager (Keyboard shortcut : Ctrl+Shift+Esc)
  5. In that, go to Details Tab and under PID Column, search for the number you found in step 3
  6. Right Click on it and select end process
  7. Now happily go to Netbeans and Run your program

NOTE : If you are running your program for the first time in Netbeans, it takes some time. So don't worry if it takes time.

How to comment lines in rails html.erb files?

Note that if you want to comment out a single line of printing erb you should do like this

<%#= ["Buck", "Papandreou"].join(" you ") %>

COALESCE Function in TSQL

I'm not sure why you think the documentation is vague.

It simply goes through all the parameters one by one, and returns the first that is NOT NULL.

COALESCE(NULL, NULL, NULL, 1, 2, 3)
=> 1


COALESCE(1, 2, 3, 4, 5, NULL)
=> 1


COALESCE(NULL, NULL, NULL, 3, 2, NULL)
=> 3


COALESCE(6, 5, 4, 3, 2, NULL)
=> 6


COALESCE(NULL, NULL, NULL, NULL, NULL, NULL)
=> NULL

It accepts pretty much any number of parameters, but they should be the same data-type. (If they're not the same data-type, they get implicitly cast to an appropriate data-type using data-type order of precedence.)

It's like ISNULL() but for multiple parameters, rather than just two.

It's also ANSI-SQL, where-as ISNULL() isn't.

Is it possible to add an array or object to SharedPreferences on Android

So from the android developer site on Data Storage:

User Preferences

Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).

So I think it is okay since it is simply just key-value pairs which are persisted.

To the original poster, this is not that hard. You simply just iterate through your array list and add the items. In this example I use a map for simplicity but you can use an array list and change it appropriately:

// my list of names, icon locations
Map<String, String> nameIcons = new HashMap<String, String>();
nameIcons.put("Noel", "/location/to/noel/icon.png");
nameIcons.put("Bob", "another/location/to/bob/icon.png");
nameIcons.put("another name", "last/location/icon.png");

SharedPreferences keyValues = getContext().getSharedPreferences("name_icons_list", Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();

for (String s : nameIcons.keySet()) {
    // use the name as the key, and the icon as the value
    keyValuesEditor.putString(s, nameIcons.get(s));
}
keyValuesEditor.commit()

You would do something similar to read the key-value pairs again. Let me know if this works.

Update: If you're using API level 11 or later, there is a method to write out a String Set

How can I reverse a list in Python?

Summary of Methods with Explanation and Timing Results

There are three different built-in ways to reverse a list. Which method is best depends on whether you need to:

  1. Reverse an existing list in-place (altering the original list variable)
    • Best solution is object.reverse() method
  2. Create an iterator of the reversed list (because you are going to feed it to a for-loop, a generator, etc.)
    • Best solution is reversed(object) which creates the iterator
  3. Create a copy of the list, just in the reverse order (to preserve the original list)
    • Best solution is using slices with a -1 step size: object[::-1]

From a speed perspective, it is best to use the built-in functions to reverse a list. In this case, they are 2 to 8 times faster on short lists (10 items), and up to ~300+ times faster on long lists compared to a manually-created loop or generator. This makes sense as they are written in a native language (i.e. C), have experts creating them, scrutiny, and optimization. They are also less prone to defects and more likely to handle edge and corner cases.

Test Script

Put all the code snippets in this answer together to make a script that will run the different ways of reversing a list that are described below. It will time each method while running it 100,000 times. The results are shown in the last section for lists of length 2, 10, and 1000 items.

from timeit import timeit
from copy import copy

def time_str_ms(t):
    return '{0:8.2f} ms'.format(t * 1000)

Method 1: Reverse in place with obj.reverse()

If the goal is just to reverse the order of the items in an existing list, without looping over them or getting a copy to work with, use the <list>.reverse() function. Run this directly on a list object, and the order of all items will be reversed:

Note that the following will reverse the original variable that is given, even though it also returns the reversed list back. i.e. you can create a copy by using this function output. Typically, you wouldn't make a function for this, but the timing script requires it.

We test the performance of this two ways - first just reversing a list in-place (changes the original list), and then copying the list and reversing it afterward to see if that is the fastest way to create a reversed copy compared to the other methods.

def rev_in_place(mylist):
    mylist.reverse()
    return mylist

def rev_copy_reverse(mylist):
    a = copy(mylist)
    a.reverse()
    return a

Method 2: Reverse a list using slices obj[::-1]

The built-in index slicing method allows you to make a copy of part of any indexed object.

  • It does not affect the original object
  • It builds a full list, not an iterator

The generic syntax is: <object>[first_index:last_index:step]. To exploit slicing to create a simple reversed list, use: <list>[::-1]. When leaving an option empty, it sets them to defaults of the first and last element of the object (reversed if the step size is negative).

Indexing allows one to use negative numbers, which count from the end of the object's index backwards (i.e. -2 is the second to last item). When the step size is negative, it will start with the last item and index backward by that amount.

def rev_slice(mylist):
    a = mylist[::-1]
    return a

Method 3: Reverse a list with the reversed(obj) iterator function

There is a reversed(indexed_object) function:

  • This creates a reverse index iterator, not a list. Great if you are feeding it to a loop for better performance on large lists
  • This creates a copy and does not affect the original object

Test with both a raw iterator, and creating a list from the iterator.

def reversed_iterator(mylist):
    a = reversed(mylist)
    return a

def reversed_with_list(mylist):
    a = list(reversed(mylist))
    return a

Method 4: Reverse list with Custom/Manual indexing

As the timing shows, creating your own methods of indexing is a bad idea. Use the built-in methods unless you really do need to do something custom. This simply means learning the built-in methods.

That said, there is not a huge penalty with smaller list sizes, but when you scale up the penalty becomes tremendous. The code below could be optimized, I'm sure, but it can't ever match the built-in methods as they are directly implemented in a native language.

def rev_manual_pos_gen(mylist):
    max_index = len(mylist) - 1
    return [ mylist[max_index - index] for index in range(len(mylist)) ]

def rev_manual_neg_gen(mylist):
    ## index is 0 to 9, but we need -1 to -10
    return [ mylist[-index-1] for index in range(len(mylist)) ]

def rev_manual_index_loop(mylist):
    a = []
    reverse_index = len(mylist) - 1
    for index in range(len(mylist)):
        a.append(mylist[reverse_index - index])
    return a
    
def rev_manual_loop(mylist):
    a = []
    reverse_index = len(mylist)
    for index, _ in enumerate(mylist):
        reverse_index -= 1
        a.append(mylist[reverse_index])
    return a

Timing each method

Following is the rest of the script to time each method of reversing. It shows reversing in place with obj.reverse() and creating the reversed(obj) iterator are always the fastest, while using slices is the fastest way to create a copy.

It also proves not to try to create a way of doing it on your own unless you have to!

loops_to_test = 100000
number_of_items = 10
list_to_reverse = list(range(number_of_items))
if number_of_items < 15:
    print("a: {}".format(list_to_reverse))
print('Loops: {:,}'.format(loops_to_test))
# List of the functions we want to test with the timer, in print order
fcns = [rev_in_place, reversed_iterator, rev_slice, rev_copy_reverse,
        reversed_with_list, rev_manual_pos_gen, rev_manual_neg_gen,
        rev_manual_index_loop, rev_manual_loop]
max_name_string = max([ len(fcn.__name__) for fcn in fcns ])
for fcn in fcns:
    a = copy(list_to_reverse) # copy to start fresh each loop
    out_str = ' | out = {}'.format(fcn(a)) if number_of_items < 15 else ''
    # Time in ms for the given # of loops on this fcn
    time_str = time_str_ms(timeit(lambda: fcn(a), number=loops_to_test))
    # Get the output string for this function
    fcn_str = '{}(a):'.format(fcn.__name__)
    # Add the correct string length to accommodate the maximum fcn name
    format_str = '{{fx:{}s}} {{time}}{{rev}}'.format(max_name_string + 4)
    print(format_str.format(fx=fcn_str, time=time_str, rev=out_str))

Timing Results

The results show that scaling works best with the built-in methods best suited for a given task. In other words, as the object element count increases, the built-in methods begin to have far superior performance results.

You are also better off using the best built-in method that directly achieves what you need than to string things together. i.e. slicing is best if you need a copy of the reversed list - it's faster than creating a list from the reversed() function, and faster than making a copy of the list and then doing an in-place obj.reverse(). But if either of those methods are really all you need, they are faster, but never by more than double the speed. Meanwhile - custom, manual methods can take orders of magnitude longer, especially with very large lists.

For scaling, with a 1000 item list, the reversed(<list>) function call takes ~30 ms to setup the iterator, reversing in-place takes just ~55 ms, using the slice method takes ~210 ms to create a copy of the full reversed list, but the quickest manual method I made took ~8400 ms!!

With 2 items in the list:

a: [0, 1]
Loops: 100,000
rev_in_place(a):             24.70 ms | out = [1, 0]
reversed_iterator(a):        30.48 ms | out = <list_reverseiterator object at 0x0000020242580408>
rev_slice(a):                31.65 ms | out = [1, 0]
rev_copy_reverse(a):         63.42 ms | out = [1, 0]
reversed_with_list(a):       48.65 ms | out = [1, 0]
rev_manual_pos_gen(a):       98.94 ms | out = [1, 0]
rev_manual_neg_gen(a):       88.11 ms | out = [1, 0]
rev_manual_index_loop(a):    87.23 ms | out = [1, 0]
rev_manual_loop(a):          79.24 ms | out = [1, 0]

With 10 items in the list:

rev_in_place(a):             23.39 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
reversed_iterator(a):        30.23 ms | out = <list_reverseiterator object at 0x00000290A3CB0388>
rev_slice(a):                36.01 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
rev_copy_reverse(a):         64.67 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
reversed_with_list(a):       50.77 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
rev_manual_pos_gen(a):      162.83 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
rev_manual_neg_gen(a):      167.43 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
rev_manual_index_loop(a):   152.04 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
rev_manual_loop(a):         183.01 ms | out = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

And with 1000 items in the list:

rev_in_place(a):             56.37 ms
reversed_iterator(a):        30.47 ms
rev_slice(a):               211.42 ms
rev_copy_reverse(a):        295.74 ms
reversed_with_list(a):      418.45 ms
rev_manual_pos_gen(a):     8410.01 ms
rev_manual_neg_gen(a):    11054.84 ms
rev_manual_index_loop(a): 10543.11 ms
rev_manual_loop(a):       15472.66 ms

How to pass query parameters with a routerLink

<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/   \______________/\_________/ \_________/ \__/
 |           |            |            |        |
scheme    authority      path        query   fragment

For more info - https://angular.io/guide/router#query-parameters-and-fragments

How to convert answer into two decimal point

If you have a Decimal or similar numeric type, you can use:

Math.Round(myNumber, 2)

EDIT: So, in your case, it would be:

Public Class Form1
  Private Sub btncalc_Click(ByVal sender As System.Object,
                            ByVal e As System.EventArgs) Handles btncalc.Click
    txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
    txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
  End Sub
End Class

Process to convert simple Python script into Windows executable

i would recommend going to http://sourceforge.net/projects/py2exe/files/latest/download?source=files to download py2exe. Then make a python file named setup.py. Inside it, type

from distutils.core import setup
import py2exe
setup(console=['nameoffile.py'])

Save in your user folder Also save the file you want converted in that same folder

Run window's command prompt type in setup.py install py2exe

It should print many lines of code...

Next, open the dist folder.

Run the exe file.

If there are needed files for the program to work, move them to the folder

Copy/Send the dist folder to person.

Optional: Change the name of the dist folder

Hope it works!:)

How to programmatically set the SSLContext of a JAX-WS client?

I had problems trusting a self signed certificate when setting up the trust manager. I used the SSLContexts builder of the apache httpclient to create a custom SSLSocketFactory

SSLContext sslcontext = SSLContexts.custom()
        .loadKeyMaterial(keyStoreFile, "keystorePassword.toCharArray(), keyPassword.toCharArray())
        .loadTrustMaterial(trustStoreFile, "password".toCharArray(), new TrustSelfSignedStrategy())
        .build();
SSLSocketFactory customSslFactory = sslcontext.getSocketFactory()
bindingProvider.getRequestContext().put(JAXWSProperties.SSL_SOCKET_FACTORY, customSslFactory);

and passing in the new TrustSelfSignedStrategy() as an argument in the loadTrustMaterial method.

What's the bad magic number error?

Take the pyc file to a windows machine. Use any Hex editor to open this pyc file. I used freeware 'HexEdit'. Now read hex value of first two bytes. In my case, these were 03 f3.

Open calc and convert its display mode to Programmer (Scientific in XP) to see Hex and Decimal conversion. Select "Hex" from Radio button. Enter values as second byte first and then the first byte i.e f303 Now click on "Dec" (Decimal) radio button. The value displayed is one which is correspond to the magic number aka version of python.

So, considering the table provided in earlier reply

  • 1.5 => 20121 => 4E99 so files would have first byte as 99 and second as 4e
  • 1.6 => 50428 => C4FC so files would have first byte as fc and second as c4

can't access mysql from command line mac

On mac, open the terminal and type:

cd /usr/local/mysql/bin

then type:

./mysql -u root -p

It will ask you for the mysql root password. Enter your password and use mysql database in the terminal.

Access parent's parent from javascript object

If I'm reading your question correctly, objects in general are agnostic about where they are contained. They don't know who their parents are. To find that information, you have to parse the parent data structure. The DOM has ways of doing this for us when you're talking about element objects in a document, but it looks like you're talking about vanilla objects.

Create a simple 10 second countdown

_x000D_
_x000D_
var seconds_inputs =  document.getElementsByClassName('deal_left_seconds');_x000D_
    var total_timers = seconds_inputs.length;_x000D_
    for ( var i = 0; i < total_timers; i++){_x000D_
        var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';_x000D_
        var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
        var cal_seconds = seconds_inputs[i].getAttribute('value');_x000D_
_x000D_
        eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');_x000D_
        eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');_x000D_
    }_x000D_
    function timer() {_x000D_
        for ( var i = 0; i < total_timers; i++) {_x000D_
            var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
_x000D_
            var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);_x000D_
            var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));_x000D_
            var hours = Math.floor(hoursLeft / 3600);_x000D_
            var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));_x000D_
            var minutes = Math.floor(minutesLeft / 60);_x000D_
            var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;_x000D_
_x000D_
            function pad(n) {_x000D_
                return (n < 10 ? "0" + n : n);_x000D_
            }_x000D_
            document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);_x000D_
            document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);_x000D_
            document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);_x000D_
            document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);_x000D_
_x000D_
            if (eval('seconds_'+ seconds_prod_id) == 0) {_x000D_
                clearInterval(countdownTimer);_x000D_
                document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);_x000D_
            } else {_x000D_
                var value = eval('seconds_'+seconds_prod_id);_x000D_
                value--;_x000D_
                eval('seconds_' + seconds_prod_id + '= ' + value + ';');_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
_x000D_
    var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">_x000D_
<div class="box-wrapper">_x000D_
    <div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
    <div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
    <div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper hidden-md">_x000D_
    <div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Mysql command not found in OS X 10.7

One alternative way is creating soft link in /usr/local/bin

ln -s /usr/local/mysql/bin/mysql /usr/local/bin/mysql

But if you need other executables like mysqldump, you will need to create soft link for them.

How to change the default docker registry from docker.io to my private registry?

Earlier this could be achieved using DOCKER_OPTS in the /etc/default/docker config file which worked on Ubuntu 14:04 and had some issues on Ubuntu 15:04. Not sure if this has been fixed.

The below line needs to go into the file /etc/default/docker on the host which runs the docker daemon. The change points to the private registry is installed in your local network. Note: you would require to restart the docker service followed with this change.

DOCKER_OPTS="--insecure-registry <priv registry hostname/ip>:<port>"

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

I really like following clean solution.

class Router
  include Rails.application.routes.url_helpers

  def self.default_url_options
    ActionMailer::Base.default_url_options
  end
end

router = Router.new
router.posts_url  # http://localhost:3000/posts
router.posts_path # /posts

It's from http://hawkins.io/2012/03/generating_urls_whenever_and_wherever_you_want/

Angular Directive refresh on parameter change

If You're under AngularJS 1.5.3 or newer, You should consider to move to components instead of directives. Those works very similar to directives but with some very useful additional feautures, such as $onChanges(changesObj), one of the lifecycle hook, that will be called whenever one-way bindings are updated.

app.component('conversation ', {
    bindings: {
    type: '@',
    typeId: '='
    },
    controller: function() {
        this.$onChanges = function(changes) {
            // check if your specific property has changed
            // that because $onChanges is fired whenever each property is changed from you parent ctrl
            if(!!changes.typeId){
                refreshYourComponent();
            }
        };
    },
    templateUrl: 'conversation .html'
});

Here's the docs for deepen into components.

Android Activity as a dialog

If you want to remove activity header & provide a custom view for the dialog add the following to the activity block of you manifest

android:theme="@style/Base.Theme.AppCompat.Dialog"

and design your activity_layout with your desired view

write a shell script to ssh to a remote machine and execute commands

You can follow this approach :

  • Connect to remote machine using Expect Script. If your machine doesn't support expect you can download the same. Writing Expect script is very easy (google to get help on this)
  • Put all the action which needs to be performed on remote server in a shell script.
  • Invoke remote shell script from expect script once login is successful.

Use a URL to link to a Google map with a marker on it

If working with Basic4Android and looking for an easy fix to the problem, try this it works both Google maps and Openstreet even though OSM creates a bit of a messy result and thanx to [yndolok] for the google marker

GooglemLoc="https://www.google.com/maps/place/"&[Latitude]&"+"&[Longitude]&"/@"&[Latitude]&","&[Longitude]&",15z" 

GooglemRute="https://www.google.co.ls/maps/dir/"&[FrmLatt]&","&[FrmLong]&"/"&[ToLatt]&","&[FrmLong]&"/@"&[ScreenX]&","&[ScreenY]&",14z/data=!3m1!4b1!4m2!4m1!3e0?hl=en"  'route ?hl=en

OpenStreetLoc="https://www.openstreetmap.org/#map=16/"&[Latitude]&"/"&[Longitude]&"&layers=N"

OpenStreetRute="https://www.openstreetmap.org/directions?engine=osrm_car&route="&[FrmLatt]&"%2C"&[FrmLong]&"%3B"&[ToLatt]&"%2C"&[ToLong]&"#Map=15/"&[ScreenX]&"/"&[Screeny]&"&layers=N"

What linux shell command returns a part of a string?

From the bash manpage:

${parameter:offset}
${parameter:offset:length}
        Substring  Expansion.   Expands  to  up  to length characters of
        parameter starting at the character  specified  by  offset.
[...]

Or, if you are not sure of having bash, consider using cut.

bundle install fails with SSL certificate verification error

The simplest solution:

rvm pkg install openssl
rvm reinstall all --force

Voila!

Get installed applications in a system

While the accepted solution works, it is not complete. By far.

If you want to get all the keys, you need to take into consideration 2 more things:

x86 & x64 applications do not have access to the same registry. Basically x86 cannot normally access x64 registry. And some applications only register to the x64 registry.

and

some applications actually install into the CurrentUser registry instead of the LocalMachine

With that in mind, I managed to get ALL installed applications using the following code, WITHOUT using WMI

Here is the code:

List<string> installs = new List<string>();
List<string> keys = new List<string>() {
  @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
  @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
};

// The RegistryView.Registry64 forces the application to open the registry as x64 even if the application is compiled as x86 
FindInstalls(RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64), keys, installs);
FindInstalls(RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64), keys, installs);

installs = installs.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
installs.Sort(); // The list of ALL installed applications



private void FindInstalls(RegistryKey regKey, List<string> keys, List<string> installed)
{
  foreach (string key in keys)
  {
    using (RegistryKey rk = regKey.OpenSubKey(key))
    {
      if (rk == null)
      {
        continue;
      }
      foreach (string skName in rk.GetSubKeyNames())
      {
        using (RegistryKey sk = rk.OpenSubKey(skName))
        {
          try
          {
            installed.Add(Convert.ToString(sk.GetValue("DisplayName")));
          }
          catch (Exception ex)
          { }
        }
      }
    }
  }
}

Define a struct inside a class in C++

declare class & nested struct probably in some header file

class C {
    // struct will be private without `public:` keyword
    struct S {
        // members will be public without `private:` keyword
        int sa;
        void func();
    };
    void func(S s);
};

if you want to separate the implementation/definition, maybe in some CPP file

void C::func(S s) {
    // implementation here
}
void C::S::func() { // <= note that you need the `full path` to the function
    // implementation here
}

if you want to inline the implementation, other answers will do fine.

How to check if a number is between two values?

You can use Multiple clause in if condition instead of writing

if (windowsize > 500-600) {
    // do this
}

because this really makes no sense logically JavaScript will read your if condition like

windowSize > -100 

because it calculates 500-600 to -100

You should use && for strict checking both cases for example which will look like this

if( windowSize > 500 && windowSize < 600 ){

// Then doo something

}

Can you autoplay HTML5 videos on the iPad?

Just set

webView.mediaPlaybackRequiresUserAction = NO;

The autoplay works for me on iOS.

How to list active connections on PostgreSQL?

Following will give you active connections/ queries in postgres DB-

SELECT 
    pid
    ,datname
    ,usename
    ,application_name
    ,client_hostname
    ,client_port
    ,backend_start
    ,query_start
    ,query
    ,state
FROM pg_stat_activity
WHERE state = 'active';

You may use 'idle' instead of active to get already executed connections/queries.

How can I lock a file using java (if possible)

Use this for unix if you are transferring using winscp or ftp:

public static void isFileReady(File entry) throws Exception {
        long realFileSize = entry.length();
        long currentFileSize = 0;
        do {
            try (FileInputStream fis = new FileInputStream(entry);) {
                currentFileSize = 0;
                while (fis.available() > 0) {
                    byte[] b = new byte[1024];
                    int nResult = fis.read(b);
                    currentFileSize += nResult;
                    if (nResult == -1)
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("currentFileSize=" + currentFileSize + ", realFileSize=" + realFileSize);
        } while (currentFileSize != realFileSize);
    }

How do I solve the INSTALL_FAILED_DEXOPT error?

I've ran into this problem when I was trying to update new build tools 24.0.1. Internet connection was lost and tools was not downloaded successfully, after that I got this error and spent a lot of time trying to solve it. But when I succesfully updated build tools - problem solved. Good luck.

How to sort alphabetically while ignoring case sensitive?

I like the comparator class SortIgnoreCase, but would have used this

public class SortIgnoreCase implements Comparator<String> {
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);    // Cleaner :)
    }
}

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

For me, I was receiving this error when connecting to the new IP Address I had configured FileZilla to bind to and saved the configuration. After trying all of the other answers unsuccessfully, I decided to connect to the old IP Address to see what came up; lo and behold it responded.

I restarted the FileZilla Windows Service and it immediately came back listening on the correct IP. Pretty elementary, but it cost me some time today as a noob to FZ.

Hopefully this helps someone out in the same predicament.

How do I get the first element from an IEnumerable<T> in .net?

Just in case you're using .NET 2.0 and don't have access to LINQ:

 static T First<T>(IEnumerable<T> items)
 {
     using(IEnumerator<T> iter = items.GetEnumerator())
     {
         iter.MoveNext();
         return iter.Current;
     }
 }

This should do what you're looking for...it uses generics so you to get the first item on any type IEnumerable.

Call it like so:

List<string> items = new List<string>() { "A", "B", "C", "D", "E" };
string firstItem = First<string>(items);

Or

int[] items = new int[] { 1, 2, 3, 4, 5 };
int firstItem = First<int>(items);

You could modify it readily enough to mimic .NET 3.5's IEnumerable.ElementAt() extension method:

static T ElementAt<T>(IEnumerable<T> items, int index)
{
    using(IEnumerator<T> iter = items.GetEnumerator())
    {
        for (int i = 0; i <= index; i++, iter.MoveNext()) ;
        return iter.Current;
    }
} 

Calling it like so:

int[] items = { 1, 2, 3, 4, 5 };
int elemIdx = 3;
int item = ElementAt<int>(items, elemIdx);

Of course if you do have access to LINQ, then there are plenty of good answers posted already...

Android: Clear the back stack

If your application has minimum sdk version 16 then you can use finishAffinity()

Finish this activity as well as all activities immediately below it in the current task that have the same affinity.

This is work for me In Top Payment screen remove all back-stack activits,

 @Override
public void onBackPressed() {
         finishAffinity();
        startActivity(new Intent(PaymentDoneActivity.this,Home.class));
    } 

http://developer.android.com/reference/android/app/Activity.html#finishAffinity%28%29

jquery change style of a div on click

you can use .css method of jquery..

reference css method

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

How to add icon inside EditText view in Android ?

You can set drawableLeft in the XML as suggested by marcos, but you might also want to set it programmatically - for example in response to an event. To do this use the method setCompoundDrawablesWithIntrincisBounds(int, int, int, int):

EditText editText = findViewById(R.id.myEditText);

// Set drawables for left, top, right, and bottom - send 0 for nothing
editTxt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.myDrawable, 0, 0, 0);

How can I refresh c# dataGridView after update ?

I use the DataGridView's Invalidate() function. However, that will refresh the entire DataGridView. If you want to refresh a particular row, you use dgv.InvalidateRow(rowIndex). If you want to refresh a particular cell, you can use dgv.InvalidateCell(columnIndex, rowIndex). This is of course assuming you're using a binding source or data source.

What is the difference between MySQL, MySQLi and PDO?

Those are different APIs to access a MySQL backend

  • The mysql is the historical API
  • The mysqli is a new version of the historical API. It should perform better and have a better set of function. Also, the API is object-oriented.
  • PDO_MySQL, is the MySQL for PDO. PDO has been introduced in PHP, and the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code (if you don't use specific RDBM function in your queries), also object-oriented.

So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...

My advice would be

  1. PDO
  2. MySQLi
  3. mysql

Also my feeling, the mysql API would probably being deleted in future releases of PHP.

Remote debugging a Java application

For JDK 1.3 or earlier :

-Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006

For JDK 1.4

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=6006

For newer JDK :

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=6006

Please change the port number based on your needs.

From java technotes

From 5.0 onwards the -agentlib:jdwp option is used to load and specify options to the JDWP agent. For releases prior to 5.0, the -Xdebug and -Xrunjdwp options are used (the 5.0 implementation also supports the -Xdebug and -Xrunjdwp options but the newer -agentlib:jdwp option is preferable as the JDWP agent in 5.0 uses the JVM TI interface to the VM rather than the older JVMDI interface)

One more thing to note, from JVM Tool interface documentation:

JVM TI was introduced at JDK 5.0. JVM TI replaces the Java Virtual Machine Profiler Interface (JVMPI) and the Java Virtual Machine Debug Interface (JVMDI) which, as of JDK 6, are no longer provided.

add image to uitableview cell

Swift 4 solution:

    cell.imageView?.image = UIImage(named: "yourImageName")

How can I use Guzzle to send a POST request in JSON?

This works for me with Guzzle 6.2 :

$gClient =  new \GuzzleHttp\Client(['base_uri' => 'www.foo.bar']);
$res = $gClient->post('ws/endpoint',
                            array(
                                'headers'=>array('Content-Type'=>'application/json'),
                                'json'=>array('someData'=>'xxxxx','moreData'=>'zzzzzzz')
                                )
                    );

According to the documentation guzzle do the json_encode

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

I got here because I was concerned that cr-lfs that I specified in C# strings were not being shown in SQl Server Management Studio query responses.

It turns out, they are there, but are not being displayed.

To "see" the cr-lfs, use the print statement like:

declare @tmp varchar(500)    
select @tmp = msgbody from emailssentlog where id=6769;
print @tmp

How to load URL in UIWebView in Swift?

For swift 4.2, 5+

@IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
       super.viewDidLoad()
           //Func Gose Here 
          let url = URL(string: link)
          let requestObj = URLRequest(url: url! as URL)
           webView.loadRequest(requestObj)

       }

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

Linux Mint 19. Helped for me:

sudo apt install tk-dev

P.S. Recompile python interpreter after package install.

row-level trigger vs statement-level trigger

The main difference between statement level trigger is below :

statement level trigger : based on name it works if any statement is executed. Does not depends on how many rows or any rows effected.It executes only once. Exp : if you want to update salary of every employee from department HR and at the end you want to know how many rows get effected means how many got salary increased then use statement level trigger. please note that trigger will execute even if zero rows get updated because it is statement level trigger is called if any statement has been executed. No matters if it is affecting any rows or not.

Row level trigger : executes each time when an row is affected. if zero rows affected.no row level trigger will execute.suppose if u want to delete one employye from emp table whose department is HR and u want as soon as employee deleted from emp table the count in dept table from HR section should be reduce by 1.then you should opt for row level trigger.

Fix footer to bottom of page

Set

html, body {
    height: 100%;
}

Wrap the entire content before the footer in a div.

.wrapper {
    height:auto !important;
    min-height:100%;
}

You can adjust min-height as you like based on how much of the footer you want to show in the bottom of the browser window. If set it to 90%, 10% of the footer will show before scrolling.

proper hibernate annotation for byte[]

Here goes what O'reilly Enterprise JavaBeans, 3.0 says

JDBC has special types for these very large objects. The java.sql.Blob type represents binary data, and java.sql.Clob represents character data.

Here goes PostgreSQLDialect source code

public PostgreSQLDialect() {
    super();
    ...
    registerColumnType(Types.VARBINARY, "bytea");
    /**
      * Notice it maps java.sql.Types.BLOB as oid
      */
    registerColumnType(Types.BLOB, "oid");
}

So what you can do

Override PostgreSQLDialect as follows

public class CustomPostgreSQLDialect extends PostgreSQLDialect {

    public CustomPostgreSQLDialect() {
        super();

        registerColumnType(Types.BLOB, "bytea");
    }
}

Now just define your custom dialect

<property name="hibernate.dialect" value="br.com.ar.dialect.CustomPostgreSQLDialect"/>

And use your portable JPA @Lob annotation

@Lob
public byte[] getValueBuffer() {

UPDATE

Here has been extracted here

I have an application running in hibernate 3.3.2 and the applications works fine, with all blob fields using oid (byte[] in java)

...

Migrating to hibernate 3.5 all blob fields not work anymore, and the server log shows: ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: column is of type oid but expression is of type bytea

which can be explained here

This generaly is not bug in PG JDBC, but change of default implementation of Hibernate in 3.5 version. In my situation setting compatible property on connection did not helped.

...

Much more this what I saw in 3.5 - beta 2, and i do not know if this was fixed is Hibernate - without @Type annotation - will auto-create column of type oid, but will try to read this as bytea

Interesting is because when he maps Types.BOLB as bytea (See CustomPostgreSQLDialect) He get

Could not execute JDBC batch update

when inserting or updating

How do I use InputFilter to limit characters in an EditText in Android?

I found this on another forum. Works like a champ.

InputFilter filter = new InputFilter() {
    public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {
        for (int i = start; i < end; i++) {
            if (!Character.isLetterOrDigit(source.charAt(i))) {
                return "";
            }
        }
        return null;
    }
};
edit.setFilters(new InputFilter[] { filter });

What's the most concise way to read query parameters in AngularJS?

$location.search() will work only with HTML5 mode turned on and only on supporting browser.

This will work always:

$window.location.search

Converting Milliseconds to Minutes and Seconds?

I was creating a mp3 player app for android, so I did it like this to get current time and duration

 private String millisecondsToTime(long milliseconds) {
    long minutes = (milliseconds / 1000) / 60;
    long seconds = (milliseconds / 1000) % 60;
    String secondsStr = Long.toString(seconds);
    String secs;
    if (secondsStr.length() >= 2) {
        secs = secondsStr.substring(0, 2);
    } else {
        secs = "0" + secondsStr;
    }

    return minutes + ":" + secs;
}

How to execute powershell commands from a batch file?

This is what the code would look like in a batch file(tested, works):

powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"

Based on the information from:

http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/

How to set proxy for wget?

After trying many tutorials to configure my Ubuntu 16.04 LTS behind a authenticated proxy, it worked with these steps:

Edit /etc/wgetrc:

$ sudo nano /etc/wgetrc

Uncomment these lines:

#https_proxy = http://proxy.yoyodyne.com:18023/
#http_proxy = http://proxy.yoyodyne.com:18023/
#ftp_proxy = http://proxy.yoyodyne.com:18023/
#use_proxy = on

Change http://proxy.yoyodyne.com:18023/ to http://username:password@domain:port/

IMPORTANT: If it still doesn't work, check if your password has special characters, such as #, @, ... If this is the case, escape them (for example, replace passw@rd with passw%40rd).

How to make MySQL table primary key auto increment with some prefix

I know it is late but I just want to share on what I have done for this. I'm not allowed to add another table or trigger so I need to generate it in a single query upon insert. For your case, can you try this query.

CREATE TABLE YOURTABLE(
IDNUMBER VARCHAR(7) NOT NULL PRIMARY KEY,
ENAME VARCHAR(30) not null
);

Perform a select and use this select query and save to the parameter @IDNUMBER

(SELECT IFNULL
     (CONCAT('LHPL',LPAD(
       (SUBSTRING_INDEX
        (MAX(`IDNUMBER`), 'LHPL',-1) + 1), 5, '0')), 'LHPL001')
    AS 'IDNUMBER' FROM YOURTABLE ORDER BY `IDNUMBER` ASC)

And then Insert query will be :

INSERT INTO YOURTABLE(IDNUMBER, ENAME) VALUES 
(@IDNUMBER, 'EMPLOYEE NAME');

The result will be the same as the other answer but the difference is, you will not need to create another table or trigger. I hope that I can help someone that have a same case as mine.

Split function in oracle to comma separated values with automatic sequence

There are multiple options. See Split single comma delimited string into rows in Oracle

You just need to add LEVEL in the select list as a column, to get the sequence number to each row returned. Or, ROWNUM would also suffice.

Using any of the below SQLs, you could include them into a FUNCTION.

INSTR in CONNECT BY clause:

SQL> WITH DATA AS
  2    ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual
  3    )
  4  SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str
  5  FROM DATA
  6  CONNECT BY instr(str, ',', 1, LEVEL - 1) > 0
  7  /

STR
----------------------------------------
word1
word2
word3
word4
word5
word6

6 rows selected.

SQL>

REGEXP_SUBSTR in CONNECT BY clause:

SQL> WITH DATA AS
  2    ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual
  3    )
  4  SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str
  5  FROM DATA
  6  CONNECT BY regexp_substr(str , '[^,]+', 1, LEVEL) IS NOT NULL
  7  /

STR
----------------------------------------
word1
word2
word3
word4
word5
word6

6 rows selected.

SQL>

REGEXP_COUNT in CONNECT BY clause:

SQL> WITH DATA AS
  2        ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual
  3        )
  4      SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str
  5      FROM DATA
  6      CONNECT BY LEVEL 

Using XMLTABLE

SQL> WITH DATA AS
  2    ( SELECT 'word1, word2, word3, word4, word5, word6' str FROM dual
  3    )
  4  SELECT trim(COLUMN_VALUE) str
  5    FROM DATA, xmltable(('"' || REPLACE(str, ',', '","') || '"'))
  6  /
STR
------------------------------------------------------------------------
word1
word2
word3
word4
word5
word6

6 rows selected.

SQL>

Using MODEL clause:

SQL> WITH t AS
  2  (
  3         SELECT 'word1, word2, word3, word4, word5, word6' str
  4         FROM   dual ) ,
  5  model_param AS
  6  (
  7         SELECT str AS orig_str ,
  8                ','
  9                       || str
 10                       || ','                                 AS mod_str ,
 11                1                                             AS start_pos ,
 12                Length(str)                                   AS end_pos ,
 13                (Length(str) - Length(Replace(str, ','))) + 1 AS element_count ,
 14                0                                             AS element_no ,
 15                ROWNUM                                        AS rn
 16         FROM   t )
 17  SELECT   trim(Substr(mod_str, start_pos, end_pos-start_pos)) str
 18  FROM     (
 19                  SELECT *
 20                  FROM   model_param MODEL PARTITION BY (rn, orig_str, mod_str)
 21                  DIMENSION BY (element_no)
 22                  MEASURES (start_pos, end_pos, element_count)
 23                  RULES ITERATE (2000)
 24                  UNTIL (ITERATION_NUMBER+1 = element_count[0])
 25                  ( start_pos[ITERATION_NUMBER+1] = instr(cv(mod_str), ',', 1, cv(element_no)) + 1,
 26                  end_pos[iteration_number+1] = instr(cv(mod_str), ',', 1, cv(element_no) + 1) ) )
 27  WHERE    element_no != 0
 28  ORDER BY mod_str ,
 29           element_no
 30  /

STR
------------------------------------------
word1
word2
word3
word4
word5
word6

6 rows selected.

SQL>

You could also use DBMS_UTILITY package provided by Oracle. It provides various utility subprograms. One such useful utility is COMMA_TO_TABLE procedure, which converts a comma-delimited list of names into a PL/SQL table of names.

Read DBMS_UTILITY.COMMA_TO_TABLE

How to replicate background-attachment fixed on iOS

It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.

wrapper div{
   image wrapper div{
       div for individual image{ <--- Fixed position
          image <--- relative position
       }
   }
   quote wrapper div{
       div for individual quote{
          quote
       }
   }
 }

Recursive query in SQL Server

Something like this (not tested)

with match_groups as (

  select product_id, 
         matching_product_id,
         product_id as group_id
  from matches
  where product_id not in (select matching_product_id from matches)

  union all

  select m.product_id, m.matching_product_id, p.group_id
  from matches m
    join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;

How can I check for Python version in a program that uses new language features?

Put the following at the very top of your file:

import sys

if float(sys.version.split()[0][:3]) < 2.7:
    print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting."
    exit(1)

Then continue on with the normal Python code:

import ...
import ...
other code...

Unable to set data attribute using jQuery Data() API

Happened the same to me. It turns out that

var data = $("#myObject").data();

gives you a non-writable object. I solved it using:

var data = $.extend({}, $("#myObject").data());

And from then on, data was a standard, writable JS object.

Java says FileNotFoundException but file exists

I had this same error and solved it simply by adding the src directory that is found in Java project structure.

String path = System.getProperty("user.dir") + "\\src\\package_name\\file_name";
File file = new File(path);
Scanner scanner = new Scanner(file);

Notice that System.getProperty("user.dir") and new File(".").getAbsolutePath() return your project root directory path, so you have to add the path to your subdirectories and packages

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

I have stumbled across this questions and answers after receiving the aforementioned error in IE11 when trying to upload files using XMLHttpRequest:

var reqObj = new XMLHttpRequest();

//event Handler
reqObj.upload.addEventListener("progress", uploadProgress, false);
reqObj.addEventListener("load", uploadComplete, false);
reqObj.addEventListener("error", uploadFailed, false);
reqObj.addEventListener("abort", uploadCanceled, false);

//open the object and set method of call (post), url to call, isAsynchronous(true)
reqObj.open("POST", $rootUrlService.rootUrl + "Controller/UploadFiles", true);

//set Content-Type at request header.for file upload it's value must be multipart/form-data
reqObj.setRequestHeader("Content-Type", "multipart/form-data");

//Set header properties : file name and project milestone id
reqObj.setRequestHeader('X-File-Name', name);

// send the file
// this is the line where the error occurs
reqObj.send(fileToUpload);

Removing the line reqObj.setRequestHeader("Content-Type", "multipart/form-data"); fixed the problem.

Note: this error is shown very differently in other browsers. I.e. Chrome shows something similar to a connection reset which is similar to what Fiddler reports (an empty response due to sudden connection close).

Also, this error appeared only when upload was done from a machine different from WebServer (no problems on localhost).

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

php get values from json encode

json_decode() will return an object or array if second value it's true:

$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];

How to extract a single value from JSON response?

Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist

You could also add some logic to test for the key if you want as well.

if 'name' in resp_dict:
    resp_dict['name']
else:
    # do something else here.

Is it possible to program Android to act as physical USB keyboard?

This is possible, without any additional drivers needed.

You can emulate PC's USB keyboard with small USB dongle-sized device and then use your Android device to send keyboard (and/or mouse) data over Bluetooth.

Take a look on descriptive video in Indiegogo campaign: http://igg.me/at/hiDBLUE/x/3400885

BTW: The product technical documents is available here: http://www.flyfish-tech.com/hiDBLUE

Batch script to install MSI

This is how to install a normal MSI file silently:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"

Quick explanation:

 /L*V "C:\Temp\msilog.log"= verbose logging at indicated path
 /QN = run completely silently
 /i = run install sequence 

The msiexec.exe command line is extensive with support for a variety of options. Here is another overview of the same command line interface. Here is an annotated versions (was broken, resurrected via way back machine).

It is also possible to make a batch file a lot shorter with constructs such as for loops as illustrated here for Windows Updates.

If there are check boxes that must be checked during the setup, you must find the appropriate PUBLIC PROPERTIES attached to the check box and set it at the command line like this:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log" STARTAPP=1 SHOWHELP=Yes

These properties are different in each MSI. You can find them via the verbose log file or by opening the MSI in Orca, or another appropriate tool. You must look either in the dialog control section or in the Property table for what the property name is. Try running the setup and create a verbose log file first and then search the log for messages ala "Setting property..." and then see what the property name is there. Then add this property with the value from the log file to the command line.

Also have a look at how to use transforms to customize the MSI beyond setting command line parameters: How to make better use of MSI files

Is there a stopwatch in Java?

Simple out of the box Stopwatch class:

import java.time.Duration;
import java.time.Instant;

public class StopWatch {

    Instant startTime, endTime;
    Duration duration;
    boolean isRunning = false;

    public void start() {
        if (isRunning) {
            throw new RuntimeException("Stopwatch is already running.");
        }
        this.isRunning = true;
        startTime = Instant.now();
    }

    public Duration stop() {
        this.endTime = Instant.now();
        if (!isRunning) {
            throw new RuntimeException("Stopwatch has not been started yet");
        }
        isRunning = false;
        Duration result = Duration.between(startTime, endTime);
        if (this.duration == null) {
            this.duration = result;
        } else {
            this.duration = duration.plus(result);
        }

        return this.getElapsedTime();
    }

    public Duration getElapsedTime() {
        return this.duration;
    }

    public void reset() {
        if (this.isRunning) {
            this.stop();
        }
        this.duration = null;
    }
}

Usage:

StopWatch sw = new StopWatch();
sw.start();
    // doWork()
sw.stop();
System.out.println( sw.getElapsedTime().toMillis() + "ms");

mvn command not found in OSX Mavrerick

Try following these if these might help:

Since your installation works on the terminal you installed, all the exports you did, work on the current bash and its child process. but is not spawned to new terminals.

env variables are lost if the session is closed; using .bash_profile, you can make it available in all sessions, since when a bash session starts, it 'runs' its .bashrc and .bash_profile

Now follow these steps and see if it helps:

  1. type env | grep M2_HOME on the terminal that is working. This should give something like

    M2_HOME=/usr/local/apache-maven/apache-maven-3.1.1

  2. typing env | grep JAVA_HOME should give like this:

    JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home

Now you have the PATH for M2_HOME and JAVA_HOME.

If you just do ls /usr/local/apache-maven/apache-maven-3.1.1/bin, you will see mvn binary there. All you have to do now is to point to this location everytime using PATH. since bash searches in all the directory path mentioned in PATH, it will find mvn.

  1. now open .bash_profile, if you dont have one just create one

    vi ~/.bash_profile

Add the following:

#set JAVA_HOME
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home
export JAVA_HOME


M2_HOME=/usr/local/apache-maven/apache-maven-3.1.1
export M2_HOME

PATH=$PATH:$JAVA_HOME/bin:$M2_HOME/bin
export PATH
  1. save the file and type source ~/.bash_profile. This steps executes the commands in the .bash_profile file and you are good to go now.

  2. open a new terminal and type mvn that should work.

Check if value exists in column in VBA

The find method of a range is faster than using a for loop to loop through all the cells manually.

here is an example of using the find method in vba

Sub Find_First()
Dim FindString As String
Dim Rng As Range
FindString = InputBox("Enter a Search value")
If Trim(FindString) <> "" Then
    With Sheets("Sheet1").Range("A:A") 'searches all of column A
        Set Rng = .Find(What:=FindString, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
            Application.Goto Rng, True 'value found
        Else
            MsgBox "Nothing found" 'value not found
        End If
    End With
End If
End Sub

std::string to char*

To be strictly pedantic, you cannot "convert a std::string into a char* or char[] data type."

As the other answers have shown, you can copy the content of the std::string to a char array, or make a const char* to the content of the std::string so that you can access it in a "C style".

If you're trying to change the content of the std::string, the std::string type has all of the methods to do anything you could possibly need to do to it.

If you're trying to pass it to some function which takes a char*, there's std::string::c_str().

Add a background image to shape in XML Android

This is a corner image

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@drawable/img_main_blue"
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />

    <item>
        <shape
            android:padding="10dp"
            android:shape="rectangle">
            <corners android:radius="10dp" />
            <stroke
                android:width="5dp"
                android:color="@color/white" />
        </shape>

    </item>
</layer-list>

LaTeX: Multiple authors in a two-column article

I put together a little test here:

\documentclass[10pt,twocolumn]{article}

\title{Article Title}
\author{
    First Author\\
    Department\\
    school\\
    email@edu
  \and
    Second Author\\
    Department\\
    school\\
    email@edu
    \and
    Third Author\\
    Department\\
    school\\
    email@edu
    \and
    Fourth Author\\
    Department\\
    school\\
    email@edu
}
\date{\today}

\begin{document}

\maketitle

\begin{abstract}
\ldots
\end{abstract}

\section{Introduction}
\ldots

\end{document}

Things to note, the title, author and date fields are declared before \begin{document}. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn in the document class.

This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}. Here's a more detailed article on \LaTeX font sizes:

https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont

To italicize you can use {\it First Name} or \textit{First Name}.

Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.

Regular expression for floating point numbers

I want to match what most languages consider valid numbers (integer and floats):

  • '5' / '-5'

  • '1.0' / '1.' / '.1' / '-1.' / '-.1'

  • '0.45326e+04', '666999e-05', '0.2e-3', '-33.e-1'

Notes:

  • preceding sign of number ('-' or '+') is optional

  • '-1.' and '-.1' are valid but '.' and '-.' are invalid

  • '.1e3' is valid, but '.e3' and 'e3' are invalid

In order to support both '1.' and '.1' we need an OR operator ('|') in order to make sure we exclude '.' from matching.

[+-]? +/- sing is optional since ? means 0 or 1 matches

( since we have 2 sub expressions we need to put them in parenthesis

\d+([.]\d*)?(e[+-]?\d+)? This is for numbers starting with a digit

| separates sub expressions

[.]\d+(e[+-]?\d+)? this is for numbers starting with '.'

) end of expressions

  • For numbers starting with '.'

[.] first character is dot (inside brackets or else it is a wildcard character)

\d+ one or more digits

(e[+-]?\d+)? this is an optional (0 or 1 matches due to ending '?') scientific notation

  • For numbers starting with a digit

\d+ one or more digits

([.]\d*)? optionally we can have a dot character an zero or more digits after it

(e[+-]?\d+)? this is an optional scientific notation

  • Scientific notation

e literal that specifies exponent

[+-]? optional exponent sign

\d+ one or more digits

All of those combined:

[+-]?(\d+([.]\d*)?(e[+-]?\d+)?|[.]\d+(e[+-]?\d+)?)

To accept E as well:

[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]\d+([eE][+-]?\d+)?)

(Test cases)

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

Convert long/lat to pixel x/y on a given picture

You may have a look at code that used on gheat, it's ported from js to python.

SQL Greater than, Equal to AND Less Than

If start time is a datetime type then you can use something like

SELECT BookingId, StartTime
FROM Booking
WHERE StartTime >= '2012-03-08 00:00:00.000' 
AND StartTime <= '2012-03-08 01:00:00.000'

Obviously you would want to use your own values for the times but this should give you everything in that 1 hour period inclusive of both the upper and lower limit.

You can use the GETDATE() function to get todays current date.

How to enable CORS in flask

Try the following decorators:

@app.route('/email/',methods=['POST', 'OPTIONS']) #Added 'Options'
@crossdomain(origin='*')                          #Added
def hello_world():
    name=request.form['name']
    email=request.form['email']
    phone=request.form['phone']
    description=request.form['description']

    mandrill.send_email(
        from_email=email,
        from_name=name,
        to=[{'email': app.config['QOLD_SUPPORT_EMAIL']}],
        text="Phone="+phone+"\n\n"+description
    )

    return '200 OK'

if __name__ == '__main__':
    app.run()

This decorator would be created as follows:

from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper


def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):

    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator

You can also check out this package Flask-CORS

Scrolling a div with jQuery

An excellent plug-in is jscrollpane