Programs & Examples On #Javapos

What good technology podcasts are out there?

Most of the podcasts I listened to are already discussed above.

  • .NET Rocks
  • HanselMinutes
  • RunAsRadio
  • Mondays (for when you are bored with development stuffs)
  • Herding Code
  • Arcast (used to)
  • AudibleAjax
  • OpenWeb

There are some bits from OOPSLA that were interesting as well (not long running podcasts, but it's nice to hear).

How to remove a variable from a PHP session array

if (isset($_POST['remove'])) {
    $key=array_search($_GET['name'],$_SESSION['name']);
    if($key!==false)
    unset($_SESSION['name'][$key]);
    $_SESSION["name"] = array_values($_SESSION["name"]);
} 

Since $_SESSION['name'] is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.

How to generate random float number in C

You can also generate in a range [min, max] with something like

float float_rand( float min, float max )
{
    float scale = rand() / (float) RAND_MAX; /* [0, 1.0] */
    return min + scale * ( max - min );      /* [min, max] */
}

Save Screen (program) output to a file

A different answer if you need to save the output of your whole scrollback buffer from an already actively running screen:

Ctrl-a [ g SPACE G $ >.

This will save your whole buffer to /tmp/screen-exchange

Javascript: formatting a rounded number to N decimals

That's not a rounding ploblem, that is a display problem. A number doesn't contain information about significant digits; the value 2 is the same as 2.0000000000000. It's when you turn the rounded value into a string that you have make it display a certain number of digits.

You could just add zeroes after the number, something like:

var s = number.toString();
if (s.indexOf('.') == -1) s += '.';
while (s.length < s.indexOf('.') + 4) s += '0';

(Note that this assumes that the regional settings of the client uses period as decimal separator, the code needs some more work to function for other settings.)

Use RSA private key to generate public key?

In most software that generates RSA private keys, including openssl's, the private key is represented as a PKCS#1 RSAPrivatekey object or some variant thereof:

A.1.2 RSA private key syntax

An RSA private key should be represented with the ASN.1 type
RSAPrivateKey:

  RSAPrivateKey ::= SEQUENCE {
      version           Version,
      modulus           INTEGER,  -- n
      publicExponent    INTEGER,  -- e
      privateExponent   INTEGER,  -- d
      prime1            INTEGER,  -- p
      prime2            INTEGER,  -- q
      exponent1         INTEGER,  -- d mod (p-1)
      exponent2         INTEGER,  -- d mod (q-1)
      coefficient       INTEGER,  -- (inverse of q) mod p
      otherPrimeInfos   OtherPrimeInfos OPTIONAL
  }

As you can see, this format has a number of fields including the modulus and public exponent and thus is a strict superset of the information in an RSA public key.

How to extract a single value from JSON response?

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

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

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

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

Lollipop : draw behind statusBar with its color set to transparent

Similar to some of the solutions posted, but in my case I did the status bar transparent and fix the position of the action bar with some negative margin

if (Build.VERSION.SDK_INT >= 21) {
    getWindow().setStatusBarColor(Color.TRANSPARENT);
    FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) toolbar.getLayoutParams();
    lp.setMargins(0, -getStatusBarHeight(), 0, 0);
}

And I used in the toolbar and the root view

android:fitsSystemWindows="true"

Can Powershell Run Commands in Parallel?

To complete previous answers, you can also use Wait-Job to wait for all jobs to complete:

For ($i=1; $i -le 3; $i++) {
    $ScriptBlock = {
        Param (
            [string] [Parameter(Mandatory=$true)] $increment
        )

        Write-Host $increment
    }

    Start-Job $ScriptBlock -ArgumentList $i
}

Get-Job | Wait-Job | Receive-Job

How to comment out a block of Python code in Vim

No plugins or mappings required. Try the built-in "norm" command, which literally executes anything you want on every selected line.

Add # Comments

1. shift V to visually select lines
2. :norm i#

Remove # Comments

1. visually select region as before
2. :norm x

Or if your comments are indented you can do :norm ^x

Notice that these are just ordinary vim commands being preceded by ":norm" to execute them on each line.

More detailed answer for using "norm" command in one of the answers here

What's a quick way to comment/uncomment lines in Vim?

How do I set up HttpContent for my HttpClient PostAsync second parameter?

    public async Task<ActionResult> Index()
    {
        apiTable table = new apiTable();
        table.Name = "Asma Nadeem";
        table.Roll = "6655";

        string str = "";
        string str2 = "";

        HttpClient client = new HttpClient();

        string json = JsonConvert.SerializeObject(table);

        StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);

        str = "" + response.Content + " : " + response.StatusCode;

        if (response.IsSuccessStatusCode)
        {       
            str2 = "Data Posted";
        }

        return View();
    }

Display number with leading zeros

You can use str.zfill:

print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))

prints:

01
10
100

OTP (token) should be automatically read from the message

I implemented something of that such. But, here is what I did when the message comes in, I retrieve only the six digit code, bundle it in an intent and send it to the activity or fragment needing it and verifies the code. The example shows you the way to get the sms already. Look at the code below for illustration on how to send using LocalBrodcastManager and if your message contains more texts E.g Greetings, standardize it to help you better. E.g "Your verification code is: 84HG73" you can create a regex pattern like this ([0-9]){2}([A-Z]){2}([0-9]){2} which means two ints, two [capital] letters and two ints. Good Luck!

After discarding all un needed info from the message

 Intent intent = new Intent("AddedItem");
 intent.putExtra("items", code);
 LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent); 

And the Fragment/Activity receiving it

@Override
public void onResume() {
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter("AddedItem"));
    super.onResume();
}

@Override
public void onPause() {
    super.onDestroy();
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
}

And the code meant to handle the payload you collected

 private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction()) {
            final String message = intent.getStringExtra("message");
            //Do whatever you want with the code here
        }
    }
};

Does that help a little bit. I did it better by using Callbacks

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

Node.js uses the environmental variable NODE_PATH to allow for specifying additional directories to include in the module search path. You can use npm itself to tell you where global modules are stored with the npm root -g command. So putting those two together, you can make sure global modules are included in your search path with the following command (on Linux-ish)

export NODE_PATH=$(npm root --quiet -g)

View google chrome's cached pictures

This page contains all the cached urls

chrome://cache

Unfortunately to actually see the file you have to select everything on the page and paste it in this tool: http://www.sensefulsolutions.com/2012/01/viewing-chrome-cache-easy-way.html

Loading local JSON file

In a more modern way, you can now use the Fetch API:

fetch("test.json")
  .then(response => response.json())
  .then(json => console.log(json));

All modern browsers support Fetch API. (Internet Explorer doesn't, but Edge does!)

source:

Loop X number of times

This may be what you are looking for:

for ($i=1; $i -le $ActiveCampaigns; $i++)
{
  $PQCampaign     = Get-Variable -Name "PQCampaign$i"     -ValueOnly
  $PQCampaignPath = Get-Variable -Name "PQCampaignPath$i" -ValueOnly

  # Do stuff with $PQCampaign and $PQCampaignPath
}

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

Got a better approach to implement the animating FAB menu without using any library or to write huge xml code for animations. hope this will help in future for someone who needs a simple way to implement this.

Just using animate().translationY() function, you can animate any view up or down just I did in my below code, check complete code in github. In case you are looking for the same code in kotlin, you can checkout the kotlin code repo Animating FAB Menu.

first define all your FAB at same place so they overlap each other, remember on top the FAB should be that you want to click and to show other. eg:

    <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab3"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_btn_speak_now" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab2"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_menu_camera" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab1"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_dialog_map" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

Now in your java class just define all your FAB and perform the click like shown below:

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab1 = (FloatingActionButton) findViewById(R.id.fab1);
    fab2 = (FloatingActionButton) findViewById(R.id.fab2);
    fab3 = (FloatingActionButton) findViewById(R.id.fab3);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!isFABOpen){
                showFABMenu();
            }else{
                closeFABMenu();
            }
        }
    });

Use the animation().translationY() to animate your FAB,I prefer you to use the attribute of this method in DP since only using an int will effect the display compatibility with higher resolution or lower resolution. as shown below:

 private void showFABMenu(){
    isFABOpen=true;
    fab1.animate().translationY(-getResources().getDimension(R.dimen.standard_55));
    fab2.animate().translationY(-getResources().getDimension(R.dimen.standard_105));
    fab3.animate().translationY(-getResources().getDimension(R.dimen.standard_155));
}

private void closeFABMenu(){
    isFABOpen=false;
    fab1.animate().translationY(0);
    fab2.animate().translationY(0);
    fab3.animate().translationY(0);
}

Now define the above mentioned dimension inside res->values->dimens.xml as shown below:

    <dimen name="standard_55">55dp</dimen>
<dimen name="standard_105">105dp</dimen>
<dimen name="standard_155">155dp</dimen>

That's all hope this solution will help the people in future, who are searching for simple solution.

EDITED

If you want to add label over the FAB then simply take a horizontal LinearLayout and put the FAB with textview as label, and animate the layouts if find any issue doing this, you can check my sample code in github, I have handelled all backward compatibility issues in that sample code. check my sample code for FABMenu in Github

to close the FAB on Backpress, override onBackPress() as showen below:

    @Override
public void onBackPressed() {
    if(!isFABOpen){
        this.super.onBackPressed();
    }else{
        closeFABMenu();
    }
}

The Screenshot have the title as well with the FAB,because I take it from my sample app present ingithub

enter image description here

Renaming column names of a DataFrame in Spark Scala

def aliasAllColumns(t: DataFrame, p: String = "", s: String = ""): DataFrame =
{
  t.select( t.columns.map { c => t.col(c).as( p + c + s) } : _* )
}

In case is isn't obvious, this adds a prefix and a suffix to each of the current column names. This can be useful when you have two tables with one or more columns having the same name, and you wish to join them but still be able to disambiguate the columns in the resultant table. It sure would be nice if there were a similar way to do this in "normal" SQL.

Pass correct "this" context to setTimeout callback?

In browsers other than Internet Explorer, you can pass parameters to the function together after the delay:

var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);

So, you can do this:

var timeoutID = window.setTimeout(function (self) {
  console.log(self); 
}, 500, this);

This is better in terms of performance than a scope lookup (caching this into a variable outside of the timeout / interval expression), and then creating a closure (by using $.proxy or Function.prototype.bind).

The code to make it work in IEs from Webreflection:

/*@cc_on
(function (modifierFn) {
  // you have to invoke it as `window`'s property so, `window.setTimeout`
  window.setTimeout = modifierFn(window.setTimeout);
  window.setInterval = modifierFn(window.setInterval);
})(function (originalTimerFn) {
    return function (callback, timeout){
      var args = [].slice.call(arguments, 2);
      return originalTimerFn(function () { 
        callback.apply(this, args) 
      }, timeout);
    }
});
@*/

How can I convert a Unix timestamp to DateTime and vice versa?

From .net 4.6, you can do this:

var dateTime = DateTimeOffset.FromUnixTimeSeconds(unixDateTime).DateTime;

From ND to 1D arrays

For list of array with different size use following:

import numpy as np

# ND array list with different size
a = [[1],[2,3,4,5],[6,7,8]]

# stack them
b = np.hstack(a)

print(b)

Output:

[1 2 3 4 5 6 7 8]

What does .shape[] do in "for i in range(Y.shape[0])"?

shape is a tuple that gives you an indication of the number of dimensions in the array. So in your case, since the index value of Y.shape[0] is 0, your are working along the first dimension of your array.

From http://www.scipy.org/Tentative_NumPy_Tutorial#head-62ef2d3c0a5b4b7d6fdc48e4a60fe48b1ffe5006

 An array has a shape given by the number of elements along each axis:
 >>> a = floor(10*random.random((3,4)))

 >>> a
 array([[ 7.,  5.,  9.,  3.],
        [ 7.,  2.,  7.,  8.],
        [ 6.,  8.,  3.,  2.]])

 >>> a.shape
 (3, 4)

and http://www.scipy.org/Numpy_Example_List#shape has some more examples.

How to deal with the URISyntaxException

Replace spaces in URL with + like If url contains dimension1=Incontinence Liners then replace it with dimension1=Incontinence+Liners.

How to iterate (keys, values) in JavaScript?

WELCOME TO 2020 *Drools in ES6*

Theres some pretty old answers in here - take advantage of destructuring. In my opinion this is without a doubt the nicest (very readable) way to iterate an object.

