Programs & Examples On #Hashalgorithm


The module was expected to contain an assembly manifest

First try to open the file with a decompiler such as ILSpy, your dll might be corrupt. I had this error on an online web site, when I downloaded the dll and tried to open it, it was corrupt, probably some error occurred while uploading it via ftp.

Fiddler not capturing traffic from browsers

Same problem here, in all browsers (IE, Chrome, FF). Upon startup the Fiddler Log tab showed the following:

"!WARNING Fiddler has detected that system or domain Group Policy has set ProxySettingsPerUser to 0. Unless Fiddler is run Elevated (e.g. Run As Administrator), it may not capture traffic from Internet Explorer and other programs. Current process IS running Elevated."

I'm in a huge corporate environment, with no connection to or info about group policy changes; it apparently just got applied one day. Thanks, bureaucracy :)

Anyway, that led me to messing around with IE proxy settings. Changing it from Automatic to on port 8888 (the default configured port in Fiddler) worked. Kind of a pain, though, because I have to set it each time to override the group policy setting. And then I get cert errors, which is a known thing because Fiddler uses it's own, untrusted cert . . . and the beat goes on . . .

Cannot connect to SQL Server named instance from another SQL Server

You've tried alot. And I feel for you. Here is an idea. I kinda followed everything you tried. The mental note I have in my head goes like this: "When Sql Server won't connect when you've tried everything, wire up your firewall rules by the program, not the port"

I know you said you disabled the firewall. But something is telling me to give this a try anyways.

I think you have to open the firewall "by program", and not by port.

To add a program exception to the firewall using the Windows Firewall item in Control Panel.

On the Exceptions tab of the Windows Firewall item in Control Panel, click Add a program.

Browse to the location of the instance of SQL Server that you want to allow through the firewall, for example C:\Program Files\Microsoft SQL Server\MSSQL11.<instance_name>\MSSQL\Binn, select sqlservr.exe, and then click Open.

 Click OK.


I'm a little cloudy on which "program" you're trying to use on SQLB?

Is it SSMS on SQLB? Or a client program on SQLB ?


No idea if this will help. But I use this to ping "ports" ... and something that is outside of the SSMS world.

How to put a new line into a wpf TextBlock control?

you must use

 < SomeObject xml:space="preserve" > once upon a time ...
      this line will be below the first one < /SomeObject>

Or if you prefer :

 <SomeObject xml:space="preserve" />  once upon a time... &#10; this line below < / SomeObject>

watch out : if you both use &10 AND you go to the next line in your text, you'll have TWO empty lines.

here for details :

How does Google calculate my location on a desktop?

It's a lot more simple that you think. You've signed into both your mobile and Chrome on your desktop using the same Google account. Google simply expect you will have your mobile with you most of the time. They take the location data from your phone and assume the location of your current desktop session is the same.

I proved this by RDPing into my Windows machine at home from work and checking Google maps remotely. It show my location as the same as Chrome on Linux at work.

If you don't have a mobile that is signed into Google then all they can do is lookup GeoIP data for the IP address assigned by your ISP. It will typically be wildly inaccurate.

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Please make a backup for the script.bs1 file

What works for me was deleting the script.bs1 file and running the execution command.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

If you have MFA enabled on GitLab you should go to Repository Settings/Repository ->Deploy Keys and create one, then use it as login while importing repo on GitHub

Java - removing first character of a string

Use substring() and give the number of characters that you want to trim from front.

String value = "Jamaica";
value = value.substring(1);

Answer: "amaica"

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

You will want to use a CONVERT() statement.

Try the following;

SELECT CONVERT(VARCHAR(10), SA.[RequestStartDate], 103) as 'Service Start Date', CONVERT(VARCHAR(10), SA.[RequestEndDate], 103) as 'Service End Date', FROM (......) SA WHERE.....

See MSDN Cast and Convert for more information.

Get GPS location from the web browser

To give a bit more specific answer. HTML5 allows you to get the geo coordinates, and it does a pretty decent job. Overall the browser support for geolocation is pretty good, all major browsers except ie7 and ie8 (and opera mini). IE9 does the job but is the worst performer. Checkout

Also you need the approval of your user to access their location, so make sure you check for this and give some decent instructions in case it's turned off. Especially for Iphone turning permissions on for Safari is a bit cumbersome.

What is difference between sleep() method and yield() method of multi threading?

sleep() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).

yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.

How do I remove duplicate items from an array in Perl?

The variable @array is the list with duplicate elements

@unique = grep { ! $seen{$_} ++ } @array;

Changing background colour of tr element on mouseover

I had the same problem:

tr:hover { background: #000 !important; }

allone did not work, but adding

tr:hover td { background: transparent; }

to the next line of my css did the job for me!! My problem was that some of the TDs already had a background-color assigned and I did not know that I have to set that to TRANSPARENT to make the tr:hover work.

Actually, I used it with a classnames:

.trclass:hover { background: #000 !important; }
.trclass:hover td { background: transparent; }

Thanks for these answers, they made my day!! :)

Reset all the items in a form

There is a very effective way to use to clear or reset Windows Form C# controls like TextBox, ComboBox, RadioButton, CheckBox, DateTimePicker etc.

private void btnClear_Click(object sender, EventArgs e)

internal class Utilities
    internal static void ClearAllControls(Control control)
        foreach (Control c in control.Controls)
            if (c is TextBox)
            else if (c is ComboBox)
                ((ComboBox)c).SelectedIndex = -1;
            else if (c is RadioButton)
                ((RadioButton)c).Checked = false;
            else if (c is CheckBox)
                ((CheckBox)c).Checked = false;
            else if (c is DateTimePicker)
                ((DateTimePicker)c).Value = DateTime.Now; // or null 

To accomplish this with overall user experience in c# we can use one statement to clear them. Pretty straight forward so far, above is the code.

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Use permission symbols instead of numbers

Your problem would have been avoided if you had used the more semantically named permission symbols rather than raw magic numbers, e.g. for 664:

#!/usr/bin/env python3

import os
import stat

    stat.S_IRUSR |
    stat.S_IWUSR |
    stat.S_IRGRP |
    stat.S_IWGRP |

This is documented at and the names are the same as the POSIX C API values documented at man 2 stat.

Another advantage is the greater portability as mentioned in the docs:

Note: Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

chmod +x is demonstrated at: How do you do a simple "chmod +x" from within python?

Tested in Ubuntu 16.04, Python 3.5.2.

extract column value based on another column pandas dataframe

It's easier for me to think in these terms, but borrowing from other answers. The value you want is located in the series:


where column and row point to the value you want returned. For your example, column is 'A' and for row you use a mask:

df['B'] == 3

To get the value from the series there are several options:

df['A'][df['B'] == 3].values[0]
df['A'][df['B'] == 3].iloc[0]
df['A'][df['B'] == 3].to_numpy()[0]

How to build an android library with Android Studio and gradle?

Note: This answer is a pure Gradle answer, I use this in IntelliJ on a regular basis but I don't know how the integration is with Android Studio. I am a believer in knowing what is going on for me, so this is how I use Gradle and Android.

TL;DR Full Example -

Disclaimer: This is a project I am/was working on.

Gradle has a defined structure ( that you can change, link at the bottom tells you how ) that is very similar to Maven if you have ever used it.

Project Root
+-- src
|   +-- main (your project)
|   |   +-- java (where your java code goes)
|   |   +-- res  (where your res go)
|   |   +-- assets (where your assets go)
|   |   \-- AndroidManifest.xml
|   \-- instrumentTest (test project)
|       \-- java (where your java code goes)
+-- build.gradle
\-- settings.gradle

If you only have the one project, the settings.gradle file isn't needed. However you want to add more projects, so we need it.

Now let's take a peek at that build.gradle file. You are going to need this in it (to add the android tools)


buildscript {
    repositories {
    dependencies {
        classpath ''

Now we need to tell Gradle about some of the Android parts. It's pretty simple. A basic one (that works in most of my cases) looks like the following. I have a comment in this block, it will allow me to specify the version name and code when generating the APK.


apply plugin: "android"
android {
        compileSdkVersion 17
        defaultConfig {
            versionCode = 1
            versionName = "0.0.0"

Something we are going to want to add, to help out anyone that hasn't seen the light of Gradle yet, a way for them to use the project without installing it.


task wrapper(type: org.gradle.api.tasks.wrapper.Wrapper) {
    gradleVersion = '1.4'

So now we have one project to build. Now we are going to add the others. I put them in a directory, maybe call it deps, or subProjects. It doesn't really matter, but you will need to know where you put it. To tell Gradle where the projects are you are going to need to add them to the settings.gradle.

Directory Structure:

Project Root
+-- src (see above)
+-- subProjects (where projects are held)
|   +-- reallyCoolProject1 (your first included project)
|       \-- See project structure for a normal app
|   \-- reallyCoolProject2 (your second included project)
|       \-- See project structure for a normal app
+-- build.gradle
\-- settings.gradle


include ':subProjects:reallyCoolProject1'
include ':subProjects:reallyCoolProject2'

The last thing you should make sure of is the subProjects/reallyCoolProject1/build.gradle has apply plugin: "android-library" instead of apply plugin: "android".

Like every Gradle project (and Maven) we now need to tell the root project about it's dependency. This can also include any normal Java dependencies that you want.


    compile 'com.fasterxml.jackson.core:jackson-core:2.1.4'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.1.4'
    compile project(":subProjects:reallyCoolProject1")
    compile project(':subProjects:reallyCoolProject2')

I know this seems like a lot of steps, but they are pretty easy once you do it once or twice. This way will also allow you to build on a CI server assuming you have the Android SDK installed there.

NDK Side Note: If you are going to use the NDK you are going to need something like below. Example build.gradle file can be found here:


task copyNativeLibs(type: Copy) {
    from fileTree(dir: 'libs', include: '**/*.so' )  into  'build/native-libs'
tasks.withType(Compile) { compileTask -> compileTask.dependsOn copyNativeLibs }

clean.dependsOn 'cleanCopyNativeLibs'

tasks.withType( { pkgTask ->
  pkgTask.jniDir new File('build/native-libs')



Google Maps API v3 marker with label

I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.

 .labels {
   color: red;
   background-color: white;
   font-family: "Lucida Grande", "Arial", sans-serif;
   font-size: 10px;
   font-weight: bold;
   text-align: center;
   width: 60px;     
   border: 2px solid black;
   white-space: nowrap;


 var marker = new MarkerWithLabel({
   position: homeLatLng,
   draggable: true,
   map: map,
   labelContent: "$425K",
   labelAnchor: new google.maps.Point(22, 0),
   labelClass: "labels", // the CSS class for the label
   labelStyle: {opacity: 0.75}

The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50).

In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|

Javascript sleep/delay/wait function

You will have to use a setTimeout so I see your issue as

I have a script that is generated by PHP, and so am not able to put it into two different functions

What prevents you from generating two functions in your script?

function fizz() {
    var a;
    a = 'buzz';
    // sleep x desired
    a = 'complete';

Could be rewritten as

function foo() {
    var a; // variable raised so shared across functions below
    function bar() { // consider this to be start of fizz
        a = 'buzz';
        setTimeout(baz, x); // start wait
    } // code split here for timeout break
    function baz() { // after wait
        a = 'complete';
    } // end of fizz
    bar(); // start it

You'll notice that a inside baz starts as buzz when it is invoked and at the end of invocation, a inside foo will be "complete".

Basically, wrap everything in a function, move all variables up into that wrapping function such that the contained functions inherit them. Then, every time you encounter wait NUMBER seconds you echo a setTimeout, end the function and start a new function to pick up where you left off.

how to know status of currently running jobs

Given a job (I assume you know its name) you can use:

EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'

as suggested in MSDN Job Help Procedure. It returns a lot of informations about the job (owner, server, status and so on).

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

You can use ObjectMapper

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectClass object = objectMapper.readValue(data, ObjectClass.class);

Pushing empty commits to remote

What about this;

 git commit --allow-empty-message -m ''

How to get a jqGrid selected row cells value

Just Checkout This :

Solution 1 :

In Subgrid Function You have to write following :

var selectid = $(this).jqGrid('getCell', row_id, 'id');

Where row_id is the variable which you define in subgrid as parameter. And id is the column name which you want to get value of the cell.

Solution 2 :

If You Get Jqgrid Row Id In alert Then set your primary key id as key:true In ColModels. So You will get value of your database id in alert. Like this :

{name:"id",index:"id",hidden:true, width:15,key:true, jsonmap:"id"},

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Problem solved.

Just drop down status bar, touch Choose input method, then change to another input method, type the password again. And everything is OK.

So weird...

Solution from a Chinese BBS. Thanks for the answer's author and all above who try to provide a solution, thanks!

How to get current value of RxJS Subject or Observable?

A Subject or Observable doesn't have a current value. When a value is emitted, it is passed to subscribers and the Observable is done with it.

If you want to have a current value, use BehaviorSubject which is designed for exactly that purpose. BehaviorSubject keeps the last emitted value and emits it immediately to new subscribers.

It also has a method getValue() to get the current value.

Configuring Log4j Loggers Programmatically

If someone comes looking for configuring log4j2 programmatically in Java, then this link could help: (

Here is the basic code for configuring a Console Appender:

ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();

// naming the logger configuration

// create a console appender
AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
                .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
// add a layout like pattern, json etc
                .addAttribute("pattern", "%d %p %c [%t] %m%n"));
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);


This will reconfigure the default rootLogger and will also create a new appender.

How can I view the Git history in Visual Studio Code?

It is evident to me that GitLens is the most popular extension for Git history.

enter image description here

What I like the most it can provide you side annotations when some line has been changed the last time and by whom.

Enter image description here

'Java' is not recognized as an internal or external command

My solution was to put same value (path to JDK bin folder) in JAVA_HOME and Path


Replacing blank values (white space) with NaN in pandas

If you want to replace an empty string and records with only spaces, the correct answer is!:

df = df.replace(r'^\s*$', np.nan, regex=True)

The accepted answer

df.replace(r'\s+', np.nan, regex=True)

Does not replace an empty string!, you can try yourself with the given example slightly updated:

df = pd.DataFrame([
    [-0.532681, 'foo', 0],
    [1.490752, 'bar', 1],
    [-1.387326, 'fo o', 2],
    [0.814772, 'baz', ' '],     
    [-0.222552, '   ', 4],
    [-1.176781,  'qux', ''],         
], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))

Note, also that 'fo o' is not replaced with Nan, though it contains a space. Further note, that a simple:

df.replace(r'', np.NaN)

Does not work either - try it out.

Javascript getElementById based on a partial string

querySelectorAll with modern enumeration

polls = document.querySelectorAll('[id ^= "poll-"]');, callback);

function callback(element, iterator) {

The first line selects all elements which id starts with the string poll-. The second line evokes the enumeration and a callback function.

How to insert an image in python

Install PIL(Python Image Library) :


from PIL import Image
myImage ="your_image_here");;

Why would a " Connection timed out" exception occur when URL is up?

  • try to do the Telnet to see any firewall issue
  • perform tracert/traceroute to find number of hops

Block direct access to a file over http but allow php script access

in httpd.conf to block browser & wget access to include files especially say or . Note you cannot chain file types in the directive instead create multiple file directives.

<Files ~ "\.inc$">
Order allow,deny
Deny from all

to test your config before restarting apache

service httpd configtest

then (graceful restart)

service httpd graceful error in opening zip file

It could be related to log4j.

Do you have log4j.jar file in the websphere java classpath (as defined in the startup file) as well as the application classpath ?

If you do make sure that the log4j.jar file is in the java classpath and that it is NOT in the web-inf/lib directory of your webapp.

It can also be related with the ant version (may be not your case, but I do put it here for reference):

You have a .class file in your class path (i.e. not a directory or a .jar file). Starting with ant 1.6, ant will open the files in the classpath checking for manifest entries. This attempted opening will fail with the error ""

The problem does not exist with ant 1.5 as it does not try to open the files. - so make sure that your classpath's do not contain .class files.

On a side note, did you consider having separate jars ?
You could in the manifest of your main jar, refer to the other jars with this attribute:

Class-Path: one.jar two.jar three.jar

Then, place all of your jars in the same folder.
Again, may be not valid for your case, but still there for reference.

Getting values from JSON using Python

What error is it giving you?

If you do exactly this:

data = json.loads('{"lat":444, "lon":555}')



SHOULD NOT give you any error at all.

Android WebView Cookie Problem

I've spent the greater half of 3 hours working on a very similar issue. In my case I had a number of calls, that I made to a web service using a DefaulHttpClient and then I wanted to set the session and all other corresponding cookies in my WebView.

I don't know if this will solve your problem, since I don't know what your getCookie() method does, but in my case I actually had to call.


First to remove the session cookie and then re-add it. I was finding that when I tried to set the JSESSIONID cookie without first removing it, the value I wanted to set it to wasn't being save. Not sure if this will help you particular issue, but thought I'd share what I had found.

Updates were rejected because the tip of your current branch is behind its remote counterpart

To make sure your local branch FixForBug is not ahead of the remote branch FixForBug pull and merge the changes before pushing.

git pull origin FixForBug
git push origin FixForBug

How to disable a input in angular2

Disabled Select in angular 9.

one thing keep in mind disabled work with boolean values in this example, I am using the (change) event with the select option if the country is not selected region will be disabled.

find.component.ts file

import { Component, OnInit } from '@angular/core';

  selector: 'app-find',
  templateUrl: './find.component.html',
  styleUrls: ['./find.component.css']
export class FindComponent implements OnInit {

  constructor() { }
  //onchange event disabled false
   this.isCountrySelected = false;
  ngOnInit(): void {
    //initially disabled true
    this.isCountrySelected = true;



//Country select option
<select  class="form-control"  (change)="onChangeCountry()" value="Choose Country">
                    <option value="">Choose a Country</option>
                    <option value="US">United States</option>
//region disabled till country is not selected 
<select class="form-control" [disabled]="isCountrySelected">
                    <option value="">Choose a Region</option>
                    <option value="">Any regions.</option>

Count elements with jQuery

use the .size() method or .length attribute

How to detect IE11?

IE11 no longer reports as MSIE, according to this list of changes it's intentional to avoid mis-detection.

What you can do if you really want to know it's IE is to detect the Trident/ string in the user agent if navigator.appName returns Netscape, something like (the untested);

function getInternetExplorerVersion()_x000D_
  var rv = -1;_x000D_
  if (navigator.appName == 'Microsoft Internet Explorer')_x000D_
    var ua = navigator.userAgent;_x000D_
    var re = new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})");_x000D_
    if (re.exec(ua) != null)_x000D_
      rv = parseFloat( RegExp.$1 );_x000D_
  else if (navigator.appName == 'Netscape')_x000D_
    var ua = navigator.userAgent;_x000D_
    var re  = new RegExp("Trident/.*rv:([0-9]{1,}[\\.0-9]{0,})");_x000D_
    if (re.exec(ua) != null)_x000D_
      rv = parseFloat( RegExp.$1 );_x000D_
  return rv;_x000D_
console.log('IE version:', getInternetExplorerVersion());

Note that IE11 (afaik) still is in preview, and the user agent may change before release.

Apache: Restrict access to specific source IP inside virtual host

If you are using apache 2.2 inside your virtual host you should add following directive (mod_authz_host):

Order deny,allow
Deny from all
Allow from

You can even specify a subnet

Allow from 10.0.0

Apache 2.4 looks like a little different as configuration. Maybe better you specify which version of apache are you using.

(Built-in) way in JavaScript to check if a string is a valid number

I used this function as a form validation tool, and I didn't want users to be able to write exponential function, so I came up with this function:


    function isNumber(value, acceptScientificNotation) {

        if(true !== acceptScientificNotation){
            return /^-{0,1}\d+(\.\d+)?$/.test(value);

        if (true === Array.isArray(value)) {
            return false;
        return !isNaN(parseInt(value, 10));

    console.log(isNumber(""));              // false
    console.log(isNumber(false));           // false
    console.log(isNumber(true));            // false
    console.log(isNumber("0"));             // true
    console.log(isNumber("0.1"));           // true
    console.log(isNumber("12"));            // true
    console.log(isNumber("-12"));           // true
    console.log(isNumber(-45));             // true
    console.log(isNumber({jo: "pi"}));      // false
    console.log(isNumber([]));              // false
    console.log(isNumber([78, 79]));        // false
    console.log(isNumber(NaN));             // false
    console.log(isNumber(Infinity));        // false
    console.log(isNumber(undefined));       // false
    console.log(isNumber("0,1"));           // false

    console.log(isNumber("1e-1"));          // false
    console.log(isNumber("1e-1", true));    // true

jQuery: Load Modal Dialog Contents via Ajax

try to use this one.

    url: "yourPageWhereToLoadData.php",
    success: function(data){

        bgiframe: true,
        autoOpen: false,
        height: 100,
        modal: true

Python Socket Receive Large Amount of Data

You can use it as: data = recvall(sock)

def recvall(sock):
    BUFF_SIZE = 4096 # 4 KiB
    data = b''
    while True:
        part = sock.recv(BUFF_SIZE)
        data += part
        if len(part) < BUFF_SIZE:
            # either 0 or end of data
    return data

Cordova app not displaying correctly on iPhone X (Simulator)

For a manual fix to an existing cordova project

The black bars

Add this to your info.plist file. Fixing the launch image is a separate issue i.e. How to Add iPhoneX Launch Image


The white bars

Set viewport-fit=cover in the meta tag

<meta name="viewport" content="initial-scale=1, width=device-width, height=device-height, viewport-fit=cover">

Import Excel Data into PostgreSQL 9.3

For python you could use openpyxl for all 2010 and newer file formats (xlsx).

Al Sweigart has a full tutorial from automate the boring parts on working with excel spreadsheets its very indepth and the whole book and accompanying Udemy course are great resources.

From his example

>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">

Understandably once you have this access you can now use psycopg to parse the data to postgres as you normally would do.

This is a link to a list of python resources at python-excel also xlwings provides a large array of features for using python in place of vba in excel.

Why do we usually use || over |? What is the difference?

The basic difference between them is that | first converts the values to binary then performs the bit wise or operation. Meanwhile, || does not convert the data into binary and just performs the or expression on it's original state.

int two = -2; int four = -4;
result = two | four; // bitwise OR example



Read more:

How to convert a Drawable to a Bitmap?

Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);

This will not work every time for example if your drawable is layer list drawable then it gives a null response, so as an alternative you need to draw your drawable into canvas then save as bitmap, please refer below a cup of code.

public void drawableToBitMap(Context context, int drawable, int widthPixels, int heightPixels) {
    try {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/", "drawable.png");
        FileOutputStream fOut = new FileOutputStream(file);
        Drawable drw = ResourcesCompat.getDrawable(context.getResources(), drawable, null);
        if (drw != null) {
            convertToBitmap(drw, widthPixels, heightPixels).compress(Bitmap.CompressFormat.PNG, 100, fOut);
    } catch (Exception e) {

private Bitmap convertToBitmap(Drawable drawable, int widthPixels, int heightPixels) {
    Bitmap bitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, widthPixels, heightPixels);
    return bitmap;

above code save you're drawable as drawable.png in the download directory

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

This is resolved. The problem was elsewhere. Another code in cron job was truncating XML to 0 length file. I have taken care of that.

Convert Java string to Time, NOT Date

You might consider Joda Time or Java 8, which has a type called LocalTime specifically for a time of day without a date component.

Example code in Joda-Time 2.7/Java 8.

LocalTime t = LocalTime.parse( "17:40" ) ;

How to print HTML content on click of a button, but not the page?

Below Code May Be Help You :

function printPage(id)
   var html="<html>";
   html+= document.getElementById(id).innerHTML;


   var printWin ='','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status  =0');
<div id="block1">
<table border="1" >
<th colspan="3">Block 1</th>


<div id="block2">
    This is Block 2 content

<input type="button" value="Print Block 1" onclick="printPage('block1');"></input>
<input type="button" value="Print Block 2" onclick="printPage('block2');"></input>

Ajax request returns 200 OK, but an error event is fired instead of success

I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.

Then in your Ajax call please mention dataType='text'.

It will resolve the problem.

How to set a Javascript object values dynamically?


myObj['name']=value     (Quotes are required)

Both of these are interchangeable.

Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine:

What is the exact location of MySQL database tables in XAMPP folder?

The exact location is stored in "my.ini" which exists under main mysql installation directory. In my.ini file, look for 'datadir'. This parameter points the data folder.

Alert handling in Selenium WebDriver (selenium 2) with Java

        //Handle the alert pop-up using seithTO alert statement
        Alert alert = driver.switchTo().alert();

        //Print alert is present
        System.out.println("Alert is present");

        //get the message which is present on pop-up
        String message = alert.getText();

        //print the pop-up message

        //Click on OK button on pop-up
    catch (NoAlertPresentException e) 
        //if alert is not present print message
        System.out.println("alert is not present");

Common sources of unterminated string literal

You might try running the script through JSLint.

How to display request headers with command line curl

A popular answer for displaying response headers, but OP asked about request headers.

curl -s -D - -o /dev/null
  • -s : Avoid showing progress bar
  • -D - : Dump headers to a file, but - sends it to stdout
  • -o /dev/null : Ignore response body

This is better than -I as it doesn't send a HEAD request, which can produce different results.

It's better than -v because you don't need so many hacks to un-verbose it.

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

you can use the code:

<asp:Button ID="Button2" runat="server"_x000D_

if nee submit

<form id="form1" runat="server" onsubmit="deshabilita()">_x000D_
<script type="text/javascript">_x000D_
    function deshabilita()_x000D_
        var btn = "<%= Button1.ClientID %>";_x000D_
        if (confirm("Confirme postback"))_x000D_
            document.getElementById(btn).disabled = true;_x000D_
            return true;_x000D_
        return false;_x000D_

Check if enum exists in Java

Based on Jon Skeet answer i've made a class that permits to do it easily at work:


import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

 * <p>
 * This permits to easily implement a failsafe implementation of the enums's valueOf
 * Better use it inside the enum so that only one of this object instance exist for each enum...
 * (a cache could solve this if needed)
 * </p>
 * <p>
 * Basic usage exemple on an enum class called MyEnum:
 *   private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
 *   public static MyEnum failSafeValueOf(String enumName) {
 *       return FAIL_SAFE.valueOf(enumName);
 *   }
 * </p>
 * <p>
 * You can also use it outside of the enum this way:
 *   FailSafeValueOf.create(MyEnum.class).valueOf("EnumName");
 * </p>
 * @author Sebastien Lorber <i>([email protected])</i>
public class FailSafeValueOf<T extends Enum<T>> {

    private final Map<String,T> nameToEnumMap;

    private FailSafeValueOf(Class<T> enumClass) {
        Map<String,T> map = Maps.newHashMap();
        for ( T value : EnumSet.allOf(enumClass)) {
            map.put( , value);
        nameToEnumMap = ImmutableMap.copyOf(map);

     * Returns the value of the given enum element
     * If the 
     * @param enumName
     * @return
    public T valueOf(String enumName) {
        return nameToEnumMap.get(enumName);

    public static <U extends Enum<U>> FailSafeValueOf<U> create(Class<U> enumClass) {
        return new FailSafeValueOf<U>(enumClass);


And the unit test:

import org.testng.annotations.Test;

import static org.testng.Assert.*;

 * @author Sebastien Lorber <i>([email protected])</i>
public class FailSafeValueOfTest {

    private enum MyEnum {

        private static final FailSafeValueOf<MyEnum> FAIL_SAFE = FailSafeValueOf.create(MyEnum.class);
        public static MyEnum failSafeValueOf(String enumName) {
            return FAIL_SAFE.valueOf(enumName);

    public void testInEnum() {
        assertNotNull( MyEnum.failSafeValueOf("TOTO") );
        assertNotNull( MyEnum.failSafeValueOf("TATA") );
        assertNull( MyEnum.failSafeValueOf("TITI") );

    public void testInApp() {
        assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TOTO") );
        assertNotNull( FailSafeValueOf.create(MyEnum.class).valueOf("TATA") );
        assertNull( FailSafeValueOf.create(MyEnum.class).valueOf("TITI") );


Notice that i used Guava to make an ImmutableMap but actually you could use a normal map i think since the map is never returned...

window.location.href doesn't redirect

If you are calling this function through a submit button. This may be the reason why the browser does not redirect. It will run the code in the function and then submit the page instead of redirect. In this case change the type tag of your button.

IO Error: The Network Adapter could not establish the connection

In my case, I needed to specify a viahost and viauser. Worth trying if you're in a complex system. :)

Checking if an object is null in C#

The problem in this case is not that data is null. It is that dataList itself is null.

In the place where you declare dataList you should create a new List object and assign it to the variable.

List<object> dataList = new List<object>();

Import Excel to Datagridview

I used the following code, it's working!

using System.Data.OleDb;
using System.IO;
using System.Text.RegularExpressions;

private void btopen_Click(object sender, EventArgs e)
     OpenFileDialog openFileDialog1 = new OpenFileDialog();  //create openfileDialog Object
     openFileDialog1.Filter = "XML Files (*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb) |*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb";//open file format define Excel Files(.xls)|*.xls| Excel Files(.xlsx)|*.xlsx| 
     openFileDialog1.FilterIndex = 3;

     openFileDialog1.Multiselect = false;        //not allow multiline selection at the file selection level
     openFileDialog1.Title = "Open Text File-R13";   //define the name of openfileDialog
     openFileDialog1.InitialDirectory = @"Desktop"; //define the initial directory

     if (openFileDialog1.ShowDialog() == DialogResult.OK)        //executing when file open
       string pathName = openFileDialog1.FileName;
       fileName = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
       DataTable tbContainer = new DataTable();
       string strConn = string.Empty;
       string sheetName = fileName;

       FileInfo file = new FileInfo(pathName);
       if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
       string extension = file.Extension;
       switch (extension)
          case ".xls":
                   strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
          case ".xlsx":
                   strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
                   strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
         OleDbConnection cnnxls = new OleDbConnection(strConn);
         OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);

         dtGrid.DataSource = tbContainer;

     catch (Exception)

How to convert a ruby hash object to JSON?

One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).

So, take a look here:

car = {:make => "bmw", :year => "2003"}
# => {:make=>"bmw", :year=>"2003"}
# NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
#   from (irb):11
#   from /usr/bin/irb:12:in `<main>'
require 'json'
# => true
# => "{"make":"bmw","year":"2003"}"

As you can see, requiring json has magically brought method to_json to our Hash.

What linux shell command returns a part of a string?

In bash you can try this:

#       0123456789.....
#       0-based indexing.

echo ${stringZ:0:2} # prints ab

More samples in The Linux Documentation Project

How to capture multiple repeated groups?

After reading Byte Commander's answer, I want to introduce a tiny possible improvement:

You can generate a regexp that will match either n words, as long as your n is predetermined. For instance, if I want to match between 1 and 3 words, the regexp:


will match the next sentences, with one, two or three capturing groups.


You can see a fully detailed explanation about this regular expression on Regex101.

As I said, it is pretty easy to generate this regexp for any groups you want using your favorite language. Since I'm not much of a swift guy, here's a ruby example:

def make_regexp(group_regexp, count: 3, delimiter: ",")
  regexp_str = "^(#{group_regexp})"
  (count - 1).times.each do
    regexp_str += "(?:#{delimiter}(#{group_regexp}))?"
  regexp_str += "$"
  return regexp_str

puts make_regexp("[A-Z]+")

That being said, I'd suggest not using regular expression in that case, there are many other great tools from a simple split to some tokenization patterns depending on your needs. IMHO, a regular expression is not one of them. For instance in ruby I'd use something like str.split(",") or str.scan(/[A-Z]+/)

How to suspend/resume a process in Windows?

Without any external tool you can simply accomplish this on Windows 7 or 8, by opening up the Resource monitor and on the CPU or Overview tab right clicking on the process and selecting Suspend Process. The Resource monitor can be started from the Performance tab of the Task manager.

How to check that a JCheckBox is checked?

Use the isSelected method.

You can also use an ItemListener so you'll be notified when it's checked or unchecked.

How to redirect to another page using PHP

That's the problem. I've outputted a bunch of information (including the HTML to build the login page itself). So how do I redirect the user from one page to the next?

This means your application design is pretty broken. You shouldn't be doing output while your business logic is running. Go an use a template engine (like Smarty) or quickfix it by using output buffering).

Another option (not a good one though!) would be outputting JavaScript to redirect:

<script type="text/javascript">location.href = 'newurl';</script>

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

Stored procedures can be executed like below

 string cmd = Constants.StoredProcs.usp_AddRoles.ToString() + " @userId, @roleIdList";
                        int result = db.Database
                                           new SqlParameter("@userId", userId),
                                           new SqlParameter("@roleIdList", roleId)

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

I have got the same error as :

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools":

As, said by @Agaline, i download the outside wheel from this Christoph Gohlke.

If your is Python 3.7 then try to PyAudio-0.2.11-cp37-cp37m-win_amd64.whl and use command as, go to the download directroy and:

pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl and it works.

Calling Python in PHP

Your call_python_file.php should look like this:

    $item='Everything is awesome!!';
    $tmp = exec(" $item");
    echo $tmp;

This executes the python script and outputs the result to the browser. While in your python script the (sys.argv[1:]) variable will bring in all your arguments. To display the argv as a string for wherever your php is pulling from so if you want to do a text area:

import sys

list1 = ' '.join(sys.argv[1:])

def main():
  print list1

if __name__ == '__main__':

How can I convert a DOM element to a jQuery element?

So far best solution that I've made:

function convertHtmlToJQueryObject(html){
    var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
    return $(htmlDOMObject.documentElement);

No newline after div?

This works the best, in my case, I tried it all

.div_class {
    clear: left;

mongodb how to get max value from collections

you can use group and max:

        $group: {
            _id: null,
            maxQuantity: {$max: "$age"}

Using C++ filestreams (fstream), how can you determine the size of a file?

You can seek until the end, then compute the difference:

std::streampos fileSize( const char* filePath ){

    std::streampos fsize = 0;
    std::ifstream file( filePath, std::ios::binary );

    fsize = file.tellg();
    file.seekg( 0, std::ios::end );
    fsize = file.tellg() - fsize;

    return fsize;

git diff between cloned and original remote repository

Another reply to your questions (assuming you are on master and already did "git fetch origin" to make you repo aware about remote changes):

1) Commits on remote branch since when local branch was created:

git diff HEAD...origin/master

2) I assume by "working copy" you mean your local branch with some local commits that are not yet on remote. To see the differences of what you have on your local branch but that does not exist on remote branch run:

git diff origin/master...HEAD

3) See the answer by dbyrne.

Rails: update_attribute vs update_attributes

update_attribute and update_attributes are similar, but with one big difference: update_attribute does not run validations.


  • update_attribute is used to update record with single attribute.

    Model.update_attribute(:column_name, column_value1)
  • update_attributes is used to update record with multiple attributes.

    Model.update_attributes(:column_name1 => column_value1, :column_name2 => column_value2, ...)

These two methods are really easy to confuse given their similar names and works. Therefore, update_attribute is being removed in favor of update_column.

Now, in Rails4 you can use Model.update_column(:column_name, column_value) at the place of Model.update_attribute(:column_name, column_value)

Click here to get more info about update_column.

Length of the String without using length() method

We can iterate through the string like a character array, and count that way (A much more down to earth way of doing it):

String s = "foo"
char arr[]=s.toCharArray();
int len = 0;
for(char single : arr){

Using the "foreach" version of the for loop

Difference between Big-O and Little-O Notation

In general

Asymptotic notation is something you can understand as: how do functions compare when zooming out? (A good way to test this is simply to use a tool like Desmos and play with your mouse wheel). In particular:

  • f(n) ? o(n) means: at some point, the more you zoom out, the more f(n) will be dominated by n (it will progressively diverge from it).
  • g(n) ? T(n) means: at some point, zooming out will not change how g(n) compare to n (if we remove ticks from the axis you couldn't tell the zoom level).

Finally h(n) ? O(n) means that function h can be in either of these two categories. It can either look a lot like n or it could be smaller and smaller than n when n increases. Basically, both f(n) and g(n) are also in O(n).

In computer science

In computer science, people will usually prove that a given algorithm admits both an upper O and a lower bound . When both bounds meet that means that we found an asymptotically optimal algorithm to solve that particular problem.

For example, if we prove that the complexity of an algorithm is both in O(n) and (n) it implies that its complexity is in T(n). That's the definition of T and it more or less translates to "asymptotically equal". Which also means that no algorithm can solve the given problem in o(n). Again, roughly saying "this problem can't be solved in less than n steps".

An upper bound of O(n) simply means that even in the worse case, the algorithm will terminate in at most n steps (ignoring all constant factors, both multiplicative and additive). A lower bound of (n) means on the opposite that we built some examples where the problem solved by this algorithm couldn't be solved in less than n steps (again ignoring multiplicative and additive constants). The number of steps is at most n and at least n so this problem complexity is "exactly n". Instead of saying "ignoring constant multiplicative/additive factor" every time we just write T(n) for short.

"for loop" with two variables?

For your use case, it may be easier to utilize a while loop.

t1 = [137, 42]
t2 = ["Hello", "world"]

i = 0
j = 0
while i < len(t1) and j < len(t2):
    print t1[i], t2[j]
    i += 1
    j += 1

# 137 Hello
# 42 world

As a caveat, this approach will truncate to the length of your shortest list.

Show just the current branch in Git

I guess this should be quick and can be used with a Python API:

git branch --contains HEAD
* master

Generate a Hash from string in Javascript

About half of the answers here are the same String.hashCode hash function taken from Java. It dates back to 1981 from Gosling Emacs, is extremely weak, and makes zero sense performance-wise in modern JavaScript. In fact, implementations could be significantly faster by using ES6 Math.imul, but no one took notice. We can do much better than this, at essentially identical performance.

Here's something I did—cyrb53, a simple but high quality 53-bit hash. It's quite fast, provides very good hash distribution, and has significantly lower collision rates compared to any 32-bit hash.

const cyrb53 = function(str, seed = 0) {
    let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
    for (let i = 0, ch; i < str.length; i++) {
        ch = str.charCodeAt(i);
        h1 = Math.imul(h1 ^ ch, 2654435761);
        h2 = Math.imul(h2 ^ ch, 1597334677);
    h1 = Math.imul(h1 ^ (h1>>>16), 2246822507) ^ Math.imul(h2 ^ (h2>>>13), 3266489909);
    h2 = Math.imul(h2 ^ (h2>>>16), 2246822507) ^ Math.imul(h1 ^ (h1>>>13), 3266489909);
    return 4294967296 * (2097151 & h2) + (h1>>>0);

It is similar to the well-known MurmurHash/xxHash algorithms, it uses a combination of multiplication and Xorshift to generate the hash, but not as thorough. As a result it's faster than either in JavaScript and significantly simpler to implement. Furthermore, keep in mind this is not a secure algorithm, if privacy/security is a concern, this is not for you.

Like any proper hash, it has an avalanche effect, which basically means small changes in the input have big changes in the output making the resulting hash appear more 'random':

"501c2ba782c97901" = cyrb53("a")
"459eda5bc254d2bf" = cyrb53("b")
"fbce64cc3b748385" = cyrb53("revenge")
"fb1d85148d13f93a" = cyrb53("revenue")

You can also supply a seed for alternate streams of the same input:

"76fee5e6598ccd5c" = cyrb53("revenue", 1)
"1f672e2831253862" = cyrb53("revenue", 2)
"2b10de31708e6ab7" = cyrb53("revenue", 3)

Technically, it is a 64-bit hash, that is, two uncorrelated 32-bit hashes computed in parallel, but JavaScript is limited to 53-bit integers. If convenient, the full 64-bit output can be used by altering the return statement with a hex string or array.

return [h2>>>0, h1>>>0];
// or
return (h2>>>0).toString(16).padStart(8,0)+(h1>>>0).toString(16).padStart(8,0);

Be aware that constructing hex strings drastically slows down batch processing. The array is more efficient, but obviously requires two checks instead of one.

Just for fun, here's the smallest hash I could come up with that's still decent. It's a 32-bit hash in 89 chars with better quality randomness than even FNV or DJB2:

TSH=s=>{for(var i=0,h=9;i<s.length;)h=Math.imul(h^s.charCodeAt(i++),9**9);return h^h>>>9}

How to set environment variables in Jenkins?

Normally you can configure Environment variables in Global properties in Configure System.

However for dynamic variables with shell substitution, you may want to create a script file in Jenkins HOME dir and execute it during the build. The SSH access is required. For example.

  1. Log-in as Jenkins: sudo su - jenkins or sudo su - jenkins -s /bin/bash
  2. Create a shell script, e.g.:

    echo 'export VM_NAME="$JOB_NAME"' > ~/
    echo "export AOEU=$(echo aoeu)" >> ~/
    chmod 750 ~/
  3. In Jenkins Build (Execute shell), invoke the script and its variables before anything else, e.g.

    source ~/

How to enter in a Docker container already running with a new TTY

With docker 1.3, there is a new command docker exec. This allows you to enter a running container:

docker exec -it [container-id] bash

Check if passed argument is file or directory in Bash

Using the "file" command may be useful for this:


if [ -z "${1}" ] ;then
 echo "Please input something"

result="$(file $f)"
if [[ $result == *"cannot open"* ]] ;then
        echo "NO FILE FOUND ($result) ";
elif [[ $result == *"directory"* ]] ;then
        echo "DIRECTORY FOUND ($result) ";
        echo "FILE FOUND ($result) ";


check_file "${1}"

Output examples :

$ ./f.bash login
DIRECTORY FOUND (login: directory) 
$ ./f.bash ldasdas
NO FILE FOUND (ldasdas: cannot open `ldasdas' (No such file or  directory)) 
$ ./f.bash evil.php 
FILE FOUND (evil.php: PHP script, ASCII text) 

FYI: the answers above work but you can use -s to help in weird situations by checking for a valid file first:


    local file="${1}"
    [[ -s "${file}" ]] || { echo "is not valid"; return; } 
    [[ -d "${file}" ]] && { echo "is a directory"; return; }
    [[ -f "${file}" ]] && { echo "is a file"; return; }

check_file ${1}

go get results in 'terminal prompts disabled' error for github private repo

I found this extremely helpful, and it solved my problem. This command will allow your 2FA to do its thing (and save you the trouble of entering your username and password):

git config --global --add url."[email protected]:".insteadOf ""


If you're not using 2FA, you can still use SSH and this will work.

Edit: added the --add flag as suggested by slatunje.

How to declare a local variable in Razor?

If you want a variable to be accessible across the entire page, it works well to define it at the top of the file. (You can use either an implicit or explicit type.)

    // implicit type
    var something1 = "something";

    // explicit type
    string something2 = "something";

<div>@something1</div> @*display first variable*@
<div>@something2</div> @*display second variable*@

Nullable type as a generic parameter possible?

I think you want to handle Reference types and struct types. I use it to convert XML Element strings to a more typed type. You can remove the nullAlternative with reflection. The formatprovider is to handle the culture dependent '.' or ',' separator in e.g. decimals or ints and doubles. This may work:

public T GetValueOrNull<T>(string strElementNameToSearchFor, IFormatProvider provider = null ) 
        IFormatProvider theProvider = provider == null ? Provider : provider;
        XElement elm = GetUniqueXElement(strElementNameToSearchFor);

        if (elm == null)
            object o =  Activator.CreateInstance(typeof(T));
            return (T)o; 
                Type type = typeof(T);
                if (type.IsGenericType &&
                type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
                    type = Nullable.GetUnderlyingType(type);
                return (T)Convert.ChangeType(elm.Value, type, theProvider); 
            catch (Exception)
                object o = Activator.CreateInstance(typeof(T));
                return (T)o; 

You can use it like this:

iRes = helper.GetValueOrNull<int?>("top_overrun_length");
Assert.AreEqual(100, iRes);

decimal? dRes = helper.GetValueOrNull<decimal?>("top_overrun_bend_degrees");
Assert.AreEqual(new Decimal(10.1), dRes);

String strRes = helper.GetValueOrNull<String>("top_overrun_bend_degrees");
Assert.AreEqual("10.1", strRes);

Fastest way to update 120 Million records

I break the task up into smaller units. Test with different batch size intervals for your table, until you find an interval that performs optimally. Here is a sample that I have used in the past.

declare @counter int 
declare @numOfRecords int
declare @batchsize int

set @numOfRecords = (SELECT COUNT(*) AS NumberOfRecords FROM <TABLE> with(nolock))
set @counter = 0 
set @batchsize = 2500

set rowcount @batchsize
while @counter < (@numOfRecords/@batchsize) +1
set @counter = @counter + 1 
Update table set int_field = -1 where int_field <> -1;
set rowcount 0

Detect change to selected date with bootstrap-datepicker

Based on Irvin Dominin example, I've created 2 examples supporting Paste and hit Enter.

This works in Chrome:

$(document).ready(function() {
      format: 'dd/mm/yyyy',
      assumeNearbyYear: true,
      autoclose: true,
      orientation: 'bottom right',
      todayHighlight: true,
      keyboardNavigation: false
    /* On 'paste' -> loses focus, hide calendar and trigger 'change' */
    .on('paste', function(e) {
    /* On 'enter' keypress -> loses focus and trigger 'change' */
    .on('keydown', function(e) {

      if (e.which === 13) {
    .change(function(e) {
      $('#stdout').append($('#date-daily').val() + ' change\n');

But not in IE, so I created another example for IE11:,js,console,output

$(document).ready(function() {
      format: 'dd/mm/yyyy',
      assumeNearbyYear: true,
      autoclose: true,
      orientation: 'bottom right',
      todayHighlight: true,
      keyboardNavigation: false
    // OnEnter -> lose focus
    .on('keydown', function(e) {
         if (e.which === 13){ 
    // onPaste -> hide and lose focus
    .on('keyup', function(e) {
         if (e.which === 86){ 
    .change(function(e) {
       $('#stdout').append($('#date-daily').val() + ' change\n');

If last example still doesn't work in IE11, you can try splitting the setup:

// DatePicker setup
    format: 'dd/mm/yyyy',
    assumeNearbyYear: true,      /* manually-entered dates with two-digit years, such as '5/1/15', will be parsed as '2015', not '15' */
    autoclose: true,             /* close the datepicker immediately when a date is selected */
    orientation: 'bottom rigth',
    todayHighlight: true,        /* today appears with a blue box */
    keyboardNavigation: false    /* select date only onClick. when true, is too difficult free typing  */

And the event handlers: (note I'm not using $('.datepicker').datepicker({)

   // Smoker DataPicker behaviour
    // OnEnter -> lose focus
    .on('keydown', function (e) {
        if (e.which === 13){ 
    // onPaste -> hide and lose focus
    .on('keyup', function (e) {
        if (e.which === 86){ 
    .change(function (e) {
        // do saomething

How to set the default value for radio buttons in AngularJS?

Set a default value for people with ngInit

<div ng-app>
    <div ng-init="people=1" />
        <input type="radio" ng-model="people" value="1"><label>1</label>
        <input type="radio" ng-model="people" value="2"><label>2</label>
        <input type="radio" ng-model="people" value="3"><label>3</label>

Demo: Fiddle

How to view data saved in android database(SQLite)?

Try this..

  1. Download the Sqlite Manager jar file here.

  2. Add it to your eclipse > dropins Directory.

  3. Restart eclipse.

  4. Launch the compatible emulator or device

  5. Run your application.

  6. Go to Window > Open Perspective > DDMS >

  7. Choose the running device.

  8. Go to File Explorer tab.

  9. Select the directory called databases under your application's package.

  10. Select the .db file under the database directory.

  11. Then click Sqlite manager icon like this Sqlite manager icon.

  12. Now you're able to see the .db file.

Happy coding.....

Copy folder recursively in Node.js

Since I'm just building a simple Node.js script, I didn't want the users of the script to need to import a bunch of external modules and dependencies, so I put on my thinking cap and did a search for running commands from the Bash shell.

This Node.js code snippet recursively copies a folder called to a folder called build:

child = exec("cp -r build", function(error, stdout, stderr) {
    sys.print("stdout: " + stdout);
    sys.print("stderr: " + stderr);
    if(error !== null) {
        console.log("exec error: " + error);
    } else {


Thanks to Lance Pollard at dzone for getting me started.

The above snippet is limited to Unix-based platforms, like macOS and Linux, but a similar technique may work for Windows.

Special characters like @ and & in cURL POST data

cURL > 7.18.0 has an option --data-urlencode which solves this problem. Using this, I can simply send a POST request as

curl -d name=john --data-urlencode passwd=@31&3*J

How can I get the current page's full URL on a Windows/IIS server?

REQUEST_URI is set by Apache, so you won't get it with IIS. Try doing a var_dump or print_r on $_SERVER and see what values exist there that you can use.

height style property doesn't work in div elements

You're loosing your height attribute because you're changing the block element to inline (it's now going to act like a <p>). You're probably picking up that 14px height because of the text height inside your in-line div.

Inline-block may work for your needs, but you may have to implement a work around or two for cross-browser support.

IE supports inline-block, but only for elements that are natively inline.

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

I'm running SQL Developer build 188.1159 which does indeed contain data modeling capability. I just created a relational model diagram via the menu: File->Data Modeler->Import->Data Dictionary....

I also have the stand-alone Data Modeler, which does the same thing.

As the Data Modeler tutorial states:

Figure 4: Relational model and diagram for HR

The diagram you’ve generated is not an ERD. Logical models are higher abstractions. An ERD represents entities and their attributes and relations, whereas a relational or physical model represents tables, columns, and foreign keys."

Environment variables in Jenkins

The quick and dirty way, you can view the available environment variables from the below link.


Just replace localhost with your Jenkins hostname, if its different

Initialize a string in C to empty string

It's a bit late but I think your issue may be that you've created a zero-length array, rather than an array of length 1.

A string is a series of characters followed by a string terminator ('\0'). An empty string ("") consists of no characters followed by a single string terminator character - i.e. one character in total.

So I would try the following:

string[1] = ""

Note that this behaviour is not the emulated by strlen, which does not count the terminator as part of the string length.

Automating the InvokeRequired code pattern

You could write an extension method:

public static void InvokeIfRequired(this Control c, Action<Control> action)
        c.Invoke(new Action(() => action(c)));

And use it like this:

object1.InvokeIfRequired(c => { c.Visible = true; });

EDIT: As Simpzon points out in the comments you could also change the signature to:

public static void InvokeIfRequired<T>(this T c, Action<T> action) 
    where T : Control

keycloak Invalid parameter: redirect_uri

If you're trying to redirect to the keycloak login page after logout (as I was), that is not allowed by default but also needs to be configured in the "Valid Redirect URIs" setting in the admin console of your client.

(WAMP/XAMP) send Mail using SMTP localhost

Method 1 (Preferred) - Using hMailServer

After installation, you need the following configuration to properly send mail from wampserver:

1) When you first open hMailServer Administrator, you need to add a new domain.
2) Click on the "Add Domain ..." button at the Welcome page. 
3) Under the domain text field, enter your computer's IP, in this case it should be
4) Click on the Save button.
5) Go to Settings>Protocols>SMTP and select "Delivery of Email" tab
6) Enter "localhost" in the localhost name field.
7) Click on the Save button.

If you need to send mail using a FROM addressee of another computer, you need to allow deliveries from External to External accounts. To do that, follow these steps:

1) Go to Settings>Advanced>IP Ranges and double click on "My Computer" which should have IP address of
2) Check the Allow Deliveries from External to External accounts checkbox.
3) Save settings using Save button.

(However, Windows Live/Hotmail has denied all emails coming from dynamic IPs, which most residential computers are using. The workaround is to use Gmail account )

Note to use Gmail users :

1) Go to Settings>Protocols>SMTP and select "Delivery of Email" tab
2) Enter "" in the Remote Host name field.
3) Enter "465" as the port number
4) Check "Server requires authentication"
5) Enter gmail address in the Username
6) Enter gmail password in the password 
7) Check "Use SSL"

(Note, From field doesnt function with gmail)
*p.s. For some people it might also be needed to untick everything under require SMTP authentication in :

  • for local : Settings>Advanced>IP Ranges>"My Computer"
  • for external : Settings>Advanced>IP Ranges>"Internet"

Method 2 - Using SendMail

You can use SendMail installation.

Method 3 - Using different methods

Use any of these methods.

fatal: bad default revision 'HEAD'

Make sure branch "master" exists! It's not just a name apparently.

I got this error after creating a blank bare repo, pushing a branch named "dev" to it, and trying to use git log in the bare repo. Interestingly, git branch knows that dev is the only branch existing (so I think this is a git bug).

Solution: I repeated the procedure, this time having renamed "dev" to "master" on the working repo before pushing to the bare repo. Success!

Android SDK installation doesn't find JDK

Setting the JAVA_HOME environment variable to

C:\Program Files\Java\jdk1.7.0_07

instead of

C:\Program Files\Java\jdk1.7.0_07\bin

fixed it for me.

What is the difference between x86 and x64

If you download Java Development Kit(JDK) then there is a difference as it contains native libraries which differ for different architectures:

  • x86 is for 32-bit OS
  • x64 is for 64-bit OS

In addition you can use 32-bit JDK(x86) on 64-bit OS. But you can not use 64-bit JDK on 32-bit OS.

At the same time you can run compiled Java classes on any JVM. It does not matter whether it 32 or 64-bit.

How do I remove packages installed with Python's easy_install?

To uninstall an .egg you need to rm -rf the egg (it might be a directory) and remove the matching line from site-packages/easy-install.pth

using stored procedure in entity framework

// Add some tenants to context so we have something for the procedure to return! AddTenentsToContext(Context);

    // ACT
    // Get the results by calling the stored procedure from the context extention method 
    var results = Context.ExecuteStoredProcedure(procedure);

    // ASSERT
    Assert.AreEqual(expectedCount, results.Count);

How to increase dbms_output buffer?

Here you go:

  dbms_output.enable(NULL); -- Disables the limit of DBMS
  -- Your print here !

PHP - Get key name of array value

If i understand correctly, can't you simply use:

foreach($arr as $key=>$value)
  echo $key;

See PHP manual

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

Follow the tutorial you listed above for setting up your key preferences in iterm2.

  1. Create a new shorcut key
  2. Choose "Send escape sequence" as the action
  3. Then, to set cmd-left, in the text below that:
    • Enter [H for line start
    • Enter [F for line end

Out-File -append in Powershell does not produce a new line and breaks string into characters

Out-File defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii to change this behavior. In your case

Out-File -Encoding Ascii -append textfile.txt. 

Add-Content uses Ascii and also appends by default.

"This is a test" | Add-Content textfile.txt.

As for the lack of newline: You did not send a newline so it will not write one to file.

How to prevent column break within an element?

Firefox 26 seems to require

page-break-inside: avoid;

And Chrome 32 needs


Kill some processes by .exe file name

public void EndTask(string taskname)
      string processName = taskname.Replace(".exe", "");

      foreach (Process process in Process.GetProcessesByName(processName))


Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.

Does Python have “private” variables in classes?

The only time I ever use private variables is when I need to do other things when writing to or reading from the variable and as such I need to force the use of a setter and/or getter.

Again this goes to culture, as already stated. I've been working on projects where reading and writing other classes variables was free-for-all. When one implementation became deprecated it took a lot longer to identify all code paths that used that function. When use of setters and getters was forced, a debug statement could easily be written to identify that the deprecated method had been called and the code path that calls it.

When you are on a project where anyone can write an extension, notifying users about deprecated methods that are to disappear in a few releases hence is vital to keep module breakage at a minimum upon upgrades.

So my answer is; if you and your colleagues maintain a simple code set then protecting class variables is not always necessary. If you are writing an extensible system then it becomes imperative when changes to the core is made that needs to be caught by all extensions using the code.

How to convert buffered image to image and vice-versa?

Example: say you have an 'image' you want to scale you will need a bufferedImage probably, and probably will be starting out with just 'Image' object. So this works I think... The AVATAR_SIZE is the target width we want our image to be:

Image imgData = image.getScaledInstance(Constants.AVATAR_SIZE, -1, Image.SCALE_SMOOTH);     

BufferedImage bufferedImage = new BufferedImage(imgData.getWidth(null), imgData.getHeight(null), BufferedImage.TYPE_INT_RGB);

bufferedImage.getGraphics().drawImage(imgData, 0, 0, null);

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:


And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

Why does this "Slow network detected..." log appear in Chrome?

As soon as I disabled the DuckDuckGo Privacy Essentials plugin it disappeared. Bit annoying as the fonts I was serving was from localhost so shouldn't be anything to do with a slow network connection.

Parsing HTTP Response in Python

I guess things have changed in python 3.4. This worked for me:

print("resp:" + json.dumps(resp.json()))

Switching to landscape mode in Android Emulator

If you can not switch to landscape(or portrait) while using ctr+f11/12 Maybe the virtual device (android phone) itself lock the rotation. Going to the android control center (pull down on the home page), and unlock.

"A lambda expression with a statement body cannot be converted to an expression tree"

Is Arr a base type of Obj? Does the Obj class exist? Your code would work only if Arr is a base type of Obj. You can try this instead:

Obj[] myArray = objects.Select(o =>
    var someLocalVar = o.someVar;

    return new Obj() 
       Var1 = someLocalVar,
       Var2 = o.var2 

How can I update npm on Windows?

You can update your npm to the latest stable version with the following command:

 npm install npm@latest -g

Use PowerShell to run it. This command doesn't need windows administrator privileges and you can verify the result with npm -v


There won't be much difference. Howver version 2 is easier when you have some calculations, aggregations, etc that should be joined outside of it

--Version 2 
SELECT p.Name, s.OrderQty 
FROM Product p 
(SELECT ProductID, SUM(OrderQty) as OrderQty FROM SalesOrderDetail GROUP BY ProductID
HAVING SUM(OrderQty) >1000) s 
on p.ProductID = s.ProdctId 

How to style a JSON block in Github Wiki?

2019 Github Solution

   "this-json": "looks awesome..."


enter image description here

If you want to have keys a different colour to the parameters, set your language as yaml

@Ankanna's answer gave me the idea of going through github's supported language list and yaml was my best find.

Uploading Images to Server android

Try this method for uploading Image file from camera

package com.example.imageupload;


import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;

public class MultipartEntity implements HttpEntity {

private String boundary = null;

ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;

public MultipartEntity() {
    this.boundary = System.currentTimeMillis() + "";

public void writeFirstBoundaryIfNeeds() {
    if (!isSetFirst) {
        try {
            out.write(("--" + boundary + "\r\n").getBytes());
        } catch (final IOException e) {

    isSetFirst = true;

public void writeLastBoundaryIfNeeds() {
    if (isSetLast) {
    try {
        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
    } catch (final IOException e) {

    isSetLast = true;

public void addPart(final String key, final String value) {
    try {
        out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
        out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
        out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
        out.write(("\r\n--" + boundary + "\r\n").getBytes());
    } catch (final IOException e) {


public void addPart(final String key, final String fileName,
        final InputStream fin) {
    addPart(key, fileName, fin, "application/octet-stream");

public void addPart(final String key, final String fileName,
        final InputStream fin, String type) {
    try {
        type = "Content-Type: " + type + "\r\n";
        out.write(("Content-Disposition: form-data; name=\"" + key
                + "\"; filename=\"" + fileName + "\"\r\n").getBytes());
        out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());

        final byte[] tmp = new byte[4096];
        int l = 0;
        while ((l = != -1) {
            out.write(tmp, 0, l);
    } catch (final IOException e) {

    } finally {
        try {
        } catch (final IOException e) {


public void addPart(final String key, final File value) {
    try {
        addPart(key, value.getName(), new FileInputStream(value));
    } catch (final FileNotFoundException e) {


public long getContentLength() {
    return out.toByteArray().length;

public Header getContentType() {
    return new BasicHeader("Content-Type", "multipart/form-data; boundary="
            + boundary);

public boolean isChunked() {
    return false;

public boolean isRepeatable() {
    return false;

public boolean isStreaming() {
    return false;

public void writeTo(final OutputStream outstream) throws IOException {

public Header getContentEncoding() {
    return null;

public void consumeContent() throws IOException,
        UnsupportedOperationException {
    if (isStreaming()) {
        throw new UnsupportedOperationException(
                "Streaming entity does not implement #consumeContent()");

public InputStream getContent() throws IOException,
        UnsupportedOperationException {
    return new ByteArrayInputStream(out.toByteArray());


Use of class for uploading

private void doFileUpload(File file_path) {

    Log.d("Uri", "Do file path" + file_path);

    try {

        HttpClient client = new DefaultHttpClient();
        //use your server path of php file
        HttpPost post = new HttpPost(ServerUploadPath);

        Log.d("ServerPath", "Path" + ServerUploadPath);

        FileBody bin1 = new FileBody(file_path);
        Log.d("Enter", "Filebody complete " + bin1);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("uploaded_file", bin1);
        reqEntity.addPart("email", new StringBody(useremail));

        Log.d("Enter", "Image send complete");

        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        Log.d("Enter", "Get Response");
        try {

            final String response_str = EntityUtils.toString(resEntity);
            if (resEntity != null) {
                Log.i("RESPONSE", response_str);
                JSONObject jobj = new JSONObject(response_str);
                result = jobj.getString("ResponseCode");
                Log.e("Result", "...." + result);

        } catch (Exception ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        Log.e("Upload Exception", "");

Service for uploading

$image_name = $_FILES["uploaded_file"]["name"]; 
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;    

if (file_exists("Images/".$new_image_name))
           $msg=$new_image_name . " already exists."
           header('Content-type: application/json');        
           echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));        
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
                   $flag = 1;

if($flag == 1){                    
            require 'db.php';   
            $static_url =$new_image_name;
            $conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
            $db=mysql_select_db($db_database,$conn) or die("unable to select message_app"); 
            $email = "";
                     $email = $_REQUEST['email'];

    $sql ="insert into alert(images) values('$static_url')";


    echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
       } else

         echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
    echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));

How to create a responsive image that also scales up in Bootstrap 3

I found that you can put the .col class on the image will do the trick - however this gives it extra padding along with any other attributes associated with the class such as float left, however these can be cancelled by say for example a no padding class as an addition.

Bootstrap 3 2-column form layout

As mentioned earlier, you can use the grid system to layout your inputs and labels anyway that you want. The trick is to remember that you can use rows within your columns to break them into twelfths as well.

The example below is one possible way to accomplish your goal and will put the two text boxes near Label3 on the same line when the screen is small or larger.

<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
    <meta charset="utf-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link href="" rel="stylesheet"/>_x000D_
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->_x000D_
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
    <!--[if lt IE 9]>_x000D_
      <script src=""></script>_x000D_
      <script src=""></script>_x000D_
    <div class="row">_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <input class="form-control" type="text"/>_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <input class="form-control" type="text"/>_x000D_
        <div class="col-xs-6">_x000D_
            <div class="row">_x000D_
                <label class="col-xs-12">Label3</label>_x000D_
            <div class="row">_x000D_
                <div class="col-xs-12 col-sm-6">_x000D_
                    <input class="form-control" type="text"/>_x000D_
                <div class="col-xs-12 col-sm-6">_x000D_
                    <input class="form-control" type="text"/>_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <input class="form-control" type="text"/>_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?


Just use method "text()".

The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.

In Maven how to exclude resources from the generated jar?

Another possibility is to use the Maven Shade Plugin, e.g. to exclude a logging properties file used only locally in your IDE:


This will however exclude the files from every artifact, so it might not be feasible in every situation.

htaccess redirect to https://www

I used the below code from this website, it works great

RewriteEngine On_x000D_
RewriteCond %{SERVER_PORT} 80_x000D_
RewriteRule ^(.*)$$1 [R,L]

Hope it helps

Is there a Python caching library?

You can use my simple solution to the problem. It is really straightforward, nothing fancy:

class MemCache(dict):
    def __init__(self, fn):
        self.__fn = fn

    def __getitem__(self, item):
        if item not in self:
            dict.__setitem__(self, item, self.__fn(item))
        return dict.__getitem__(self, item)

mc = MemCache(lambda x: x*x)

for x in xrange(10):
    print mc[x]

for x in xrange(10):
    print mc[x]

It indeed lacks expiration funcionality, but you can easily extend it with specifying a particular rule in MemCache c-tor.

Hope code is enough self-explanatory, but if not, just to mention, that cache is being passed a translation function as one of its c-tor params. It's used in turn to generate cached output regarding the input.

Hope it helps

Update records using LINQ

public ActionResult OrderDel(int id)
        string a = Session["UserSession"].ToString();
        var s = (from test in ob.Order_Details where test.Email_ID_Fk == a && test.Order_ID == id select test).FirstOrDefault();
        s.Status = "Order Cancel By User";
        //foreach(var updter in s)
        //    updter.Status = "Order Cancel By User";

        return Json("Sucess", JsonRequestBehavior.AllowGet);
    } <script>
            function Cancel(id) {
                if (confirm("Are your sure ? Want to Cancel?")) {

                        type: 'POST',
                        url: '@Url.Action("OrderDel", "Home")/' + id,
                        datatype: 'JSON',
                        success: function (Result) {
                            if (Result == "Sucess")
                                alert("Your Order has been Canceled..");
                        error: function (Msgerror) {



How do I correctly upgrade angular 2 (npm) to the latest version?

Another nice package which I used for migrating form a beta version of Angular2 to Angular2 2.0.0 final is npm-check-updates

It shows the latest available version of all packages specified within your package.json. In contrast to npm outdated it is also capable to edit your package.json, enabling you to do a npm upgrade later.


sudo npm install -g npm-check-updates


ncufor display

ncu -u for re-writing your package.json

Sass nth-child nesting

You're trying to do &(2), &(4) which won't work

#romtest {
  .detailed {
    th {
      &:nth-child(2) {//your styles here}
      &:nth-child(4) {//your styles here}
      &:nth-child(6) {//your styles here}

Regarding C++ Include another class

When you want to convert your code to result( executable, library or whatever ), there is 2 steps:
1) compile
2) link
In first step compiler should now about some things like sizeof objects that used by you, prototype of functions and maybe inheritance. on the other hand linker want to find implementation of functions and global variables in your code.

Now when you use ClassTwo in File1.cpp compiler know nothing about it and don't know how much memory should allocate for it or for example witch members it have or is it a class and enum or even a typedef of int, so compilation will be failed by the compiler. adding File2.cpp solve the problem of linker that look for implementation but the compiler is still unhappy, because it know nothing about your type.

So remember, in compile phase you always work with just one file( and of course files that included by that one file ) and in link phase you need multiple files that contain implementations. and since C/C++ are statically typed and they allow their identifier to work for many purposes( definition, typedef, enum class, ... ) so you should always identify you identifier to the compiler and then use it and as a rule compiler should always know size of your variable!!

Java : How to determine the correct charset encoding of a stream

Which library to use?

As of this writing, they are three libraries that emerge:

I don't include Apache Any23 because it uses ICU4j 3.4 under the hood.

How to tell which one has detected the right charset (or as close as possible)?

It's impossible to certify the charset detected by each above libraries. However, it's possible to ask them in turn and score the returned response.

How to score the returned response?

Each response can be assigned one point. The more points a response have, the more confidence the detected charset has. This is a simple scoring method. You can elaborate others.

Is there any sample code?

Here is a full snippet implementing the strategy described in the previous lines.

public static String guessEncoding(InputStream input) throws IOException {
    // Load input data
    long count = 0;
    int n = 0, EOF = -1;
    byte[] buffer = new byte[4096];
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    while ((EOF != (n = && (count <= Integer.MAX_VALUE)) {
        output.write(buffer, 0, n);
        count += n;
    if (count > Integer.MAX_VALUE) {
        throw new RuntimeException("Inputstream too large.");

    byte[] data = output.toByteArray();

    // Detect encoding
    Map<String, int[]> encodingsScores = new HashMap<>();

    // * GuessEncoding
    updateEncodingsScores(encodingsScores, new CharsetToolkit(data).guessEncoding().displayName());

    // * ICU4j
    CharsetDetector charsetDetector = new CharsetDetector();
    CharsetMatch cm = charsetDetector.detect();
    if (cm != null) {
        updateEncodingsScores(encodingsScores, cm.getName());

    // * juniversalchardset
    UniversalDetector universalDetector = new UniversalDetector(null);
    universalDetector.handleData(data, 0, data.length);
    String encodingName = universalDetector.getDetectedCharset();
    if (encodingName != null) {
        updateEncodingsScores(encodingsScores, encodingName);

    // Find winning encoding
    Map.Entry<String, int[]> maxEntry = null;
    for (Map.Entry<String, int[]> e : encodingsScores.entrySet()) {
        if (maxEntry == null || (e.getValue()[0] > maxEntry.getValue()[0])) {
            maxEntry = e;

    String winningEncoding = maxEntry.getKey();
    return winningEncoding;

private static void updateEncodingsScores(Map<String, int[]> encodingsScores, String encoding) {
    String encodingName = encoding.toLowerCase();
    int[] encodingScore = encodingsScores.get(encodingName);

    if (encodingScore == null) {
        encodingsScores.put(encodingName, new int[] { 1 });
    } else {

private static void dumpEncodingsScores(Map<String, int[]> encodingsScores) {

private static String toString(Map<String, int[]> encodingsScores) {
    String GLUE = ", ";
    StringBuilder sb = new StringBuilder();

    for (Map.Entry<String, int[]> e : encodingsScores.entrySet()) {
        sb.append(e.getKey() + ":" + e.getValue()[0] + GLUE);
    int len = sb.length();
    sb.delete(len - GLUE.length(), len);

    return "{ " + sb.toString() + " }";

Improvements: The guessEncoding method reads the inputstream entirely. For large inputstreams this can be a concern. All these libraries would read the whole inputstream. This would imply a large time consumption for detecting the charset.

It's possible to limit the initial data loading to a few bytes and perform the charset detection on those few bytes only.

When to use dynamic vs. static libraries

Really the trade off you are making (in a large project) is in initial load time, the libraries are going to get linked at one time or another, the decision that has to be made is will the link take long enough that the compiler needs to bite the bullet and do it up front, or can the dynamic linker do it at load time.

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

Javascript | Set all values of an array

The other answers are Ok, but a while loop seems more appropriate:

function setAll(array, value) {
  var i = array.length;
  while (i--) {
    array[i] = value;

A more creative version:

function replaceAll(array, value) {
  var re = new RegExp(value, 'g');
  return new Array(++array.length).toString().replace(/,/g, value).match(re);

May not work everywhere though. :-)

How to get child element by ID in JavaScript?

If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.


You can also use jQuery selectors to basically achieve the same thing:

$('#note #textid');

Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.

On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.

Update 2020.03.10

It's a breeze to use native JS for this:

document.querySelector('#note #textid');

If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(

var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;

Check if process returns 0 with batch file

ERRORLEVEL will contain the return code of the last command. Sadly you can only check >= for it.

Note specifically this line in the MSDN documentation for the If statement:

errorlevel Number

Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than Number.

So to check for 0 you need to think outside the box:

IF ERRORLEVEL 1 GOTO errorHandling
REM no error here, errolevel == 0

Or if you want to code error handling first:

REM errorhandling, errorlevel >= 1

Further information about BAT programming: Or more specific for Windows cmd: MSDN using batch files

How do I add a new class to an element dynamically?

Yes you can - first capture the event using onmouseover, then set the class name using Element.className.

If you like to add or remove classes - use the more convenient Element.classList method.

.active {
  background: red;
<div onmouseover=className="active">
  Hover this!

How to restore SQL Server 2014 backup in SQL Server 2008

Not really as far as I know but here are couple things you can try.

Third party tools: Create empty database on 2008 instance and use third party tools such as ApexSQL Diff and Data Diff to synchronize schema and tables.

Just use these (or any other on the market such as Red Gate, Idera, Dev Art, there are many similar) in trial mode to get the job done.

Generate scripts: Go to Tasks -> Generate Scripts, select option to script the data too and execute it on 2008 instance. Works just fine but note that script order is something you must be careful about. By default scripts are not ordered to take dependencies into account.

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

What are the differences between .gitignore and .gitkeep?

Many people prefer to use just .keep since the convention has nothing to do with git.

How to identify a strong vs weak relationship on ERD?

In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.

memory error in python

you could try to create the same script that popups that error, dividing the script into several script by importing from external script. Example, expect an error Memory error, so i divide into several scripts all of them have to get into a folder "hellohello" into that folder create into init write import h,e,ll,o and then on ide you write import hellohello

Cannot find JavaScriptSerializer in .Net 4.0

This is how to get JavaScriptSerializer available in your application, targetting .NET 4.0 (full)

using System.Web.Script.Serialization;

This should allow you to create a new JavaScriptSerializer object!

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

How to keep the local file or the remote file during merge using Git and the command line?

git checkout {branch-name} -- {file-name}

This will use the file from the branch of choice.

I like this because posh-git autocomplete works great with this. It also removes any ambiguity as to which branch is remote and which is local. And --theirs didn't work for me anyways.

How to get a view table query (code) in SQL Server 2008 Management Studio

if i understood you can do the following

Right Click on View Name in SQL Server Management Studio -> Script View As ->CREATE To ->New Query Window

Need to combine lots of files in a directory

I know this is an old post, but I found it and then found someone who suggested Total Mail Converter. I was able to convert my folder with 2k .msg files into .txt. It also allows you to convert into PDF and other popular formats.

It's a great tool that I am glad someone suggested as it will save me several days.

FYI - My project is combining the .msg files into one text file so that I can run a script to extract certain information from the files (ie: email and links). Instead of 2k files, I can work with one.

How do I get the APK of an installed app without root access?

I found a way to get the APK's package name in a non-root device. it's not so elegant, but works all the time.

Step 1: on your device, open the target APK

Step 2: on PC cmd window, type this commands:

 adb shell dumpsys activity a > dump.txt

because the output of this command is numerous, redirect to a file is recommended.

Step 3: open this dump.txt file with any editor.

for device befor Android 4.4:
the beginning of the file would be looked like this:

ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)  
  Main stack:  
  * TaskRecord{41aa9ed0 #4 A U 0}  
    numActivities=1 rootWasReset=true userId=0  
    intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10600000}  
    lastThumbnail=null lastDescription=null  
    lastActiveTime=19915965 (inactive for 10s)  
    * Hist #9: ActivityRecord{41ba1a30 u0}  

the package name is in the 3rd line, for this example.

for Android 4.4 and later:
the dumpsys output has changed a little. try search "Stack #1", the package name would be very close below it.

Also, search "baseDir", you will find the full path of the apk file!

What is the best or most commonly used JMX Console / Client

JRockit Mission Control is becoming Java Mission Control and will be dedicated exclusively to Hotspot. If you are an Oracle customer, you can download the 5.x versions of Java Mission Control from MOS (My Oracle Support). Java Mission Control will eventually be released together with the Oracle JDK. The reason it is not yet generally available is that there are some serious limitations, especially when using the Flight Recorder. However, if you are only interested in using the JMX console, you should be golden!

Pass a datetime from javascript to c# (Controller)

The following format should work:

    type: "POST",
    url: "@Url.Action("refresh", "group")",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ 
        myDate: '2011-04-02 17:15:45'
    success: function (result) {
        //do something
    error: function (req, status, error) {

Current Subversion revision command

Nobody mention for Windows world SubWCRev, which, properly used, can substitute needed data into the needed places automagically, if script call SubWCRev in form SubWCRev WC_PATH TPL-FILE READY-FILE

Sample of my post-commit hook (part of)

SubWCRev.exe CustomLocations Builder.tpl  z:\Builder.bat
call z:\Builder.bat

where my Builder.tpl is

svn.exe export trunk z:\trunk$WCDATE=%Y%m%d$-r$WCREV$

as result, I have every time bat-file with variable part - name of dir - which corresponds to the metadata of Working Copy

How can I determine the URL that a local Git repository was originally cloned from?

git config --list

This command will give all information related to your repository.

How do I create a list of random numbers without duplicates?

The solution presented in this answer works, but it could become problematic with memory if the sample size is small, but the population is huge (e.g. random.sample(insanelyLargeNumber, 10)).

To fix that, I would go with this:

answer = set()
sampleSize = 10
answerSize = 0

while answerSize < sampleSize:
    r = random.randint(0,100)
    if r not in answer:
        answerSize += 1

# answer now contains 10 unique, random integers from 0.. 100


You technically have two options when speaking of ISO dates.

In general, if you're filtering specifically on Date values alone OR looking to persist date in a neutral fashion. Microsoft recommends using the language neutral format of ymd or y-m-d. Which are both valid ISO formats.

Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.

Because of this, your safest bet is to persist/filter based on the always netural ymd format.

The code:

select convert(char(10), getdate(), 126) -- ISO YYYY-MM-DD
select convert(char(8), getdate(), 112) -- ISO YYYYMMDD (safest)

How do I update Anaconda?

To update your installed version to the latest version, say 2019.07, run:

conda install anaconda=2019.07

In most cases, this method can meet your needs and avoid dependency problems.

Vertically centering Bootstrap modal window

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="table">
        <div class="table-cell">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                    <div class="modal-body">
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>

// Styles

.table {
 display: table;
.table-cell {
display: table-cell;
vertical-align: middle;

What's the difference between implementation and compile in Gradle?

Compile configuration was deprecated and should be replaced by implementation or api.

You can read the docs at

The brief part being-

The key difference between the standard Java plugin and the Java Library plugin is that the latter introduces the concept of an API exposed to consumers. A library is a Java component meant to be consumed by other components. It's a very common use case in multi-project builds, but also as soon as you have external dependencies.

The plugin exposes two configurations that can be used to declare dependencies: api and implementation. The api configuration should be used to declare dependencies which are exported by the library API, whereas the implementation configuration should be used to declare dependencies which are internal to the component.

For further explanation refer to this image. Brief explanation

Count the number of items in my array list

Using Java 8 stream API:

 String[] keys = new String[0];

// A map for keys and their count
Map<String, Long> keyCountMap =
collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
int uniqueItemIdCount= keyCountMap.size();

Script parameters in Bash

I needed to make sure that my scripts are entirely portable between various machines, shells and even cygwin versions. Further, my colleagues who were the ones I had to write the scripts for, are programmers, so I ended up using this:

for ((i=1;i<=$#;i++)); 

    if [ ${!i} = "-s" ] 
    then ((i++)) 

    elif [ ${!i} = "-log" ];
    then ((i++)) 

    elif [ ${!i} = "-x" ];
    then ((i++)) 

    elif [ ${!i} = "-p" ]; 
    then ((i++)) 

    elif [ ${!i} = "-b" ];
    then ((i++)) 

    elif [ ${!i} = "-l" ];
    then ((i++)) 

    elif [ ${!i} = "-a" ];
    then ((i++)) 


Rationale: I included a script as well, since the whole operation had several steps which were quasi independent on each other (I'm saying "quasi", because even though each script could be run on its own, they were usually all run together), and in two days I found out, that about half of my colleagues, being programmers and all, were too good to be using the launcher file, follow the "usage", or read the HELP which was displayed every time they did something wrong and they were making a mess of the whole thing, running scripts with arguments in the wrong order and complaining that the scripts didn't work properly. Being the choleric I am I decided to overhaul all my scripts to make sure that they are colleague-proof. The code segment above was the first thing.

How to use ? : if statements with Razor and inline code blocks

In most cases the solution of CD.. will work perfectly fine. However I had a bit more twisted situation:

 @(String.IsNullOrEmpty(Model.MaidenName) ? "&nbsp;" : Model.MaidenName)

This would print me "&nbsp;" in my page, respectively generate the source &amp;nbsp;. Now there is a function Html.Raw("&nbsp;") which is supposed to let you write source code, except in this constellation it throws a compiler error:

Compiler Error Message: CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Web.IHtmlString' and 'string'

So I ended up writing a statement like the following, which is less nice but works even in my case:

@if (String.IsNullOrEmpty(Model.MaidenName)) { @Html.Raw("&nbsp;") } else { @Model.MaidenName } 

Note: interesting thing is, once you are inside the curly brace, you have to restart a Razor block.

Regexp Java for password validation

Password Requirement :

  • Password should be at least eight (8) characters in length where the system can support it.
  • Passwords must include characters from at least two (2) of these groupings: alpha, numeric, and special characters.


I tested it and it works

Regular Expression to find a string included between two characters while EXCLUDING the delimiters


$string ='This is the match [more or less]';
preg_match('#\[(.*)\]#', $string, $match);

How to call a parent method from child class in javascript?

Well in order to do this, you are not limited with the Class abstraction of ES6. Accessing the parent constructor's prototype methods is possible through the __proto__ property (I am pretty sure there will be fellow JS coders to complain that it's depreciated) which is depreciated but at the same time discovered that it is actually an essential tool for sub-classing needs (especially for the Array sub-classing needs though). So while the __proto__ property is still available in all major JS engines that i know, ES6 introduced the Object.getPrototypeOf() functionality on top of it. The super() tool in the Class abstraction is a syntactical sugar of this.

So in case you don't have access to the parent constructor's name and don't want to use the Class abstraction you may still do as follows;

function ChildObject(name) {
    // call the parent's constructor, name);
    this.myMethod = function(arg) {

Mocking Extension Methods with Moq

You can easily mock an extension method with JustMock. The API is the same as mocking normal method. Consider the following

public static string Echo(this Foo foo, string strValue) 
    return strValue; 

To arrange and verify this method use the following:

string expected = "World";

var foo = new Foo();
Mock.Arrange(() => foo.Echo(Arg.IsAny<string>())).Returns(expected);

string result = foo.Echo("Hello");

Assert.AreEqual(expected, result);

Here is also a link to the documentation: Extension Methods Mocking

Disclaimer. I am one of the developers responsible for JustMock.

How do I set path while saving a cookie value in JavaScript?

See for more documentation:

 setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {  
     if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }  
     var sExpires = "";  
     if (vEnd) {  
       switch (typeof vEnd) {  
         case "number": sExpires = "; max-age=" + vEnd; break;  
         case "string": sExpires = "; expires=" + vEnd; break;  
         case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;  
     document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");  

Classes cannot be accessed from outside package

Let me guess

Your initial declaration of class PUBLICClass was not public, then you made it `Public', can you try to clean and rebuild your project ?

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.

If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

What is the backslash character (\\)?

It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.


System.out.println("printing \"this\" in quotes");


printing "this" in quotes

How can I make Java print quotes, like "Hello"?


How to convert a String to JsonObject using gson library

You can convert it to a JavaBean if you want using:

 Gson gson = new GsonBuilder().setPrettyPrinting().create();
 gson.fromJson(jsonString, JavaBean.class)

To use JsonObject, which is more flexible, use the following:

String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}";
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(json);

Which is equivalent to the following:

JsonElement jelem = gson.fromJson(json, JsonElement.class);
JsonObject jobj = jelem.getAsJsonObject();

Detect If Browser Tab Has Focus

Cross Browser jQuery Solution! Raw available at GitHub

Fun & Easy to Use!

The following plugin will go through your standard test for various versions of IE, Chrome, Firefox, Safari, etc.. and establish your declared methods accordingly. It also deals with issues such as:

  • onblur|.blur/onfocus|.focus "duplicate" calls
  • window losing focus through selection of alternate app, like word
    • This tends to be undesirable simply because, if you have a bank page open, and it's onblur event tells it to mask the page, then if you open calculator, you can't see the page anymore!
  • Not triggering on page load

Use is as simple as: Scroll Down to 'Run Snippet'

$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);

//  OR Pass False boolean, and it will not trigger on load,
//  Instead, it will first trigger on first blur of current tab_window
$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);
}, false);

//  OR Establish an object having methods "blur" & "focus", and/or "blurFocus"
//  (yes, you can set all 3, tho blurFocus is the only one with an 'isVisible' param)
    blur: function(event) {
        console.log("Blur\t\t", event);
    focus: function(event) {
        console.log("Focus\t\t", event);

//  OR First method becoms a "blur", second method becoms "focus"!
$.winFocus(function(event) {
    console.log("Blur\t\t", event);
function(event) {
    console.log("Focus\t\t", event);

/*    Begin Plugin    */_x000D_
;;(function($){$.winFocus||($.extend({winFocus:function(){var a=!0,b=[];$(document).data("winFocus")||$(document).data("winFocus",$.winFocus.init());for(x in arguments)"object"==typeof arguments[x]?(arguments[x].blur&&$.winFocus.methods.blur.push(arguments[x].blur),arguments[x].focus&&$.winFocus.methods.focus.push(arguments[x].focus),arguments[x].blurFocus&&$.winFocus.methods.blurFocus.push(arguments[x].blurFocus),arguments[x].initRun&&(a=arguments[x].initRun)):"function"==typeof arguments[x]?b.push(arguments[x]):_x000D_
"boolean"==typeof arguments[x]&&(a=arguments[x]);b&&(1==b.length?$.winFocus.methods.blurFocus.push(b[0]):($.winFocus.methods.blur.push(b[0]),$.winFocus.methods.focus.push(b[1])));if(a)$.winFocus.methods.onChange()}}),$.winFocus.init=function(){$.winFocus.props.hidden in document?document.addEventListener("visibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="mozHidden")in document?document.addEventListener("mozvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden=_x000D_
"webkitHidden")in document?document.addEventListener("webkitvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="msHidden")in document?document.addEventListener("msvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="onfocusin")in document?document.onfocusin=document.onfocusout=$.winFocus.methods.onChange:window.onpageshow=window.onpagehide=window.onfocus=window.onblur=$.winFocus.methods.onChange;return $.winFocus},$.winFocus.methods={blurFocus:[],blur:[],focus:[],_x000D_
exeCB:function(a){$.winFocus.methods.blurFocus&&$.each($.winFocus.methods.blurFocus,function(b,c){this.apply($.winFocus,[a,!a.hidden])});a.hidden&&$.winFocus.methods.blur&&$.each($.winFocus.methods.blur,function(b,c){this.apply($.winFocus,[a])});!a.hidden&&$.winFocus.methods.focus&&$.each($.winFocus.methods.focus,function(b,c){this.apply($.winFocus,[a])})},onChange:function(a){var b={focus:!1,focusin:!1,pageshow:!1,blur:!0,focusout:!0,pagehide:!0};if(a=a||window.event)a.hidden=a.type in b?b[a.type]:_x000D_
document[$.winFocus.props.hidden],$(window).data("visible",!a.hidden),$.winFocus.methods.exeCB(a);else try{$,new Event("visibilitychange"))}catch(c){}}},$.winFocus.props={hidden:"hidden"})})(jQuery);_x000D_
/*    End Plugin      */_x000D_
// Simple example_x000D_
$(function() {_x000D_
 $.winFocus(function(event, isVisible) {_x000D_
  $('td tbody').empty();_x000D_
  $.each(event, function(i) {_x000D_
   $('td tbody').append(_x000D_
    $('<tr />').append(_x000D_
     $('<th />', { text: i }),_x000D_
     $('<td />', { text: this.toString() })_x000D_
  if (isVisible) _x000D_
   $("#isVisible").stop().delay(100).fadeOut('fast', function(e) {_x000D_
  else {_x000D_
body { background: #AAF; }_x000D_
table { width: 100%; }_x000D_
table table { border-collapse: collapse; margin: 0 auto; width: auto; }_x000D_
tbody > tr > th { text-align: right; }_x000D_
td { width: 50%; }_x000D_
th, td { padding: .1em .5em; }_x000D_
td th, td td { border: 1px solid; }_x000D_
.visible { background: #FFA; }
<script src=""></script>_x000D_
<h3>See Console for Event Object Returned</h3>_x000D_
        <th><p>Is Visible?</p></th>_x000D_
        <td><p id="isVisible">TRUE</p></td>_x000D_
        <td colspan="2">_x000D_
                        <th colspan="2">Event Data <span style="font-size: .8em;">{ See Console for More Details }</span></th>_x000D_

What is the difference between a var and val definition in Scala?

The difference is that a var can be re-assigned to whereas a val cannot. The mutability, or otherwise of whatever is actually assigned, is a side issue:

import collection.immutable
import collection.mutable
var m = immutable.Set("London", "Paris")
m = immutable.Set("New York") //Reassignment - I have change the "value" at m.


val n = immutable.Set("London", "Paris")
n = immutable.Set("New York") //Will not compile as n is a val.

And hence:

val n = mutable.Set("London", "Paris")
n = mutable.Set("New York") //Will not compile, even though the type of n is mutable.

If you are building a data structure and all of its fields are vals, then that data structure is therefore immutable, as its state cannot change.

How to make a HTTP request using Ruby on Rails?

OpenURI is the best; it's as simple as

require 'open-uri'
response = open('').read

Main differences between SOAP and RESTful web services in Java



? SOAP is simple object access protocol that run on TCP/UDP/SMTP.
? SOAP read and write request response messages in XML format.
? SOAP uses interface in order to define the services.
? SOAP is more secure as it has its own security and well defined standards.
? SOAP follows RPC and Document style to define web services.
? SOAP uses SOAP-UI as client tools for testing.


? REST is representational state transfer that uses underlying HTTP protocols.
? REST is stateless.
? REST is an architectural style that is used to describe and define web services.
? REST can read and write request response messages in JSON/XML/Plain HTML.
? REST uses URI for each resource that is used in web service.A resource can be image text method etc.
? REST uses set of verbs, like HTTP's GET, POST, PUT, DELETE.
? REST is easy to develop and easy to manage as compared to SOAP UI.
? REST has light-weight client tools or plugins that can easily be integrated inside a browser.
? REST services are cacheable.

How to make promises work in IE11

You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.

used like: window.Promise

If you want more information on Polyfills check out the following MDN web doc

How to convert a private key to an RSA private key?

This may be of some help (do not literally write out the backslashes '\' in the commands, they are meant to indicate that "everything has to be on one line"):

Which Command to Apply When

It seems that all the commands (in grey) take any type of key file (in green) as "in" argument. Which is nice.

Here are the commands again for easier copy-pasting:

openssl rsa                                                -in $FF -out $TF
openssl rsa -aes256                                        -in $FF -out $TF
openssl pkcs8 -topk8 -nocrypt                              -in $FF -out $TF
openssl pkcs8 -topk8 -v2 aes-256-cbc -v2prf hmacWithSHA256 -in $FF -out $TF


openssl rsa -check -in $FF
openssl rsa -text  -in $FF

Subversion ignoring "--password" and "--username" options

I had a similar problem, I wanted to use a different user name for a svn+ssh repository. In the end, I used svn relocate (as described in in this answer. In my case, I'm using svn 1.6.11 and did the following:

svn switch --relocate \
    svn+ssh://olduser@svnserver/path/to/repo \

where svn+ssh://olduser@svnserver/path/to/repo can be found in the URL: line output of svn info command. This command asked me for the password of newuser.

Note that this change is persistent, i.e. if you want only temporarily switch to the new username with this method, you'll have to issue a similar command again after svn update etc.

Auto-fit TextView for Android

Ok I have used the last week to massively rewrite my code to precisely fit your test. You can now copy this 1:1 and it will immediately work - including setSingleLine(). Please remember to adjust MIN_TEXT_SIZE and MAX_TEXT_SIZE if you're going for extreme values.

Converging algorithm looks like this:

for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) {

    // Go to the mean value...
    testSize = (upperTextSize + lowerTextSize) / 2;

    // ... inflate the dummy TextView by setting a scaled textSize and the text...
    mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor);

    // ... call measure to find the current values that the text WANTS to occupy
    mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    int tempHeight = mTestView.getMeasuredHeight();

    // ... decide whether those values are appropriate.
    if (tempHeight >= targetFieldHeight) {
        upperTextSize = testSize; // Font is too big, decrease upperSize
    else {
        lowerTextSize = testSize; // Font is too small, increase lowerSize

And the whole class can be found here.

The result is very flexible now. This works the same declared in xml like so:

    android:text="@string/LoremIpsum" />

... as well as built programmatically like in your test.

I really hope you can use this now. You can call setText(CharSequence text) now to use it by the way. The class takes care of stupendously rare exceptions and should be rock-solid. The only thing that the algorithm does not support yet is:

  • Calls to setMaxLines(x) where x >= 2

But I have added extensive comments to help you build this if you wish to!

Please note:

If you just use this normally without limiting it to a single line then there might be word-breaking as you mentioned before. This is an Android feature, not the fault of the AutoFitText. Android will always break words that are too long for a TextView and it's actually quite a convenience. If you want to intervene here than please see my comments and code starting at line 203. I have already written an adequate split and the recognition for you, all you'd need to do henceforth is to devide the words and then modify as you wish.

In conclusion: You should highly consider rewriting your test to also support space chars, like so:

final Random _random = new Random();
final String ALLOWED_CHARACTERS = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
final int textLength = _random.nextInt(80) + 20;
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < textLength; ++i) {
    if (i % 7 == 0 && i != 0) {
        builder.append(" ");
((AutoFitText) findViewById(;

This will produce very beutiful (and more realistic) results.
You will find commenting to get you started in this matter as well.

Good luck and best regards

pgadmin4 : postgresql application server could not be contacted.

It seems in most of the cases Postgres trying to use information from previous sessions to find/connect the server and failing. Clearing out the previous session info helped me, it is a combination of 2 already mentioned answers above:

  1. Navigate to Postgres session's folder "C:\Users\YourUsernameOrAdmin\AppData\Roaming\pgAdmin\sessions"
  2. Delete all the data from this folder.
  3. Start PgAdmin in administrator mode.


Can a java lambda have more than 1 parameter?

Another alternative, not sure if this applies to your particular problem but to some it may be applicable is to use UnaryOperator in java.util.function library. where it returns same type you specify, so you put all your variables in one class and is it as a parameter:

public class FunctionsLibraryUse {

    public static void main(String[] args){
        UnaryOperator<People> personsBirthday = (p) ->{
            System.out.println("it's " + p.getName() + " birthday!");
            p.setAge(p.getAge() + 1);
            return p;
        People mel = new People();
        mel = personsBirthday.apply(mel);
        System.out.println("he is now : " + mel.getAge());

class People{
    private String name;
    private int age;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public int getAge() {
        return age;
    public void setAge(int age) {
        this.age = age;

So the class you have, in this case Person, can have numerous instance variables and won't have to change the parameter of your lambda expression.

For those interested, I've written notes on how to use java.util.function library:

How do I tokenize a string in C++?

Another quick way is to use getline. Something like:

stringstream ss("bla bla");
string s;

while (getline(ss, s, ' ')) {
 cout << s << endl;

If you want, you can make a simple split() method returning a vector<string>, which is really useful.

PermissionError: [Errno 13] in python

When doing;

a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')'re trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

What does from __future__ import absolute_import actually do?

The changelog is sloppily worded. from __future__ import absolute_import does not care about whether something is part of the standard library, and import string will not always give you the standard-library module with absolute imports on.

from __future__ import absolute_import means that if you import string, Python will always look for a top-level string module, rather than current_package.string. However, it does not affect the logic Python uses to decide what file is the string module. When you do

python pkg/

pkg/ doesn't look like part of a package to Python. Following the normal procedures, the pkg directory is added to the path, and all .py files in the pkg directory look like top-level modules. import string finds pkg/ not because it's doing a relative import, but because pkg/ appears to be the top-level module string. The fact that this isn't the standard-library string module doesn't come up.

To run the file as part of the pkg package, you could do

python -m pkg.script

In this case, the pkg directory will not be added to the path. However, the current directory will be added to the path.

You can also add some boilerplate to pkg/ to make Python treat it as part of the pkg package even when run as a file:

if __name__ == '__main__' and __package__ is None:
    __package__ = 'pkg'

However, this won't affect sys.path. You'll need some additional handling to remove the pkg directory from the path, and if pkg's parent directory isn't on the path, you'll need to stick that on the path too.

Converting cv::Mat to IplImage*

cv::Mat is the new type introduce in OpenCV2.X while the IplImage* is the "legacy" image structure.

Although, cv::Mat does support the usage of IplImage in the constructor parameters, the default library does not provide function for the other way. You will need to extract the image header information manually. (Do remember that you need to allocate the IplImage structure, which is lack in your example).

Constant pointer vs Pointer to constant

Please refer the following link for better understanding about the difference between Const pointer and Pointer on a constant value.

constant pointer vs pointer on a constant value

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

You need to make cross-env working globally instead of having it in the project.

1) remove node_modules folder

2) run

npm install --global cross-env

3) remove "cross-env": "^5.0.1", from package.json file devDependencies section. Actually, you can skip this step and keep package.json intact. If you prefer.

4) run

npm install --no-bin-links

5) run

npm run dev

and see it working

P.S Tested on Windows 10 with Laravel-5.4

P.P.S Windows 10 with Laravel-5.6 does not have this problem, thus updating is an alternative solution.

JavaScript: clone a function

Short and simple:

Function.prototype.clone = function() {
  return new Function('return ' + this.toString())();

How to download Google Play Services in an Android emulator?

If your emulator x86 this method works your me.

Download and install And select nano pack

More info

enter image description here

enter image description here

How to compile c# in Microsoft's new Visual Studio Code?

Since no one else said it, the short-cut to compile (build) a C# app in Visual Studio Code (VSCode) is SHIFT+CTRL+B.

If you want to see the build errors (because they don't pop-up by default), the shortcut is SHIFT+CTRL+M.

(I know this question was asking for more than just the build shortcut. But I wanted to answer the question in the title, which wasn't directly answered by other answers/comments.)

Initial size for the ArrayList

My two cents on Stream. I think it's better to use

IntStream.generate(i -> MyClass.contruct())

with the flexibility to put any initial values.