_x000D_
_x000D_
const myObject = {
    nick: 'cage',
    phil: 'murray',
};

Object.entries(myObject).forEach(([k,v]) => {
    console.log("The key: ",k)
    console.log("The value: ",v)
})
_x000D_
_x000D_
_x000D_

Edit:

As mentioned by Lazerbeak, map allows you to cycle an object and use the key and value to make an array.

_x000D_
_x000D_
const myObject = {
    nick: 'cage',
    phil: 'murray',
};

const myArray = Object.entries(myObject).map(([k, v]) => {
    return `The key '${k}' has a value of '${v}'`;
});

console.log(myArray);
_x000D_
_x000D_
_x000D_

Using HTTPS with REST in Java

Check this out: http://code.google.com/p/resting/. I could use resting to consume HTTPS REST services.

How to bind an enum to a combobox control in WPF?

public class EnumItemsConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!value.GetType().IsEnum)
            return false;

        var enumName = value.GetType();
        var obj = Enum.Parse(enumName, value.ToString());

        return System.Convert.ToInt32(obj);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Enum.ToObject(targetType, System.Convert.ToInt32(value));
    }
}

You should extend Rogers and Greg's answer with such kind of Enum value converter, if you're binding straight to enum object model properties.

echo key and value of an array without and with loop

You can try following code:

foreach ($arry as $key => $value) 
{
      echo $key;
      foreach ($value as  $val) 
      {
         echo $val; 
      }
}

How to check if variable's type matches Type stored in a variable

In order to check if an object is compatible with a given type variable, instead of writing

u is t

you should write

typeof(t).IsInstanceOfType(u)

How to delete an array element based on key?

You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()).
If so, just use unset():

unset($arr[1]);

Inserting created_at data with Laravel

Currently (Laravel 5.4) the way to achieve this is:

$model = new Model();
$model->created_at = Carbon::now();
$model->save(['timestamps' => false]);

Undefined columns selected when subsetting data frame

You want rows where that condition is true so you need a comma:

data[data$Ozone > 14, ]

How can I properly use a PDO object for a parameterized SELECT query

You can use the bindParam or bindValue methods to help prepare your statement. It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.

Check the clear, easy to read example below:

$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname',  'Bloggs');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetch(PDO::FETCH_ASSOC);
    $row_id = $check['id'];
    // do something
}

If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:

$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname',  'Bloggs');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetchAll(PDO::FETCH_ASSOC);
    //$check will now hold an array of returned rows. 
    //let's say we need the second result, i.e. index of 1
    $row_id = $check[1]['id']; 
    // do something
}

Why are hexadecimal numbers prefixed with 0x?

The preceding 0 is used to indicate a number in base 2, 8, or 16.

In my opinion, 0x was chosen to indicate hex because 'x' sounds like hex.

Just my opinion, but I think it makes sense.

Good Day!

Java - Using Accessor and Mutator methods

You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables

public class IDCard {
    public String name, fileName;
    public int id;

    public IDCard(final String name, final String fileName, final int id) {
        this.name = name;
        this.fileName = fileName
        this.id = id;
    }

    public String getName() {
        return name;
    }
}

You can the create an IDCard and use the accessor like this:

final IDCard card = new IDCard();
card.getName();

Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.

If you use the static keyword then those variables are common across every instance of IDCard.

A couple of things to bear in mind:

  1. don't add useless comments - they add code clutter and nothing else.
  2. conform to naming conventions, use lower case of variable names - name not Name.

To show error message without alert box in Java Script

You can also try this


<tr>
    <th>Name :</th>
    <td><input type="text" name="name" id="name" placeholder="Enter Your Name"><div id="name_error"></div></td>
</tr>



    function register_validate()
{
    var name = document.getElementById('name').value;
    submit = true;
    if(name == '')
    {
        document.getElementById('name_error').innerHTML = "Name Is Required";
        return false;
    }
    return submit;
}
document.getElementById('name').onkeyup = removewarning;
function removewarning()
{
    document.getElementById(this.id +'_error').innerHTML = "";
}

java: How can I do dynamic casting of a variable from one type to another?

Yes it is possible using Reflection

Object something = "something";
String theType = "java.lang.String";
Class<?> theClass = Class.forName(theType);
Object obj = theClass.cast(something);

but that doesn't make much sense since the resulting object must be saved in a variable of Object type. If you need the variable be of a given class, you can just cast to that class.

If you want to obtain a given class, Number for example:

Object something = new Integer(123);
String theType = "java.lang.Number";
Class<? extends Number> theClass = Class.forName(theType).asSubclass(Number.class);
Number obj = theClass.cast(something);

but there is still no point doing it so, you could just cast to Number.

Casting of an object does NOT change anything; it is just the way the compiler treats it.
The only reason to do something like that is to check if the object is an instance of the given class or of any subclass of it, but that would be better done using instanceof or Class.isInstance().

Update

according your last update the real problem is that you have an Integer in your HashMap that should be assigned to a Double. What you can do in this case, is check the type of the field and use the xxxValue() methods of Number

...
Field f =  this.getClass().getField(entry.getKey());
Object value = entry.getValue();
if (Integer.class.isAssignableFrom(f.getType())) {
    value = Integer.valueOf(((Number) entry.getValue()).intValue());
} else if (Double.class.isAssignableFrom(f.getType())) {
    value = Double.valueOf(((Number) entry.getValue()).doubleValue());
} // other cases as needed (Long, Float, ...)
f.set(this, value);
...

(not sure if I like the idea of having the wrong type in the Map)

Abstract methods in Python

Before abc was introduced you would see this frequently.

class Base(object):
    def go(self):
        raise NotImplementedError("Please Implement this method")


class Specialized(Base):
    def go(self):
        print "Consider me implemented"

Horizontal ListView in Android?

HorizontialListView can't work when the data in the adapter is involved in another thread. Everything runs 100% on UI thread.This is a big problem in multithread. I think using HorizontialListView is not the best solution for your problem.HorzListView is a better way.You just replace your previous Gallery with HorzListView.You neednot modify the code about the adapter.Then everything goes the way you hope.See https://stackoverflow.com/a/12339708/1525777 about HorzListView.

Difference between pre-increment and post-increment in a loop?

In C# there is no difference when used in a for loop.

for (int i = 0; i < 10; i++) { Console.WriteLine(i); }

outputs the same thing as

for (int i = 0; i < 10; ++i) { Console.WriteLine(i); }

As others have pointed out, when used in general i++ and ++i have a subtle yet significant difference:

int i = 0;
Console.WriteLine(i++);   // Prints 0
int j = 0;
Console.WriteLine(++j);   // Prints 1

i++ reads the value of i then increments it.

++i increments the value of i then reads it.

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

You need an extra reference for this; the most convenient way to do this is via the NuGet package System.IO.Compression.ZipFile

<!-- Version here correct at time of writing, but please check for latest -->
<PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" />

If you are working on .NET Framework without NuGet, you need to add a dll reference to the assembly, "System.IO.Compression.FileSystem.dll" - and ensure you are using at least .NET 4.5 (since it doesn't exist in earlier frameworks).

For info, you can find the assembly and .NET version(s) from MSDN

How do I extract the contents of an rpm?

$ mkdir packagecontents; cd packagecontents
$ rpm2cpio ../foo.rpm | cpio -idmv
$ find . 

For Reference: the cpio arguments are

-i = extract
-d = make directories
-m = preserve modification time
-v = verbose

I found the answer over here: lontar's answer

Finding modified date of a file/folder

Here's what worked for me:

$a = Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-7)}
if ($a = (Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}  
#Im using the -gt switch instead of -ge
{}
Else
{
'STORE XXX HAS NOT RECEIVED ANY ORDERS IN THE PAST 7 DAYS'
}


$b = Get-ChildItem \\COMP NAME\Folder\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-1)}
if ($b = (Get-ChildItem \\COMP NAME\TFolder\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-1)))}
{}
Else
{
'STORE XXX DID NOT RUN ITS BACKUP LAST NIGHT'
}

Java AES and using my own Key

Edit:

As written in the comments the old code is not "best practice". You should use a keygeneration algorithm like PBKDF2 with a high iteration count. You also should use at least partly a non static (meaning for each "identity" exclusive) salt. If possible randomly generated and stored together with the ciphertext.

    SecureRandom sr = SecureRandom.getInstanceStrong();
    byte[] salt = new byte[16];
    sr.nextBytes(salt);

    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1000, 128 * 8);
    SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);
    Cipher aes = Cipher.getInstance("AES");
    aes.init(Cipher.ENCRYPT_MODE, key);

===========

Old Answer

You should use SHA-1 to generate a hash from your key and trim the result to 128 bit (16 bytes).

Additionally don't generate byte arrays from Strings through getBytes() it uses the platform default Charset. So the password "blaöä" results in different byte array on different platforms.

byte[] key = (SALT2 + username + password).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit

SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");

Edit: If you need 256 bit as key sizes you need to download the "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" Oracle download link, use SHA-256 as hash and remove the Arrays.copyOf line. "ECB" is the default Cipher Mode and "PKCS5Padding" the default padding. You could use different Cipher Modes and Padding Modes through the Cipher.getInstance string using following format: "Cipher/Mode/Padding"

For AES using CTS and PKCS5Padding the string is: "AES/CTS/PKCS5Padding"

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

How to set Spinner Default by its Value instead of Position?

You can do it easily like this.

String cls=student.getStudentClass();
class_spinner.setSelection(classArray.indexOf(cls),true);

What's the effect of adding 'return false' to a click event listener?

The return false is saying not to take the default action, which in the case of an <a href> is to follow the link. When you return false to the onclick, then the href will be ignored.

Writing binary number system in C code

Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b prefix:

int foo = 0b1010;

If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:

#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
        unsigned long long i = 0;
        while (*s) {
                i <<= 1;
                i += *s++ - '0';
        }
        return i;
}

And then you can use it like this:

int foo = B(1010);

If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.

Proof:

The following code:

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


#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
    unsigned long long i = 0;
    while (*s) {
        i <<= 1;
        i += *s++ - '0';
    }
    return i;
}

int main()
{
    int foo = B(001100101);

    printf("%d\n", foo);

    return 0;
}

has been compiled using clang -o baz.S baz.c -Wall -O3 -S, and it produced the following assembly:

    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp4:
    .cfi_def_cfa_register %rbp
    leaq    L_.str1(%rip), %rdi
    movl    $101, %esi               ## <= This line!
    xorb    %al, %al
    callq   _printf
    xorl    %eax, %eax
    popq    %rbp
    ret
    .cfi_endproc

    .section    __TEXT,__cstring,cstring_literals
L_.str1:                                ## @.str1
    .asciz   "%d\n"


.subsections_via_symbols

So clang completely eliminated the call to the function, and replaced its return value with 101. Neat, huh?

How to get the current branch name in Git?

You can permanently set up your bash output to show your git-branch name. It is very handy when you work with different branches, no need to type $ git status all the time. Github repo git-aware-prompt .

Open your terminal (ctrl-alt-t) and enter the commands

mkdir ~/.bash
cd ~/.bash
git clone git://github.com/jimeh/git-aware-prompt.git

Edit your .bashrc with sudo nano ~/.bashrc command (for Ubuntu) and add the following to the top:

export GITAWAREPROMPT=~/.bash/git-aware-prompt
source "${GITAWAREPROMPT}/main.sh"

Then paste the code

export PS1="\${debian_chroot:+(\$debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \[$txtcyn\]\$git_branch\[$txtred\]\$git_dirty\[$txtrst\]\$ "

at the end of the same file you pasted the installation code into earlier. This will give you the colorized output:enter image description here

App can't be opened because it is from an unidentified developer

An easier way to open a document from an unidentified developer, if you know it's safe, is to control-click on the file icon and then select "Open." You will then be given the option of opening it regardless of its unidentified source.

REST / SOAP endpoints for a WCF service

You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration

<endpointBehaviors>
  <behavior name="jsonBehavior">
    <enableWebScript/>
  </behavior>
</endpointBehaviors>

An example of endpoint configuration in your scenario is

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="json" binding="webHttpBinding"  behaviorConfiguration="jsonBehavior" contract="ITestService"/>
  </service>
</services>

so, the service will be available at

Apply [WebGet] to the operation contract to make it RESTful. e.g.

public interface ITestService
{
   [OperationContract]
   [WebGet]
   string HelloWorld(string text)
}

Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.

Reply to the post for SOAP and RESTful POX(XML)

For plain old XML as return format, this is an example that would work both for SOAP and XML.

[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
    [OperationContract]
    [WebGet(UriTemplate = "accounts/{id}")]
    Account[] GetAccount(string id);
}

POX behavior for REST Plain Old XML

<behavior name="poxBehavior">
  <webHttp/>
</behavior>

Endpoints

<services>
  <service name="TestService">
    <endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
    <endpoint address="xml" binding="webHttpBinding"  behaviorConfiguration="poxBehavior" contract="ITestService"/>
  </service>
</services>

Service will be available at

REST request try it in browser,

http://www.example.com/xml/accounts/A123

SOAP request client endpoint configuration for SOAP service after adding the service reference,

  <client>
    <endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
      contract="ITestService" name="BasicHttpBinding_ITestService" />
  </client>

in C#

TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");

Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.

How to select the rows with maximum values in each group with dplyr?

df %>% group_by(A,B) %>% slice(which.max(value))

How to use ES6 Fat Arrow to .filter() an array of objects

As simple as you can use const adults = family.filter(({ age }) => age > 18 );

_x000D_
_x000D_
const family =[{"name":"Jack",  "age": 26},_x000D_
              {"name":"Jill",  "age": 22},_x000D_
              {"name":"James", "age": 5 },_x000D_
              {"name":"Jenny", "age": 2 }];_x000D_
_x000D_
const adults = family.filter(({ age }) => age > 18 );_x000D_
_x000D_
console.log(adults)
_x000D_
_x000D_
_x000D_

Laravel 5 call a model function in a blade view

Related to the question in your answer:

You have multiple options to achieve this that are way better:

Let's assume you have a model which you pass to the view:

$model = Model::find(1);
View::make('view')->withModel($model);

Now in your Model you could have a function:

public function someFunction() {
    // do something
}

In your view you could call that function directly:

{{$model->someFunction()}}

This is nice if you want to do something with the model (the dataset).

If not you can still make a static function in the model:

public static function someStaticFunction($var1, $var2) {
    // do something
}

And then:

{{App\Model::someStaticFunction($yourVar1,$yourVar2)}}

Hope it helps.

Program "make" not found in PATH

Make sure you have installed 'make' tool through Cygwin's installer.

Is recursion ever faster than looping?

Functional programming is more about "what" rather than "how".

The language implementors will find a way to optimize how the code works underneath, if we don't try to make it more optimized than it needs to be. Recursion can also be optimized within the languages that support tail call optimization.

What matters more from a programmer standpoint is readability and maintainability rather than optimization in the first place. Again, "premature optimization is root of all evil".

List all sequences in a Postgres db 8.1 with SQL

Note, that starting from PostgreSQL 8.4 you can get all information about sequences used in the database via:

SELECT * FROM information_schema.sequences;

Since I'm using a higher version of PostgreSQL (9.1), and was searching for same answer high and low, I added this answer for posterity's sake and for future searchers.

Why is my toFixed() function not working?

document.getElementById("EDTVALOR").addEventListener("change", function() {
  this.value = this.value.replace(",", ".");
  this.value = parseFloat(this.value).toFixed(2);
  if (this.value < 0) {
    this.value = 0;
  }
  this.value = this.value.replace(".", ",");
  this.value = this.value.replace("NaN", "0");
});

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

Have you seen this one? From http://www.aspspider.com/resources/Resource510.aspx:

public DataTable Import(String path)
{
    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

    Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.ActiveSheet;

    int index = 0;
    object rowIndex = 2;

    DataTable dt = new DataTable();
    dt.Columns.Add("FirstName");
    dt.Columns.Add("LastName");
    dt.Columns.Add("Mobile");
    dt.Columns.Add("Landline");
    dt.Columns.Add("Email");
    dt.Columns.Add("ID");

    DataRow row;

    while (((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 1]).Value2 != null)
    {

        row = dt.NewRow();
        row[0] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 1]).Value2);
        row[1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 2]).Value2);
        row[2] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 3]).Value2);
        row[3] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 4]).Value2);
        row[4] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 5]).Value2);
        index++;

        rowIndex = 2 + index;
        dt.Rows.Add(row);
    }
    app.Workbooks.Close();
    return dt;
}

How to use phpexcel to read data and insert into database?

In order to read data from microsoft excel 2007 by codeigniter just create a helper function excel_helper.php and add the following in:

      require_once APPPATH.'libraries/phpexcel/PHPExcel.php';
      require_once APPPATH.'libraries/phpexcel/PHPExcel/IOFactory.php';
      in controller add the following code to read spread sheet by active sheet
     //initialize php excel first  
     ob_end_clean();
     //define cachemethod
     $cacheMethod   = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
     $cacheSettings = array('memoryCacheSize' => '20MB');
     //set php excel settings
     PHPExcel_Settings::setCacheStorageMethod(
            $cacheMethod,$cacheSettings
          );

    $arrayLabel = array("A","B","C","D","E");
    //=== set object reader
    $objectReader = PHPExcel_IOFactory::createReader('Excel2007');
    $objectReader->setReadDataOnly(true);

    $objPHPExcel = $objectReader->load("./forms/test.xlsx");
    $objWorksheet = $objPHPExcel->setActiveSheetIndexbyName('Sheet1');

    $starting = 1;
    $end      = 3;
    for($i = $starting;$i<=$end; $i++)
    {

       for($j=0;$j<count($arrayLabel);$j++)
       {
           //== display each cell value
           echo $objWorksheet->getCell($arrayLabel[$j].$i)->getValue();
       }
    }
     //or dump data
     $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
     var_dump($sheetData);

     //see also the following link
     http://blog.mayflower.de/561-Import-and-export-data-using-PHPExcel.html
     ----------- import in another style around 5000 records ------
     $this->benchmark->mark('code_start');
    //=== change php ini limits. =====
    $cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
    $cacheSettings = array( ' memoryCacheSize ' => '50MB');
    PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
    //==== create excel object of reader
    $objReader = PHPExcel_IOFactory::createReader('Excel2007');
    //$objReader->setReadDataOnly(true);
    //==== load forms tashkil where the file exists
    $objPHPExcel = $objReader->load("./forms/5000records.xlsx");
    //==== set active sheet to read data
    $worksheet  = $objPHPExcel->setActiveSheetIndexbyName('Sheet1');


    $highestRow         = $worksheet->getHighestRow(); // e.g. 10
    $highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $nrColumns          = ord($highestColumn) - 64;
    $worksheetTitle     = $worksheet->getTitle();

    echo "<br>The worksheet ".$worksheetTitle." has ";
    echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
    echo ' and ' . $highestRow . ' row.';
    echo '<br>Data: <table border="1"><tr>';
    //----- loop from all rows -----
    for ($row = 1; $row <= $highestRow; ++ $row) 
    {
        echo '<tr>';
        echo "<td>".$row."</td>";
        //--- read each excel column for each row ----
        for ($col = 0; $col < $highestColumnIndex; ++ $col) 
        {
            if($row == 1)
            {
                // show column name with the title
                 //----- get value ----
                $cell = $worksheet->getCellByColumnAndRow($col, $row);
                $val = $cell->getValue();
                //$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
                echo '<td>' . $val ."(".$row." X ".$col.")".'</td>';
            }
            else
            {
                if($col == 9)
                {
                    //----- get value ----
                    $cell = $worksheet->getCellByColumnAndRow($col, $row);
                    $val = $cell->getValue();
                    //$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
                    echo '<td>zone ' . $val .'</td>';
                }
                else if($col == 13)
                {
                    $date = PHPExcel_Shared_Date::ExcelToPHPObject($worksheet->getCellByColumnAndRow($col, $row)->getValue())->format('Y-m-d');
                    echo '<td>' .dateprovider($date,'dr') .'</td>';
                }
                else
                {
                     //----- get value ----
                    $cell = $worksheet->getCellByColumnAndRow($col, $row);
                    $val = $cell->getValue();
                    //$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
                    echo '<td>' . $val .'</td>';
                }
            }
        }
        echo '</tr>';
    }
    echo '</table>';
    $this->benchmark->mark('code_end');

    echo "Total time:".$this->benchmark->elapsed_time('code_start', 'code_end');     
    $this->load->view("error");

Why can't I find SQL Server Management Studio after installation?

Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.

It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\

Update Git branches from master

git rebase master is the proper way to do this. Merging would mean a commit would be created for the merge, while rebasing would not.

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

The following steps could help:

  1. Right-click on project » Properties » Java Build Path
  2. Select Libraries tab
  3. Find the JRE System Library and remove it
  4. Click Add Library... button at right side » Add the JRE System Library (Workspace default JRE)

How to get data out of a Node.js http get request

Of course your logs return undefined : you log before the request is done. The problem isn't scope but asynchronicity.

http.request is asynchronous, that's why it takes a callback as parameter. Do what you have to do in the callback (the one you pass to response.end):

callback = function(response) {

  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(req.data);
    console.log(str);
    // your code here if you want to use the results !
  });
}

var req = http.request(options, callback).end();

How do I get the current username in .NET using C#?

Get the current Windows username:

using System;

class Sample
{
    public static void Main()
    {
        Console.WriteLine();

        //  <-- Keep this information secure! -->
        Console.WriteLine("UserName: {0}", Environment.UserName);
    }
}

How can you search Google Programmatically Java API

Indeed there is an API to search google programmatically. The API is called google custom search. For using this API, you will need an Google Developer API key and a cx key. A simple procedure for accessing google search from java program is explained in my blog.

Now dead, here is the Wayback Machine link.

Creating dummy variables in pandas for python

So I was actually needing an answer to this question today (7/25/2013), so I wrote this earlier. I've tested it with some toy examples, hopefully you get some mileage out of it

def categorize_dict(x, y=0):
    # x Requires string or numerical input
    # y is a boolean that specifices whether to return category names along with the dict.
    # default is no
    cats = list(set(x))
    n = len(cats)
    m = len(x)
    outs = {}
    for i in cats:
        outs[i] = [0]*m
    for i in range(len(x)):
        outs[x[i]][i] = 1
    if y:
        return outs,cats
    return outs

Git and nasty "error: cannot lock existing info/refs fatal"

For me this worked:

git remote prune origin

Since this answer seems to help a lot of people, I dug a little bit into what actually happens here. What this will do is remove references to remote branches in the folder .git/refs/remotes/origin. So this will not affect your local branches and it will not change anything remote, but it will update the local references you have to remote branches. It seems in some cases these references can contain data Git cannot handle correctly.

How to decrease prod bundle size?

I have a angular 5 + spring boot app(application.properties 1.3+) with help of compression(link attached below) was able to reduce the size of main.bundle.ts size from 2.7 MB to 530 KB.

Also by default --aot and --build-optimizer are enabled with --prod mode you need not specify those separately.

https://stackoverflow.com/a/28216983/9491345

Convert an image (selected by path) to base64 string

Since most of us like oneliners:

Convert.ToBase64String(File.ReadAllBytes(imageFilepath));

If you need it as Base64 byte array:

Encoding.ASCII.GetBytes(Convert.ToBase64String(File.ReadAllBytes(imageFilepath)));

How do I load an HTML page in a <div> using JavaScript?

When using

$("#content").load("content.html");

Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server

Express.js - app.listen vs server.listen

The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io within the same HTTP server instance:

var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
...
server.listen(1234);

However, app.listen() also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:

var express   = require('express');
var app       = express();

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  ...
});

Simple regular expression for a decimal with a precision of 2

^[0-9]+(\.[0-9]{1,2})?$

And since regular expressions are horrible to read, much less understand, here is the verbose equivalent:

^                         # Start of string
 [0-9]+                   # Require one or more numbers
       (                  # Begin optional group
        \.                # Point must be escaped or it is treated as "any character"
          [0-9]{1,2}      # One or two numbers
                    )?    # End group--signify that it's optional with "?"
                      $   # End of string

You can replace [0-9] with \d in most regular expression implementations (including PCRE, the most common). I've left it as [0-9] as I think it's easier to read.

Also, here is the simple Python script I used to check it:

import re
deci_num_checker = re.compile(r"""^[0-9]+(\.[0-9]{1,2})?$""")

valid = ["123.12", "2", "56754", "92929292929292.12", "0.21", "3.1"]
invalid = ["12.1232", "2.23332", "e666.76"]

assert len([deci_num_checker.match(x) != None for x in valid]) == len(valid)
assert [deci_num_checker.match(x) == None for x in invalid].count(False) == 0

Select <a> which href ends with some string

$("a[href*=ABC]").addClass('selected');

Playing m3u8 Files with HTML Video Tag

Use Flowplayer:

<link rel="stylesheet" href="//releases.flowplayer.org/7.0.4/commercial/skin/skin.css">
    <style>

   </style>
   <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
  <script src="//releases.flowplayer.org/7.0.4/commercial/flowplayer.min.js"></script>
  <script src="//releases.flowplayer.org/hlsjs/flowplayer.hlsjs.min.js"></script> 
  <script>
  flowplayer(function (api) {
    api.on("load", function (e, api, video) {
      $("#vinfo").text(api.engine.engineName + " engine playing " + video.type);
    }); });
  </script>

<div class="flowplayer fixed-controls no-toggle no-time play-button obj"
      style="    width: 85.5%;
    height: 80%;
    margin-left: 7.2%;
    margin-top: 6%;
    z-index: 1000;" data-key="$812975748999788" data-live="true" data-share="false" data-ratio="0.5625"  data-logo="">
      <video autoplay="true" stretch="true">

         <source type="application/x-mpegurl" src="http://live.wmncdn.net/safaritv2/live2.stream/index.m3u8">
      </video>   
   </div>

Different methods are available in flowplayer.org website.

Group list by values

len = max(key for (item, key) in list)
newlist = [[] for i in range(len+1)]
for item,key in list:
  newlist[key].append(item)

You can do it in a single list comprehension, perhaps more elegant but O(n**2):

[[item for (item,key) in list if key==i] for i in range(max(key for (item,key) in list)+1)]

How to go back to previous page if back button is pressed in WebView?

You can try this for webview in a fragment:

private lateinit var webView: WebView

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val root = inflater.inflate(R.layout.fragment_name, container, false)
    webView = root!!.findViewById(R.id.home_web_view)
    var url: String = "http://yoururl.com"
    webView.settings.javaScriptEnabled = true
    webView.webViewClient = WebViewClient()
    webView.loadUrl(url)
    webView.canGoBack()
    webView.setOnKeyListener{ v, keyCode, event ->
        if(keyCode == KeyEvent.KEYCODE_BACK && event.action == MotionEvent.ACTION_UP
            && webView.canGoBack()){
            webView.goBack()
            return@setOnKeyListener true
        }
        false
    }
    return root
}

How do I do a multi-line string in node.js?

Take a look at the mstring module for node.js.

This is a simple little module that lets you have multi-line strings in JavaScript.

Just do this:

var M = require('mstring')

var mystring = M(function(){/*** Ontario Mining and Forestry Group ***/})

to get

mystring === "Ontario\nMining and\nForestry\nGroup"

And that's pretty much it.

How It Works
In Node.js, you can call the .toString method of a function, and it will give you the source code of the function definition, including any comments. A regular expression grabs the content of the comment.

Yes, it's a hack. Inspired by a throwaway comment from Dominic Tarr.


note: The module (as of 2012/13/11) doesn't allow whitespace before the closing ***/, so you'll need to hack it in yourself.

Reading CSV file and storing values into an array

You can do it like this:

using System.IO;

static void Main(string[] args)
{
    using(var reader = new StreamReader(@"C:\test.csv"))
    {
        List<string> listA = new List<string>();
        List<string> listB = new List<string>();
        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            var values = line.Split(';');

            listA.Add(values[0]);
            listB.Add(values[1]);
        }
    }
}

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

Had this issue when migrated spring boot 1.5.2 to 2.0.4. Instead of creating bean I've used @EnableAutoConfiguration in the main class and it solved my problem.

Combining a class selector and an attribute selector with jQuery

This code works too:

$("input[reference=12345].myclass").css('border', '#000 solid 1px');

How to set maximum fullscreen in vmware?

From you main machine, start -> search -> "remote desktop connection" -> click on "remote desktop connection" -> Click "Options" Beside to "Connect Button" -> Display Tab - > Then increase Display Configuriton Size. If this will not work, try the same thing by closing remote desktop. But this will give you solution.

What does the keyword Set actually do in VBA?

Set is used for setting object references, as opposed to assigning a value.

How do you divide each element in a list by an int?

The abstract version can be:

import numpy as np
myList = [10, 20, 30, 40, 50, 60, 70, 80, 90]
myInt = 10
newList  = np.divide(myList, myInt)

How to insert a large block of HTML in JavaScript?

If I understand correctly, you're looking for a multi-line representation, for readability? You want something like a here-string in other languages. Javascript can come close with this:

var x =
    "<div> \
    <span> \
    <p> \
    some text \
    </p> \
    </div>";

Creating a batch file, for simple javac and java command execution

I just made a simple batch script that takes a file name as an argument compiles and runs the java file with one command. Here is the code:

@echo off
set arg1=%1
shift
javac -cp . %arg1%.java
java %arg1%
pause

I just saved that as run-java.bat and put it in the System32 directory so I can use the script from wherever I wish.

To use the command I would do:

run-java filename

and it will compile and run the file. Just make sure to leave out the .java extension when you type the filename (you could make it work even when you type the file name but I am new to batch and don't know how to do that yet).

jQuery: Clearing Form Inputs

You may try

$("#addRunner input").each(function(){ ... });

Inputs are no selectors, so you do not need the : Haven't tested it with your code. Just a fast guess!

Is there a way to do repetitive tasks at intervals?

How about something like

package main

import (
    "fmt"
    "time"
)

func schedule(what func(), delay time.Duration) chan bool {
    stop := make(chan bool)

    go func() {
        for {
            what()
            select {
            case <-time.After(delay):
            case <-stop:
                return
            }
        }
    }()

    return stop
}

func main() {
    ping := func() { fmt.Println("#") }

    stop := schedule(ping, 5*time.Millisecond)
    time.Sleep(25 * time.Millisecond)
    stop <- true
    time.Sleep(25 * time.Millisecond)

    fmt.Println("Done")
}

Playground

How to set tint for an image view programmatically in android?

Simple and one line

imageView.setColorFilter(activity.getResources().getColor(R.color.your_color));

How to import/include a CSS file using PHP code and not HTML code?

Just put

echo "<link rel='stylesheet' type='text/css' href='CSS/main.css'>";

inside the php code, then your style is incuded. Worked for me, I tried.

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

Ok, I want to provide a small answer to one of the sub-questions that the OP asked that don't seem to be addressed in the existing questions. Caveat, I have not done any testing or code generation, or disassembly, just wanted to share a thought for others to possibly expound upon.

Why does the static change the performance?

The line in question: uint64_t size = atol(argv[1])<<20;

Short Answer

I would look at the assembly generated for accessing size and see if there are extra steps of pointer indirection involved for the non-static version.

Long Answer

Since there is only one copy of the variable whether it was declared static or not, and the size doesn't change, I theorize that the difference is the location of the memory used to back the variable along with where it is used in the code further down.

Ok, to start with the obvious, remember that all local variables (along with parameters) of a function are provided space on the stack for use as storage. Now, obviously, the stack frame for main() never cleans up and is only generated once. Ok, what about making it static? Well, in that case the compiler knows to reserve space in the global data space of the process so the location can not be cleared by the removal of a stack frame. But still, we only have one location so what is the difference? I suspect it has to do with how memory locations on the stack are referenced.

When the compiler is generating the symbol table, it just makes an entry for a label along with relevant attributes, like size, etc. It knows that it must reserve the appropriate space in memory but doesn't actually pick that location until somewhat later in process after doing liveness analysis and possibly register allocation. How then does the linker know what address to provide to the machine code for the final assembly code? It either knows the final location or knows how to arrive at the location. With a stack, it is pretty simple to refer to a location based one two elements, the pointer to the stackframe and then an offset into the frame. This is basically because the linker can't know the location of the stackframe before runtime.

How do I get the number of days between two dates in JavaScript?

_x000D_
_x000D_
Date.prototype.days = function(to) {_x000D_
  return Math.abs(Math.floor(to.getTime() / (3600 * 24 * 1000)) - Math.floor(this.getTime() / (3600 * 24 * 1000)))_x000D_
}_x000D_
_x000D_
_x000D_
console.log(new Date('2014/05/20').days(new Date('2014/05/23'))); // 3 days_x000D_
_x000D_
console.log(new Date('2014/05/23').days(new Date('2014/05/20'))); // 3 days
_x000D_
_x000D_
_x000D_

How do I find duplicate values in a table in Oracle?

I know its an old thread but this may help some one.

If you need to print other columns of the table while checking for duplicate use below:

select * from table where column_name in
(select ing.column_name from table ing group by ing.column_name having count(*) > 1)
order by column_name desc;

also can add some additional filters in the where clause if needed.

How do you do a deep copy of an object in .NET?

I've seen a few different approaches to this, but I use a generic utility method as such:

public static T DeepClone<T>(this T obj)
{
 using (var ms = new MemoryStream())
 {
   var formatter = new BinaryFormatter();
   formatter.Serialize(ms, obj);
   ms.Position = 0;

   return (T) formatter.Deserialize(ms);
 }
}

Notes:

  • Your class MUST be marked as [Serializable] for this to work.
  • Your source file must include the following code:

    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;
    

Find the number of employees in each department - SQL Oracle

SELECT d.DEPTNO
    , d.dname
    , COUNT(e.ename) AS count
FROM   emp e
      INNER JOIN dept d ON e.DEPTNO = d.deptno
GROUP BY d.deptno
      , d.dname;

jQuery Ajax Request inside Ajax Request

$.ajax({
    url: "<?php echo site_url('upToWeb/ajax_edit/')?>/" + id,
    type: "GET",
    dataType: "JSON",
    success: function (data) {
        if (data.web == 0) {
            if (confirm('Data product upToWeb ?')) {
                $.ajax({
                    url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
                    type: "post",
                    dataType: "json",
                    data: {web: 1},
                    success: function (respons) {
                        location.href = location.pathname;
                    },
                    error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
                        alert(xhr.responseText); // munculkan alert
                    }
                });
            }
        }
        else {
            if (confirm('Data product DownFromWeb ?')) {
                $.ajax({
                    url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
                    type: "post",
                    dataType: "json",
                    data: {web: 0},
                    success: function (respons) {
                        location.href = location.pathname;
                    },
                    error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
                        alert(xhr.responseText); // munculkan alert
                    }
                });
            }
        }
    },

    error: function (jqXHR, textStatus, errorThrown) {
        alert('Error get data from ajax');
    }

});

How to convert String to Date value in SAS?

This code helps:

data final; set final;

first_date = INPUT(compress(char_date),date9.); format first_date date9.;

run;

I personally have tried it on SAS

Simple IEnumerator use (with example)

Also you can use LINQ's Select Method:

var source = new[] { "Line 1", "Line 2" };

var result = source.Select(s => s + " roxxors");

Read more here Enumerable.Select Method

Ruby Hash to array of values

hash  = { :a => ["a", "b", "c"], :b => ["b", "c"] }
hash.values #=> [["a","b","c"],["b","c"]]

Error ITMS-90717: "Invalid App Store Icon"

changed the icon from .png format to .jpg and everything went well.

PHP regular expression - filter number only

You can try that one:

$string = preg_replace('/[^0-9]/', '', $string);

Cheers.

How to Execute stored procedure from SQL Plus?

You have two options, a PL/SQL block or SQL*Plus bind variables:

var z number

execute  my_stored_proc (-1,2,0.01,:z)

print z

How to get the Full file path from URI

Use:

String path = yourAndroidURI.uri.getPath() // "/mnt/sdcard/FileName.mp3"
File file = new File(new URI(path));

or

String path = yourAndroidURI.uri.toString() // "file:///mnt/sdcard/FileName.mp3"
File file = new File(new URI(path));

Downgrade npm to an older version

Just replace @latest with the version number you want to downgrade to. I wanted to downgrade to version 3.10.10, so I used this command:

npm install -g [email protected]

If you're not sure which version you should use, look at the version history. For example, you can see that 3.10.10 is the latest version of npm 3.

How do I write a Windows batch script to copy the newest file from a directory?

The accepted answer gives an example of using the newest file in a command and then exiting. If you need to do this in a bat file with other complex operations you can use the following to store the file name of the newest file in a variable:

FOR /F "delims=|" %%I IN ('DIR "*.*" /B /O:D') DO SET NewestFile=%%I

Now you can reference %NewestFile% throughout the rest of your bat file.

For example here is what we use to get the latest version of a database .bak file from a directory, copy it to a server, and then restore the db:

:Variables
SET DatabaseBackupPath=\\virtualserver1\Database Backups

echo.
echo Restore WebServer Database
FOR /F "delims=|" %%I IN ('DIR "%DatabaseBackupPath%\WebServer\*.bak" /B /O:D') DO SET NewestFile=%%I
copy "%DatabaseBackupPath%\WebServer\%NewestFile%" "D:\"

sqlcmd -U <username> -P <password> -d master -Q ^
"RESTORE DATABASE [ExampleDatabaseName] ^
FROM  DISK = N'D:\%NewestFile%' ^
WITH  FILE = 1,  ^
MOVE N'Example_CS' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example.mdf',  ^
MOVE N'Example_CS_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example_1.LDF',  ^
NOUNLOAD,  STATS = 10"

Using an attribute of the current class instance as a default value for method's parameter

There are multiple false assumptions you're making here - First, function belong to a class and not to an instance, meaning the actual function involved is the same for any two instances of a class. Second, default parameters are evaluated at compile time and are constant (as in, a constant object reference - if the parameter is a mutable object you can change it). Thus you cannot access self in a default parameter and will never be able to.

How to find the sum of an array of numbers

Anyone looking for a functional oneliner like me? Take this:

sum = arr.reduce((a, b) => a + b, 0);

(If you happen to have to support ye olde IE without arrow functions:)

sum = arr.reduce(function (a, b) {return a + b;}, 0);

Add to integers in a list

fooList = [1,3,348,2]
fooList.append(3)
fooList.append(2734)
print(fooList) # [1,3,348,2,3,2734]

Angularjs ng-model doesn't work inside ng-if

You can do it like this and you mod function will work perfect let me know if you want a code pen

  <div ng-repeat="icon in icons">                   
                <div class="row" ng-if="$index % 3 == 0 ">
                    <i class="col col-33 {{icons[$index + n].icon}} custom-icon"></i>
                    <i class="col col-33 {{icons[$index + n + 1].icon}} custom-icon"></i>
                    <i class="col col-33 {{icons[$index + n + 2].icon}} custom-icon"></i>
                </div>
         </div>

Load and execution sequence of a web page?

The chosen answer looks like does not apply to modern browsers, at least on Firefox 52. What I observed is that the requests of loading resources like css, javascript are issued before HTML parser reaches the element, for example

<html>
  <head>
    <!-- prints the date before parsing and blocks HTMP parsering -->
    <script>
      console.log("start: " + (new Date()).toISOString());
      for(var i=0; i<1000000000; i++) {};
    </script>

    <script src="jquery.js" type="text/javascript"></script>
    <script src="abc.js" type="text/javascript"></script>
    <link rel="stylesheets" type="text/css" href="abc.css"></link>
    <style>h2{font-wight:bold;}</style>
    <script>
      $(document).ready(function(){
      $("#img").attr("src", "kkk.png");
     });
   </script>
 </head>
 <body>
   <img id="img" src="abc.jpg" style="width:400px;height:300px;"/>
   <script src="kkk.js" type="text/javascript"></script>
   </body>
</html>

What I found that the start time of requests to load css and javascript resources were not being blocked. Looks like Firefox has a HTML scan, and identify key resources(img resource is not included) before starting to parse the HTML.

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

For Tomcat running on Ubuntu server, to find out which Java is being used, use "ps -ef | grep tomcat" command:

Sample:

/home/mcp01$ **ps -ef |grep tomcat**
tomcat7  28477     1  0 10:59 ?        00:00:18 **/usr/local/java/jdk1.7.0_15/bin/java** -Djava.util.logging.config.file=/var/lib/tomcat7/conf/logging.properties -Djava.awt.headless=true -Xmx512m -XX:+UseConcMarkSweepGC -Djava.net.preferIPv4Stack=true -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.endorsed.dirs=/usr/share/tomcat7/endorsed -classpath /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar -Dcatalina.base=/var/lib/tomcat7 -Dcatalina.home=/usr/share/tomcat7 -Djava.io.tmpdir=/tmp/tomcat7-tomcat7-tmp org.apache.catalina.startup.Bootstrap start
1005     28567 28131  0 11:34 pts/1    00:00:00 grep --color=auto tomcat

Then, we can go in to: cd /usr/local/java/jdk1.7.0_15/jre/lib/security

Default cacerts file is located in here. Insert the untrusted certificate into it.

Regular expression for exact match of a string

(?<![\w\d])abc(?![\w\d])

this makes sure that your match is not preceded by some character, number, or underscore and is not followed immediately by character or number, or underscore

so it will match "abc" in "abc", "abc.", "abc ", but not "4abc", nor "abcde"

Radio button validation in javascript

1st: If you know that your code isn't right, you should fix it before do anything!

You could do something like this:

function validateForm() {
    var radios = document.getElementsByName("yesno");
    var formValid = false;

    var i = 0;
    while (!formValid && i < radios.length) {
        if (radios[i].checked) formValid = true;
        i++;        
    }

    if (!formValid) alert("Must check some option!");
    return formValid;
}?

See it in action: http://jsfiddle.net/FhgQS/

Change image in HTML page every few seconds

Best way to swap images with javascript with left vertical clickable thumbnails

SCRIPT FILE: function swapImages() {

    window.onload = function () {
        var img = document.getElementById("img_wrap");
        var imgall = img.getElementsByTagName("img");
        var firstimg = imgall[0]; //first image
        for (var a = 0; a <= imgall.length; a++) {
            setInterval(function () {
                var rand = Math.floor(Math.random() * imgall.length);
                firstimg.src = imgall[rand].src;
            }, 3000);



            imgall[1].onmouseover = function () {
                 //alert("what");
                clearInterval();
                firstimg.src = imgall[1].src;


            }
            imgall[2].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[2].src;
            }
            imgall[3].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[3].src;
            }
            imgall[4].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[4].src;
            }
            imgall[5].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[5].src;
            }
        }

    }


}

Using the Underscore module with Node.js

Note: The following only works for the next line of code, and only due to a coincidence.

With Lodash,

require('lodash');
_.isArray([]); // true

No var _ = require('lodash') since Lodash mysteriously sets this value globally when required.

Java Regex Replace with Capturing Group

How about:

if (regexMatcher.find()) {
    resultString = regexMatcher.replaceAll(
            String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}

To get the first match, use #find(). After that, you can use #group(1) to refer to this first match, and replace all matches by the first maches value multiplied by 3.

And in case you want to replace each match with that match's value multiplied by 3:

    Pattern p = Pattern.compile("(\\d{1,2})");
    Matcher m = p.matcher("12 54 1 65");
    StringBuffer s = new StringBuffer();
    while (m.find())
        m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
    System.out.println(s.toString());

You may want to look through Matcher's documentation, where this and a lot more stuff is covered in detail.

PHP function to build query string from array

Just as addition to @thatjuan's answer.
More compatible PHP4 version of this:

if (!function_exists('http_build_query')) {
    if (!defined('PHP_QUERY_RFC1738')) {
        define('PHP_QUERY_RFC1738', 1);
    }
    if (!defined('PHP_QUERY_RFC3986')) {
        define('PHP_QUERY_RFC3986', 2);
    }
    function http_build_query($query_data, $numeric_prefix = '', $arg_separator = '&', $enc_type = PHP_QUERY_RFC1738)
    {
        $data = array();
        foreach ($query_data as $key => $value) {
            if (is_numeric($key)) {
                $key = $numeric_prefix . $key;
            }
            if (is_scalar($value)) {
                $k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($key) : rawurlencode($key);
                $v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($value) : rawurlencode($value);
                $data[] = "$k=$v";
            } else {
                foreach ($value as $sub_k => $val) {
                    $k = "$key[$sub_k]";
                    $k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($k) : rawurlencode($k);
                    $v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($val) : rawurlencode($val);
                    $data[] = "$k=$v";
                }
            }
        }
        return implode($arg_separator, $data);
    }
}

What's the best way to detect a 'touch screen' device using JavaScript?

Right so there is a huge debate over detecting touch/non-touch devices. The number of window tablets and the size of tablets is increasing creating another set of headaches for us web developers.

I have used and tested blmstr's answer for a menu. The menu works like this: when the page loads the script detects if this is a touch or non touch device. Based on that the menu would work on hover (non-touch) or on click/tap (touch).

In most of the cases blmstr's scripts seemed to work just fine (specifically the 2018 one). BUT there was still that one device that would be detected as touch when it is not or vice versa.

For this reason I did a bit of digging and thanks to this article I replaced a few lines from blmstr's 4th script into this:

_x000D_
_x000D_
function is_touch_device4() {
    if ("ontouchstart" in window)
        return true;

    if (window.DocumentTouch && document instanceof DocumentTouch)
        return true;


    return window.matchMedia( "(pointer: coarse)" ).matches;
}

alert('Is touch device: '+is_touch_device4());
console.log('Is touch device: '+is_touch_device4());
_x000D_
_x000D_
_x000D_

Because of the lockdown have a limited supply of touch devices to test this one but so far the above works great.

I would appreceate if anyone with a desktop touch device (ex. surface tablet) can confirm if script works all right.

Now in terms of support the pointer: coarse media query seems to be supported. I kept the lines above since I had (for some reason) issues on mobile firefox but the lines above the media query do the trick.

Thanks

Convert an array into an ArrayList

declaring the list (and initializing it with an empty arraylist)

List<Card> cardList = new ArrayList<Card>();

adding an element:

Card card;
cardList.add(card);

iterating over elements:

for(Card card : cardList){
    System.out.println(card);
}

How to downgrade php from 5.5 to 5.3

Long answer: it is possible!

  1. Temporarily rename existing xampp folder
  2. Install xampp 1.7.7 into xampp folder name
  3. Folder containing just installed 1.7.7 distribution rename to different name and previously existing xampp folder rename back just to xampp.
  4. In xampp folder rename php and apache folders to different names (I propose php_prev and apache_prev) so you can after switch back to them by renaming them back.
  5. Copy apache and php folders from folder with xampp 1.7.7 into xampp directory
  6. In xampp directory comment line apache/conf/httpd.conf:458

    #Include "conf/extra/httpd-perl.conf"

  7. In xampp directory do next replaces in files:

php/pci.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pci" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\php.exe" -f "%XAMPPPHPDIR%\pci" -- %*

php/pciconf.bat:15

from

"C:\xampp\php\.\php.exe" -f "\xampp\php\pciconf" -- %*

to

set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\.\php.exe" -f "%XAMPPPHPDIR%\pciconf" -- %*

php/pear.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/peardev.bat:33

from

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/pecl.bat:32

from

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"

to

IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php\" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"

php/phar.phar.bat:1

from

%~dp0php.exe %~dp0pharcommand.phar %*

to

"%~dp0php.exe" "%~dp0pharcommand.phar" %*

Enjoy new XAMPP with PHP 5.3

Checked by myself in XAMPP 5.6.31, 7.0.15 & 7.1.1 with XAMPP Control Panel v3.2.2

How to find server name of SQL Server Management Studio

Open CMD

Run this

SQLCMD -L

You will get list of SQL Server instance

Trying Gradle build - "Task 'build' not found in root project"

Check your file: settings.gradle for presence lines with included subprojects (for example: include chapter1-bookstore )

Set selected option of select box

$('#gate').val('Gateway 2').prop('selected', true);

What is object serialization?

Serialization means persisting objects in java. If you want to save the state of the object and want to rebuild the state later (may be in another JVM) serialization can be used.

Note that the properties of an object is only going to be saved. If you want to resurrect the object again you should have the class file, because the member variables only will be stored and not the member functions.

eg:

ObjectInputStream oos = new ObjectInputStream(                                 
                                 new FileInputStream(  new File("o.ser")) ) ;
SerializationSample SS = (SearializationSample) oos.readObject();

The Searializable is a marker interface which marks that your class is serializable. Marker interface means that it is just an empty interface and using that interface will notify the JVM that this class can be made serializable.

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

Making a POST call instead of GET using urllib2

Have a read of the urllib Missing Manual. Pulled from there is the following simple example of a POST request.

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe', 'age'  : '10'})
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
print response.read()

As suggested by @Michael Kent do consider requests, it's great.

EDIT: This said, I do not know why passing data to urlopen() does not result in a POST request; It should. I suspect your server is redirecting, or misbehaving.

How do I vertically center text with CSS?

_x000D_
_x000D_
.box {  _x000D_
  width: 100%;_x000D_
  background: #000;_x000D_
  font-size: 48px;_x000D_
  color: #FFF;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.height {_x000D_
  line-height: 170px;_x000D_
  height: 170px;_x000D_
}_x000D_
_x000D_
.transform { _x000D_
  height: 170px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.transform p {_x000D_
  margin: 0;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  -ms-transform: translate(-50%, -50%);_x000D_
  transform: translate(-50%, -50%);_x000D_
}
_x000D_
<h4>Using Height</h4>_x000D_
<div class="box height">_x000D_
  Lorem ipsum dolor sit_x000D_
</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<h4>Using Transform</h4>_x000D_
<div class="box transform">_x000D_
  <p>Lorem ipsum dolor sit</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to create a HTML Table from a PHP array?

You can also use array_reduce

array_reduce — Iteratively reduce the array to a single value using a callback function

example:

$tbody = array_reduce($rows, function($a, $b){return $a.="<tr><td>".implode("</td><td>",$b)."</td></tr>";});
$thead = "<tr><th>" . implode("</th><th>", array_keys($rows[0])) . "</th></tr>";

echo "<table>\n$thead\n$tbody\n</table>";

How to find the lowest common ancestor of two nodes in any binary tree?

The following is the fastest way to solve this . Space complexity O(1) , Time complexity O(n). If

If a node has both left and right value as not null, then that node is your answer(3rd 'if' from top). While iterating if a value is found, as all the values are uniques and must be present, we don't need to search its descendants. so just return the found node that matched. if a node's both left and right branch contents null propagate null upwards. when reached top-level recursion, if one branch returned value, others do not keep propagating that value, when both returned not null return current node. If it reaches root level recursion with one null and another not null, return not null value, as the question, promises the value exists, it must be in the children tree of the found node which we never traversed.

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return null;
        if(root.val == p.val || root.val == q.val) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right !=null) return root;
        if (left == null && right ==null) return null;
        return (left != null ? left : right);
    }
}

enter image description here

Run JavaScript when an element loses focus

You want to use the onblur event.

<input type="text" name="name" value="value" onblur="alert(1);"/>

Creating a URL in the controller .NET MVC

Another way to create an absolute URL to an action:

var relativeUrl = Url.Action("MyAction");  //..or one of the other .Action() overloads
var currentUrl = Request.Url;

var absoluteUrl = new System.Uri(currentUrl, relativeUrl);

If '<selector>' is an Angular component, then verify that it is part of this module

Maybe This is for name of html tag component

You use in html something like this <mycomponent></mycomponent>

You must use this <app-mycomponent></app-mycomponent>

Object passed as parameter to another class, by value or reference?

In general, an "object" is an instance of a class, which is an "image"/"fingerprint" of a class created in memory (via New keyword).
The variable of object type refers to this memory location, that is, it essentially contains the address in memory.
So a parameter of object type passes a reference/"link" to an object, not a copy of the whole object.

If conditions in a Makefile, inside a target

There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)

You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.

UNAME := $(shell uname -m)

all:
    $(info Checking if custom header is needed)
    ifeq ($(UNAME), x86_64)
    ... do some things to build unistd_32.h
    endif

    @make -C $(KDIR) M=$(PWD) modules

So you want unistd_32.h built (maybe) before you invoke the second make, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:

ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif

all:
    @make -C $(KDIR) M=$(PWD) modules

unistd_32.h:
    ... do some things to build unistd_32.h

Now for building unistd_32.h:

F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
    $(info Copying custom header)
    $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else    
    F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
    ifeq ($(F2_EXISTS), 1)
        $(info Copying custom header)
        $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
    else
        $(error asm/unistd_32.h and asm-386/unistd.h does not exist)
    endif
endif

You are trying to build unistd.h from unistd_32.h; the only trick is that unistd_32.h could be in either of two places. The simplest way to clean this up is to use a vpath directive:

vpath unistd.h /usr/include/asm /usr/include/asm-i386

unistd_32.h: unistd.h
    sed -e 's/__NR_/__NR32_/g' $< > $@

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

The first one, ideally with a real link to follow in case the user has JavaScript disabled. Just make sure to return false to prevent the click event from firing if the JavaScript executes.

<a href="#" onclick="myJsFunc(); return false;">Link</a>

If you use Angular2, this way works:

<a [routerLink]="" (click)="passTheSalt()">Click me</a>.

See here https://stackoverflow.com/a/45465728/2803344

What is the usefulness of PUT and DELETE HTTP request methods?

Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times

According to your requirement :

1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD

How can I remove duplicate rows?

By useing below query we can able to delete duplicate records based on the single column or multiple column. below query is deleting based on two columns. table name is: testing and column names empno,empname

DELETE FROM testing WHERE empno not IN (SELECT empno FROM (SELECT empno, ROW_NUMBER() OVER (PARTITION BY empno ORDER BY empno) 
AS [ItemNumber] FROM testing) a WHERE ItemNumber > 1)
or empname not in
(select empname from (select empname,row_number() over(PARTITION BY empno ORDER BY empno) 
AS [ItemNumber] FROM testing) a WHERE ItemNumber > 1)

How to list all `env` properties within jenkins pipeline job?

The answers above, are now antiquated due to new pipeline syntax. Below prints out the environment variables.

script {
        sh 'env > env.txt'
        String[] envs = readFile('env.txt').split("\r?\n")

        for(String vars: envs){
            println(vars)
        }
    }

How do I check if an index exists on a table field in MySQL?

Try use this:

SELECT TRUE
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE TABLE_SCHEMA = "{DB_NAME}" 
AND TABLE_NAME = "{DB_TABLE}"
AND COLUMN_NAME = "{DB_INDEXED_FIELD}";

How do you synchronise projects to GitHub with Android Studio?

On Android Studio 1.0.2 you only need to go VCS-> Import into Version control -> Share Project on GitHub.

Pop up will appear asking for the repo name.

Javascript - get array of dates between 2 dates

This may help someone,

You can get the row output from this and format the row_date object as you want.

var from_date = '2016-01-01';
var to_date = '2016-02-20';

var dates = getDates(from_date, to_date);

console.log(dates);

function getDates(from_date, to_date) {
  var current_date = new Date(from_date);
  var end_date     = new Date(to_date);

  var getTimeDiff = Math.abs(current_date.getTime() - end_date.getTime());
  var date_range = Math.ceil(getTimeDiff / (1000 * 3600 * 24)) + 1 ;

  var weekday = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
  var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
  var dates = new Array();

  for (var i = 0; i <= date_range; i++) {
     var getDate, getMonth = '';

     if(current_date.getDate() < 10) { getDate = ('0'+ current_date.getDate());}
     else{getDate = current_date.getDate();}

    if(current_date.getMonth() < 9) { getMonth = ('0'+ (current_date.getMonth()+1));}
    else{getMonth = current_date.getMonth();}

    var row_date = {day: getDate, month: getMonth, year: current_date.getFullYear()};
    var fmt_date = {weekDay: weekday[current_date.getDay()], date: getDate, month: months[current_date.getMonth()]};
    var is_weekend = false;
    if (current_date.getDay() == 0 || current_date.getDay() == 6) {
        is_weekend = true;
    }
    dates.push({row_date: row_date, fmt_date: fmt_date, is_weekend: is_weekend});
    current_date.setDate(current_date.getDate() + 1);
 }
 return dates;
}

https://gist.github.com/pranid/3c78f36253cbbc6a41a859c5d718f362.js

How to get a list of sub-folders and their files, ordered by folder-names

Command to put list of all files and folders into a text file is as below:

Eg: dir /b /s | sort > ListOfFilesFolders.txt

How to size an Android view based on its parent's dimensions

I don't know if anyone is still reading this thread or not, but Jeff's solution will only get you halfway there (kinda literally). What his onMeasure will do is display half the image in half the parent. The problem is that calling super.onMeasure prior to the setMeasuredDimension will measure all the children in the view based on the original size, then just cut the view in half when the setMeasuredDimension resizes it.

Instead, you need to call setMeasuredDimension (as required for an onMeasure override) and provide a new LayoutParams for your view, then call super.onMeasure. Remember, your LayoutParams are derived from your view's parent type, not your view's type.

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
   int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
   int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
   this.setMeasuredDimension(parentWidth/2, parentHeight);
   this.setLayoutParams(new *ParentLayoutType*.LayoutParams(parentWidth/2,parentHeight));
   super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

I believe the only time you'll have problems with the parent LayoutParams is if the parent is an AbsoluteLayout (which is deprecated but still sometimes useful).

How to stick text to the bottom of the page?

Try:

.bottom {
    position: fixed;
    bottom: 0;
}

Bootstrap 3: Offset isn't working?

Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.

col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):

<div class="row">
   <div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
   <div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

In my case the issue was caused due to mismatch in .Xauthority file. Which initially showed up with "Invalid MIT-MAGIC-COOKIE-1" error and then "Error: cannot open display: :0.0" afterwards

Regenerating the .Xauthorityfile from the user under which I am running the vncserver and resetting the password with a restart of the vnc service and dbus service fixed the issue for me.

How to pass boolean parameter value in pipeline to downstream jobs?

Things are much easier nowadays: the builtin Snippet Generator supports the 'build' step (I don't know since when though).

how to write an array to a file Java

Just loop over the elements in your array.

Ex:

for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here

Vertical align in bootstrap table

Try:

.table thead th{
   vertical-align:middle;
}

Validating URL in Java

I think the best response is from the user @b1nary.atr0phy. Somehow, I recommend combine the method from the b1nay.atr0phy response with a regex to cover all the possible cases.

public static final URL validateURL(String url, Logger logger) {

        URL u = null;
        try {  
            Pattern regex = Pattern.compile("(?i)^(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))\\.?)(?::\\d{2,5})?(?:[/?#]\\S*)?$");
            Matcher matcher = regex.matcher(url);
            if(!matcher.find()) {
                throw new URISyntaxException(url, "La url no está formada correctamente.");
            }
            u = new URL(url);  
            u.toURI(); 
        } catch (MalformedURLException e) {  
            logger.error("La url no está formada correctamente.");
        } catch (URISyntaxException e) {  
            logger.error("La url no está formada correctamente.");  
        }  

        return u;  

    }

Reloading/refreshing Kendo Grid

Not a single one of these answers gets the fact that read returns a promise, which means you can wait for the data to load before calling refresh.

$('#GridId').data('kendoGrid').dataSource.read().then(function() {
    $('#GridId').data('kendoGrid').refresh();
});

This is unnecessary if your data grab is instant/synchronous, but more than likely it's coming from an endpoint that won't return immediately.

Regex to match only letters

So, I've been reading a lot of the answers, and most of them don't take exceptions into account, like letters with accents or diaeresis (á, à, ä, etc.).

I made a function in typescript that should be pretty much extrapolable to any language that can use RegExp. This is my personal implementation for my use case in typescript. What I basically did is add ranges of letters with each kind of symbol that I wanted to add. I also converted the char to upper case before applying the RegExp, which saves me some work.

function isLetter(char: string): boolean {
  return char.toUpperCase().match('[A-ZÀ-ÚÄ-Ü\s]+') !== null;
}

If you want to add another range of letters with another kind of accent, just add it to the regex. Same goes for special symbols.

I implemented this function with TDD and I can confirm this works with, at least, the following cases:

    character | isLetter
    ${'A'}    | ${true}
    ${'e'}    | ${true}
    ${'Á'}    | ${true}
    ${'ü'}    | ${true}
    ${'ù'}    | ${true}
    ${'û'}    | ${true}
    ${'('}    | ${false}
    ${'^'}    | ${false}
    ${"'"}    | ${false}
    ${'`'}    | ${false}

UIScrollView Scrollable Content Size Ambiguity

You just have to make sure that there is a way to make a continuous line of constraints from the top to the bottom of the scrollview. [-X-X-X]

In my case - a horizontally scrolling scroll view - I also needed to add width and height constraints for each child of the scroll view, although Apple's technical note doesn't tell you this.

.gitignore after commit

However, will it automatically remove these committed files from the repository?

No.

The 'best' recipe to do this is using git filter-branch as written about here:

The man page for git-filter-branch contains comprehensive examples.

Note You'll be re-writing history. If you had published any revisions containing the accidentally added files, this could create trouble for users of those public branches. Inform them, or perhaps think about how badly you need to remove the files.

Note In the presence of tags, always use the --tag-name-filter cat option to git filter-branch. It never hurts and will save you the head-ache when you realize later taht you needed it

NSRange to Range<String.Index>

In the accepted answer I find the optionals cumbersome. This works with Swift 3 and seems to have no problem with emojis.

func textField(_ textField: UITextField, 
      shouldChangeCharactersIn range: NSRange, 
      replacementString string: String) -> Bool {

  guard let value = textField.text else {return false} // there may be a reason for returning true in this case but I can't think of it
  // now value is a String, not an optional String

  let valueAfterChange = (value as NSString).replacingCharacters(in: range, with: string)
  // valueAfterChange is a String, not an optional String

  // now do whatever processing is required

  return true  // or false, as required
}

Apache shows PHP code instead of executing it

I found this to solve my related problem. I added it to the relevant <Directory> section:

<IfModule mod_php5.c>
    php_admin_flag engine on
</IfModule>

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

In a previous answer, it was suggested to use this line of code for .Net 4.5:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5

I would encourage you to OR that value in to whatever the existing values are like this:

ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; // .NET 4.5

If you look at the list of values, you notice that they are a power of two. This way, in the future when things shift to TLS 2.0 for example, your code will still work.

Find ALL tweets from a user (not just the first 3,200)

You can use twitter search page to bypass 3,200 limit. However you have to scroll down many times in the search results page. For example, I searched tweets from @beyinsiz_adam. This is the link of search results: https://twitter.com/search?q=from%3Abeyinsiz_adam&src=typd&f=realtime

Now in order to scroll down many times, you can use the following javascript code.

    var myVar=setInterval(function(){myTimer()},1000);
    function myTimer() {
        window.scrollTo(0,document.body.scrollHeight);
    }

Just run it in the FireBug console. And wait some time to load all tweets.

How to remove unused C/C++ symbols with GCC and ld?

You can use strip binary on object file(eg. executable) to strip all symbols from it.

Note: it changes file itself and don't create copy.

Plot size and resolution with R markdown, knitr, pandoc, beamer

Figure sizes are specified in inches and can be included as a global option of the document output format. For example:

---
title: "My Document"
output:
  html_document:
    fig_width: 6
    fig_height: 4
---

And the plot's size in the graphic device can be increased at the chunk level:

```{r, fig.width=14, fig.height=12}          #Expand the plot width to 14 inches

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

You can also use the out.width and out.height arguments to directly define the size of the plot in the output file:

```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels

ggplot(aes(x=mycolumn1, y=mycolumn2)) +     #specify the x and y aesthetic
geom_line(size=2) +                         #makes the line thicker
theme_grey(base_size = 25)                  #increases the size of the font
```

Renaming Columns in an SQL SELECT Statement

You can alias the column names one by one, like so

SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2` 
FROM `foobar`

Edit You can access INFORMATION_SCHEMA.COLUMNS directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(

select CONCAT('Foobar_', COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'Foobar'

Good MapReduce examples

Map reduce is a framework that was developed to process massive amounts of data efficiently. For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these.

For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases. Map Reduce provides a cluster based implementation where data is processed in a distributed manner

Here is a wikipedia article explaining what map-reduce is all about

Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and a well used use-case.

Personally, found this link quite useful to understand the concept

Copying the explanation provided in the blog (In case the link goes stale)

Finding Friends

MapReduce is a framework originally developed at Google that allows for easy large scale distributed computing across a number of domains. Apache Hadoop is an open source implementation.

I'll gloss over the details, but it comes down to defining two functions: a map function and a reduce function. The map function takes a value and outputs key:value pairs. For instance, if we define a map function that takes a string and outputs the length of the word as the key and the word itself as the value then map(steve) would return 5:steve and map(savannah) would return 8:savannah. You may have noticed that the map function is stateless and only requires the input value to compute it's output value. This allows us to run the map function against values in parallel and provides a huge advantage. Before we get to the reduce function, the mapreduce framework groups all of the values together by key, so if the map functions output the following key:value pairs:

3 : the
3 : and
3 : you
4 : then
4 : what
4 : when
5 : steve
5 : where
8 : savannah
8 : research

They get grouped as:

3 : [the, and, you]
4 : [then, what, when]
5 : [steve, where]
8 : [savannah, research]

Each of these lines would then be passed as an argument to the reduce function, which accepts a key and a list of values. In this instance, we might be trying to figure out how many words of certain lengths exist, so our reduce function will just count the number of items in the list and output the key with the size of the list, like:

3 : 3
4 : 3
5 : 2
8 : 2

The reductions can also be done in parallel, again providing a huge advantage. We can then look at these final results and see that there were only two words of length 5 in our corpus, etc...

The most common example of mapreduce is for counting the number of times words occur in a corpus. Suppose you had a copy of the internet (I've been fortunate enough to have worked in such a situation), and you wanted a list of every word on the internet as well as how many times it occurred.

The way you would approach this would be to tokenize the documents you have (break it into words), and pass each word to a mapper. The mapper would then spit the word back out along with a value of 1. The grouping phase will take all the keys (in this case words), and make a list of 1's. The reduce phase then takes a key (the word) and a list (a list of 1's for every time the key appeared on the internet), and sums the list. The reducer then outputs the word, along with it's count. When all is said and done you'll have a list of every word on the internet, along with how many times it appeared.

Easy, right? If you've ever read about mapreduce, the above scenario isn't anything new... it's the "Hello, World" of mapreduce. So here is a real world use case (Facebook may or may not actually do the following, it's just an example):

Facebook has a list of friends (note that friends are a bi-directional thing on Facebook. If I'm your friend, you're mine). They also have lots of disk space and they serve hundreds of millions of requests everyday. They've decided to pre-compute calculations when they can to reduce the processing time of requests. One common processing request is the "You and Joe have 230 friends in common" feature. When you visit someone's profile, you see a list of friends that you have in common. This list doesn't change frequently so it'd be wasteful to recalculate it every time you visited the profile (sure you could use a decent caching strategy, but then I wouldn't be able to continue writing about mapreduce for this problem). We're going to use mapreduce so that we can calculate everyone's common friends once a day and store those results. Later on it's just a quick lookup. We've got lots of disk, it's cheap.

Assume the friends are stored as Person->[List of Friends], our friends list is then:

A -> B C D
B -> A C D E
C -> A B D E
D -> A B C E
E -> B C D

Each line will be an argument to a mapper. For every friend in the list of friends, the mapper will output a key-value pair. The key will be a friend along with the person. The value will be the list of friends. The key will be sorted so that the friends are in order, causing all pairs of friends to go to the same reducer. This is hard to explain with text, so let's just do it and see if you can see the pattern. After all the mappers are done running, you'll have a list like this:

For map(A -> B C D) :

(A B) -> B C D
(A C) -> B C D
(A D) -> B C D

For map(B -> A C D E) : (Note that A comes before B in the key)

(A B) -> A C D E
(B C) -> A C D E
(B D) -> A C D E
(B E) -> A C D E
For map(C -> A B D E) :

(A C) -> A B D E
(B C) -> A B D E
(C D) -> A B D E
(C E) -> A B D E
For map(D -> A B C E) :

(A D) -> A B C E
(B D) -> A B C E
(C D) -> A B C E
(D E) -> A B C E
And finally for map(E -> B C D):

(B E) -> B C D
(C E) -> B C D
(D E) -> B C D
Before we send these key-value pairs to the reducers, we group them by their keys and get:

(A B) -> (A C D E) (B C D)
(A C) -> (A B D E) (B C D)
(A D) -> (A B C E) (B C D)
(B C) -> (A B D E) (A C D E)
(B D) -> (A B C E) (A C D E)
(B E) -> (A C D E) (B C D)
(C D) -> (A B C E) (A B D E)
(C E) -> (A B D E) (B C D)
(D E) -> (A B C E) (B C D)

Each line will be passed as an argument to a reducer. The reduce function will simply intersect the lists of values and output the same key with the result of the intersection. For example, reduce((A B) -> (A C D E) (B C D)) will output (A B) : (C D) and means that friends A and B have C and D as common friends.

The result after reduction is:

(A B) -> (C D)
(A C) -> (B D)
(A D) -> (B C)
(B C) -> (A D E)
(B D) -> (A C E)
(B E) -> (C D)
(C D) -> (A B E)
(C E) -> (B D)
(D E) -> (B C)

Now when D visits B's profile, we can quickly look up (B D) and see that they have three friends in common, (A C E).

Change tab bar tint color on iOS 7

What finally worked for me was:

[self.tabBar setTintColor:[UIColor redColor]];
[self.tabBar setBarTintColor:[UIColor yellowColor]];

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

A .pl is a single script.

In .pm (Perl Module) you have functions that you can use from other Perl scripts:

A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

Actually, I've seen this sort of thing used in BIRT reports. The query passed to the BIRT runtime is of the form:

select a,b,c from t where a = ?

and the '?' is replaced at runtime by an actual parameter value selected from a drop-down box. The choices in the drop-down are given by:

select distinct a from t
union all
select '*' from sysibm.sysdummy1

so that you get all possible values plus "*". If the user selects "*" from the drop down box (meaning all values of a should be selected), the query has to be modified (by Javascript) before being run.

Since the "?" is a positional parameter and MUST remain there for other things to work, the Javascript modifies the query to be:

select a,b,c from t where ((a = ?) or (1==1))

That basically removes the effect of the where clause while still leaving the positional parameter in place.

I've also seen the AND case used by lazy coders whilst dynamically creating an SQL query.

Say you have to dynamically create a query that starts with select * from t and checks:

  • the name is Bob; and
  • the salary is > $20,000

some people would add the first with a WHERE and subsequent ones with an AND thus:

select * from t where name = 'Bob' and salary > 20000

Lazy programmers (and that's not necessarily a bad trait) wouldn't distinguish between the added conditions, they'd start with select * from t where 1=1 and just add AND clauses after that.

select * from t where 1=1 and name = 'Bob' and salary > 20000

How to get the onclick calling object?

The easiest way is to pass this to the click123 function or you can also do something like this(cross-browser):

function click123(e){
  e = e || window.event;
  var src = e.target || e.srcElement;
  //src element is the eventsource
}

Reload an iframe with jQuery

You need to use

[0].src

to find the source of the iframe and its URL needs to be on the same domain of the parent.

setInterval(refreshMe, 5000);
function refreshMe() {
    $("#currentElement")[0].src = $("#currentElement")[0].src;   
}

How can I group by date time column without taking time into consideration

In pre Sql 2008 By taking out the date part:

GROUP BY CONVERT(CHAR(8),DateTimeColumn,10)

Delete all local git branches

If you don't need to go through Git itself, you can also delete heads under .git/refs/heads manually or programmatically. The following should work with minimal tweaking under Bash:

shopt -s extglob
rm -rf .git/refs/heads/!(master)

This will delete every local branch except your master branch. Since your upstream branches are stored under .git/refs/remotes, they will remain untouched.

If you are not using Bash, or want to recurse a lot of Git repositories at once, you can do something similar with GNU find:

find . \
    -path remotes -path logs -prune -o \
    -wholename \*.git/refs/heads/\* \! -name master -print0 |
xargs -0 rm -rf

The find solution is probably more portable, but pruning paths and filenames is tricky and potentially more error-prone.

PostgreSQL psql terminal command

Use \x Example from postgres manual:

    postgres=# \x
    postgres=# SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 3;
    -[ RECORD 1 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE branches SET bbalance = bbalance + $1 WHERE bid = $2;
    calls      | 3000
    total_time | 20.716706
    rows       | 3000
    -[ RECORD 2 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE tellers SET tbalance = tbalance + $1 WHERE tid = $2;
    calls      | 3000
    total_time | 17.1107649999999
    rows       | 3000
    -[ RECORD 3 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE accounts SET abalance = abalance + $1 WHERE aid = $2;
    calls      | 3000
    total_time | 0.645601
    rows       | 3000

Convert char* to string C++

std::string str;
char* const s = "test";

str.assign(s);

string& assign (const char* s); => signature FYR

Reference/s here.

CSS 100% height with padding/margin

Frank's example confused me a bit - it didn't work in my case because I didn't understand positioning well enough yet. It's important to note that the parent container element needs to have a non-static position (he mentioned this but I overlooked it, and it wasn't in his example).

Here's an example where the child - given padding and a border - uses absolute positioning to fill the parent 100%. The parent uses relative positioning in order to provide a point of reference for the child's position while remaining in the normal flow - the next element "more-content" is not affected:

#box {
    position: relative;
    height: 300px;
    width: 600px;
}

#box p {
    position: absolute;
    border-style: dashed;
    padding: 1em;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
<div id="box">
  <p>100% height and width!</p>
</div>
<div id="more-content">
</div>

A useful link for quickly learning CSS positioning

Creating a SOAP call using PHP with an XML body

First off, you have to specify you wish to use Document Literal style:

$client = new SoapClient(NULL, array(
    'location' => 'https://example.com/path/to/service',
    'uri' => 'http://example.com/wsdl',
    'trace' => 1,
    'use' => SOAP_LITERAL)
);

Then, you need to transform your data into a SoapVar; I've written a simple transform function:

function soapify(array $data)
{
        foreach ($data as &$value) {
                if (is_array($value)) {
                        $value = soapify($value);
                }
        }

        return new SoapVar($data, SOAP_ENC_OBJECT);
}

Then, you apply this transform function onto your data:

$data = soapify(array(
    'Acquirer' => array(
        'Id' => 'MyId',
        'UserId' => 'MyUserId',
        'Password' => 'MyPassword',
    ),
));

Finally, you call the service passing the Data parameter:

$method = 'Echo';

$result = $client->$method(new SoapParam($data, 'Data'));

Using Python 3 in virtualenv

For those of you who are using pipenv and want to install specific version:

pipenv install --python 3.6

How to add elements of a Java8 stream into an existing List

NOTE: nosid's answer shows how to add to an existing collection using forEachOrdered(). This is a useful and effective technique for mutating existing collections. My answer addresses why you shouldn't use a Collector to mutate an existing collection.

The short answer is no, at least, not in general, you shouldn't use a Collector to modify an existing collection.

The reason is that collectors are designed to support parallelism, even over collections that aren't thread-safe. The way they do this is to have each thread operate independently on its own collection of intermediate results. The way each thread gets its own collection is to call the Collector.supplier() which is required to return a new collection each time.

These collections of intermediate results are then merged, again in a thread-confined fashion, until there is a single result collection. This is the final result of the collect() operation.

A couple answers from Balder and assylias have suggested using Collectors.toCollection() and then passing a supplier that returns an existing list instead of a new list. This violates the requirement on the supplier, which is that it return a new, empty collection each time.

This will work for simple cases, as the examples in their answers demonstrate. However, it will fail, particularly if the stream is run in parallel. (A future version of the library might change in some unforeseen way that will cause it to fail, even in the sequential case.)

Let's take a simple example:

List<String> destList = new ArrayList<>(Arrays.asList("foo"));
List<String> newList = Arrays.asList("0", "1", "2", "3", "4", "5");
newList.parallelStream()
       .collect(Collectors.toCollection(() -> destList));
System.out.println(destList);

When I run this program, I often get an ArrayIndexOutOfBoundsException. This is because multiple threads are operating on ArrayList, a thread-unsafe data structure. OK, let's make it synchronized:

List<String> destList =
    Collections.synchronizedList(new ArrayList<>(Arrays.asList("foo")));

This will no longer fail with an exception. But instead of the expected result:

[foo, 0, 1, 2, 3]

it gives weird results like this:

[foo, 2, 3, foo, 2, 3, 1, 0, foo, 2, 3, foo, 2, 3, 1, 0, foo, 2, 3, foo, 2, 3, 1, 0, foo, 2, 3, foo, 2, 3, 1, 0]

This is the result of the thread-confined accumulation/merging operations I described above. With a parallel stream, each thread calls the supplier to get its own collection for intermediate accumulation. If you pass a supplier that returns the same collection, each thread appends its results to that collection. Since there is no ordering among the threads, results will be appended in some arbitrary order.

Then, when these intermediate collections are merged, this basically merges the list with itself. Lists are merged using List.addAll(), which says that the results are undefined if the source collection is modified during the operation. In this case, ArrayList.addAll() does an array-copy operation, so it ends up duplicating itself, which is sort-of what one would expect, I guess. (Note that other List implementations might have completely different behavior.) Anyway, this explains the weird results and duplicated elements in the destination.

You might say, "I'll just make sure to run my stream sequentially" and go ahead and write code like this

stream.collect(Collectors.toCollection(() -> existingList))

anyway. I'd recommend against doing this. If you control the stream, sure, you can guarantee that it won't run in parallel. I expect that a style of programming will emerge where streams get handed around instead of collections. If somebody hands you a stream and you use this code, it'll fail if the stream happens to be parallel. Worse, somebody might hand you a sequential stream and this code will work fine for a while, pass all tests, etc. Then, some arbitrary amount of time later, code elsewhere in the system might change to use parallel streams which will cause your code to break.

OK, then just make sure to remember to call sequential() on any stream before you use this code:

stream.sequential().collect(Collectors.toCollection(() -> existingList))

Of course, you'll remember to do this every time, right? :-) Let's say you do. Then, the performance team will be wondering why all their carefully crafted parallel implementations aren't providing any speedup. And once again they'll trace it down to your code which is forcing the entire stream to run sequentially.

Don't do it.

JavaFX Application Icon

I used this in my application

Image icon = new Image(getClass().getResourceAsStream("icon.png"));
window.getIcons().add(icon);

Here window is the stage.

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

<input type="number" onkeydown="return FilterInput(event)" onpaste="handlePaste(event)"  >

function FilterInput(event) {
    var keyCode = ('which' in event) ? event.which : event.keyCode;

    isNotWanted = (keyCode == 69 || keyCode == 101);
    return !isNotWanted;
};
function handlePaste (e) {
    var clipboardData, pastedData;

    // Get pasted data via clipboard API
    clipboardData = e.clipboardData || window.clipboardData;
    pastedData = clipboardData.getData('Text').toUpperCase();

    if(pastedData.indexOf('E')>-1) {
        //alert('found an E');
        e.stopPropagation();
        e.preventDefault();
    }
};

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The only thing that worked for me was creating a new application in the IIS, mapping it to exactly the same physical path, and changing only the authentication to be Anonymous.

Typescript: difference between String and string

The two types are distinct in JavaScript as well as TypeScript - TypeScript just gives us syntax to annotate and check types as we go along.

String refers to an object instance that has String.prototype in its prototype chain. You can get such an instance in various ways e.g. new String('foo') and Object('foo'). You can test for an instance of the String type with the instanceof operator, e.g. myString instanceof String.

string is one of JavaScript's primitive types, and string values are primarily created with literals e.g. 'foo' and "bar", and as the result type of various functions and operators. You can test for string type using typeof myString === 'string'.

The vast majority of the time, string is the type you should be using - almost all API interfaces that take or return strings will use it. All JS primitive types will be wrapped (boxed) with their corresponding object types when using them as objects, e.g. accessing properties or calling methods. Since String is currently declared as an interface rather than a class in TypeScript's core library, structural typing means that string is considered a subtype of String which is why your first line passes compilation type checks.

How get an apostrophe in a string in javascript

You can put an apostrophe in a single quoted JavaScript string by escaping it with a backslash, like so:

theAnchorText = 'I\'m home';

Bootstrap 3.0 Popovers and tooltips

Working with BOOTSTRAP 3 : Short and Simple

Check - JS Fiddle

HTML

<div id="myDiv">
<button class="btn btn-large btn-danger" data-toggle="tooltip" data-placement="top" title="" data-original-title="Tooltip on top">Tooltip on top</button>    
</div>

Javascript

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

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

I get the error above when I try to log into MYSQL after installing it using brew, I am running MacOs, Oh yea I also noticed mysql is running I have restarted numerous times with no luck resolving the issue along with removing mysql and numerous reinstalls!

So simple I could slap myself, no but really, I solved this by CD into the temp folder that contains mysqlx.sock and mysql.sock.lock files, I deleted the single sock.lock file only and this solved my issue after doing so and I can log into mysql using the mysql -uroot command. Here are the commands I used. (this issue had me hung up for a while)

~ cd /tmp 

/tmp ls 

(this will list all the sock files in the temp folder, output shown below)

com.apple.launchd.8AgGW2s9Bb mysql.sock.lock
com.apple.launchd.batxrSISAJ mysqlx.sock
com.apple.launchd.cRCaxtT41m mysqlx.sock.lock
com.google.Keystone          powerlog

then run

rm -R mysql.sock.lock 

(use command above to remove the sock.lock file from the /tmp directory this resolved my issue)

hope this helped :)

Python Dictionary contains List as Value - How to update?

why not just skip .get altogether and do something like this?:

for x in range(len(dictionary["C1"]))
    dictionary["C1"][x] += 10

String split on new line, tab and some number of spaces

If you look at the documentation for str.split:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

In other words, if you're trying to figure out what to pass to split to get '\n\tName: Jane Smith' to ['Name:', 'Jane', 'Smith'], just pass nothing (or None).

This almost solves your whole problem. There are two parts left.

First, you've only got two fields, the second of which can contain spaces. So, you only want one split, not as many as possible. So:

s.split(None, 1)

Next, you've still got those pesky colons. But you don't need to split on them. At least given the data you've shown us, the colon always appears at the end of the first field, with no space before and always space after, so you can just remove it:

key, value = s.split(None, 1)
key = key[:-1]

There are a million other ways to do this, of course; this is just the one that seems closest to what you were already trying.

If statement with String comparison fails

If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals() or equalsIgnoreCase() for that.

Installing Java on OS X 10.9 (Mavericks)

The new Mavericks (10.9) showed me the "Requesting install", but nothing happened.

The solution was to manually download and install the official Java package for OS X, which is in Java for OS X 2013-005.

Update: As mentioned in the comments below, there is a newer version of this same package:

Java for OS X 2014-001

Java for OS X 2014-001 (Correcting dead line above)

Java for OS X 2014-001 includes installation improvements, and supersedes all previous versions of Java for OS X. This package installs the same version of Java 6 included in Java for OS X 2013-005.

Convert datetime value into string

Try this:

concat(left(datefield,10),left(timefield,8))
  • 10 char on date field based on full date yyyy-MM-dd.

  • 8 char on time field based on full time hh:mm:ss.

It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.

Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.

Validation of radio button group using jQuery validation plugin

use the following rule for validating radio button group selection

myRadioGroupName : {required :true}

myRadioGroupName is the value you have given to name attribute

What is recursion and when should I use it?

You want to use it anytime you have a tree structure. It is very useful in reading XML.

row-level trigger vs statement-level trigger

The main difference between statement level trigger is below :

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

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

Owl Carousel Won't Autoplay

You should set both autoplay and autoplayTimeout properties. I used this code, and it works for me:

$('.owl-carousel').owlCarousel({
                autoplay: true,
                autoplayTimeout: 5000,
                navigation: false,
                margin: 10,
                responsive: {
                    0: {
                        items: 1
                    },
                    600: {
                        items: 2
                    },
                    1000: {
                        items: 2
                    }
                }
            })

Best practice to look up Java Enum

update: As GreenTurtle correctly remarked, the following is wrong


I would just write

boolean result = Arrays.asList(FooEnum.values()).contains("Foo");

This is possibly less performant than catching a runtime exception, but makes for much cleaner code. Catching such exceptions is always a bad idea, since it is prone to misdiagnosis. What happens when the retrieval of the compared value itself causes an IllegalArgumentException ? This would then be treaten like a non matching value for the enumerator.

Read line with Scanner

Try to use r.hasNext() instead of r.hasNextLine():

while(r.hasNext()) {
        scan = r.next();

How to simulate "Press any key to continue?"

If you look up kbhit() function on MSDN now, it says the function is deprecated. Use _kbhit() instead.

#include <conio.h>
int main()
{
    _kbhit();
    return 0;
}

How can I check if an ip is in a network in Python?

I don't know of anything in the standard library, but PySubnetTree is a Python library that will do subnet matching.

Java escape JSON String?

I would use a library to create your JSON String for you. Some options are:

This will make dealing with escaping much easier. An example (using org.json) would be:

JSONObject obj = new JSONObject();

obj.put("id", userID);
obj.put("type", methoden);
obj.put("msg", msget);

// etc.

final String json = obj.toString(); // <-- JSON string

How can I see normal print output created during pytest run?

If you are using PyCharm IDE, then you can run that individual test or all tests using Run toolbar. The Run tool window displays output generated by your application and you can see all the print statements in there as part of test output.

ANTLR: Is there a simple example?

ANTLR mega tutorial by Gabriele Tomassetti is very helpful

It has grammar examples, examples of visitors in different languages (Java, JavaScript, C# and Python) and many other things. Highly recommended.

EDIT: other useful articles by Gabriele Tomassetti on ANTLR

How to import a Python class that is in a directory above?

import sys
sys.path.append("..") # Adds higher directory to python modules path.