Programs & Examples On #Superset

console.log not working in Angular2 Component (Typescript)

The console.log should be wrapped in a function , the "default" function for every class is its constructor so it should be declared there.

import { Component } from '@angular/core';
console.log("Hello1");

 @Component({
  selector: 'hello-console',
})
    export class App {
     s: string = "Hello2";
    constructor(){
     console.log(s); 
    }

}

android.view.InflateException: Binary XML file: Error inflating class fragment

I have the same problem because I did not implement the listener. See the following code with /*Add This!*/.

public class SomeActivity extends AppCompatActivity
        implements BlankFragment.OnFragmentInteractionListener /*Add this!*/ 
{
    @Override                                                  /*Add This!*/
    public void onFragmentInteraction(Uri uri){                /*Add This!*/
    }                                                          /*Add This!*/
}

FYI, my fragment class is something like the following:

public class SomeFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }
}

Edit:

I also notice this same error message under another circumstances when there is an exception in the onCreate function of the Fragment. I have something as the following:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    int ID = getArguments().getInt("val");

    return rootView;
} 

Because I reuse this fragment, I total forget to set arguments. Then the result of getArguments() is null. Obviously, I get a null pointer exception here. I will suggest you keep an eye on mistakes like this as well.

TypeScript and field initializers

Updated 07/12/2016: Typescript 2.1 introduces Mapped Types and provides Partial<T>, which allows you to do this....

class Person {
    public name: string = "default"
    public address: string = "default"
    public age: number = 0;

    public constructor(init?:Partial<Person>) {
        Object.assign(this, init);
    }
}

let persons = [
    new Person(),
    new Person({}),
    new Person({name:"John"}),
    new Person({address:"Earth"}),    
    new Person({age:20, address:"Earth", name:"John"}),
];

Original Answer:

My approach is to define a separate fields variable that you pass to the constructor. The trick is to redefine all the class fields for this initialiser as optional. When the object is created (with its defaults) you simply assign the initialiser object onto this;

export class Person {
    public name: string = "default"
    public address: string = "default"
    public age: number = 0;

    public constructor(
        fields?: {
            name?: string,
            address?: string,
            age?: number
        }) {
        if (fields) Object.assign(this, fields);
    }
}

or do it manually (bit more safe):

if (fields) {
    this.name = fields.name || this.name;       
    this.address = fields.address || this.address;        
    this.age = fields.age || this.age;        
}

usage:

let persons = [
    new Person(),
    new Person({name:"Joe"}),
    new Person({
        name:"Joe",
        address:"planet Earth"
    }),
    new Person({
        age:5,               
        address:"planet Earth",
        name:"Joe"
    }),
    new Person(new Person({name:"Joe"})) //shallow clone
]; 

and console output:

Person { name: 'default', address: 'default', age: 0 }
Person { name: 'Joe', address: 'default', age: 0 }
Person { name: 'Joe', address: 'planet Earth', age: 0 }
Person { name: 'Joe', address: 'planet Earth', age: 5 }
Person { name: 'Joe', address: 'default', age: 0 }   

This gives you basic safety and property initialization, but its all optional and can be out-of-order. You get the class's defaults left alone if you don't pass a field.

You can also mix it with required constructor parameters too -- stick fields on the end.

About as close to C# style as you're going to get I think (actual field-init syntax was rejected). I'd much prefer proper field initialiser, but doesn't look like it will happen yet.

For comparison, If you use the casting approach, your initialiser object must have ALL the fields for the type you are casting to, plus don't get any class specific functions (or derivations) created by the class itself.

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This appears to be a UTF-8 encoding issue that may have been caused by a double-UTF8-encoding of the database file contents.

This situation could happen due to factors such as the character set that was or was not selected (for instance when a database backup file was created) and the file format and encoding database file was saved with.

I have seen these strange UTF-8 characters in the following scenario (the description may not be entirely accurate as I no longer have access to the database in question):

  • As I recall, there the database and tables had a "uft8_general_ci" collation.
  • Backup is made of the database.
  • Backup file is opened on Windows in UNIX file format and with ANSI encoding.
  • Database is restored on a new MySQL server by copy-pasting the contents from the database backup file into phpMyAdmin.

Looking into the file contents:

  • Opening the SQL backup file in a text editor shows that the SQL backup file has strange characters such as "sÃ¥". On a side note, you may get different results if opening the same file in another editor. I use TextPad here but opening the same file in SublimeText said "sÃ¥" because SublimeText correctly UTF8-encoded the file -- still, this is a bit confusing when you start trying to fix the issue in PHP because you don't see the right data in SublimeText at first. Anyways, that can be resolved by taking note of which encoding your text editor is using when presenting the file contents.
  • The strange characters are double-encoded UTF-8 characters, so in my case the first "Ã" part equals "Ã" and "Â¥" = "¥" (this is my first "encoding"). THe "Ã¥" characters equals the UTF-8 character for "å" (this is my second encoding).

So, the issue is that "false" (UTF8-encoded twice) utf-8 needs to be converted back into "correct" utf-8 (only UTF8-encoded once).

Trying to fix this in PHP turns out to be a bit challenging:

utf8_decode() is not able to process the characters.

// Fails silently (as in - nothing is output)
$str = "så";

$str = utf8_decode($str);
printf("\n%s", $str);

$str = utf8_decode($str);
printf("\n%s", $str);

iconv() fails with "Notice: iconv(): Detected an illegal character in input string".

echo iconv("UTF-8", "ISO-8859-1", "så");

Another fine and possible solution fails silently too in this scenario

$str = "så";
echo html_entity_decode(htmlentities($str, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-15');

mb_convert_encoding() silently: #

$str = "så";
echo mb_convert_encoding($str, 'ISO-8859-15', 'UTF-8');
// (No output)

Trying to fix the encoding in MySQL by converting the MySQL database characterset and collation to UTF-8 was unsuccessfully:

ALTER DATABASE myDatabase CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE myTable CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

I see a couple of ways to resolve this issue.

The first is to make a backup with correct encoding (the encoding needs to match the actual database and table encoding). You can verify the encoding by simply opening the resulting SQL file in a text editor.

The other is to replace double-UTF8-encoded characters with single-UTF8-encoded characters. This can be done manually in a text editor. To assist in this process, you can manually pick incorrect characters from Try UTF-8 Encoding Debugging Chart (it may be a matter of replacing 5-10 errors).

Finally, a script can assist in the process:

    $str = "så";
    // The two arrays can also be generated by double-encoding values in the first array and single-encoding values in the second array.
    $str = str_replace(["Ã","Â¥"], ["Ã","¥"], $str); 
    $str = utf8_decode($str);
    echo $str;
    // Output: "så" (correct)

Add new attribute (element) to JSON object using JavaScript

With ECMAScript since 2015 you can use Spread Syntax ( …three dots):

let  people = { id: 4 ,firstName: 'John'};
people = { ...people, secondName: 'Fogerty'};

It's allow you to add sub objects:

people = { ...people, city: { state: 'California' }};

the result would be:

{  
   "id": 4,
   "firstName": "John",
   "secondName": "Forget",
   "city": {  
      "state": "California"
   }
}

You also can merge objects:

var mergedObj = { ...obj1, ...obj2 };

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

I found this solution which solved the problem for me: Removing all entries in your *.csproj that fall into:

<manifestcertificatethumbprint>...</manifestcertificatethumbprint>
<manifestkeyfile>...</manifestkeyfile>
<generatemanifests>...</generatemanifests>
<signmanifests>...</signmanifests>

TypeError: 'undefined' is not an object

I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?

You could check in the following way (extra = and making length a truthy evaluation)

if (typeof(sub.from) !== 'undefined' && sub.from.length) {

[update]

I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:

for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
            mainid = sub.from[i]['id'];
            var sub = afcHelper_Submissions[mainid]; // <== re setting sub

My guess is that the error is not on the if statement but on the for(i... statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).

How to encrypt String in Java

Update on 12-DEC-2019

Unlike some other modes like CBC, GCM mode does not require the IV to be unpredictable. The only requirement is that the IV has to be unique for each invocation with a given key. If it repeats once for a given key, security can be compromised. An easy way to achieve this is to use a random IV from a strong pseudo random number generator as shown below.

Using a sequence or timestamp as IV is also possible, but it may not be as trivial as it may sound. For example, if the system does not correctly keep track of the sequences already used as IV in a persistent store, an invocation may repeat an IV after a system reboot. Likewise, there is no perfect clock. Computer clock readjusts etc.

Also, the key should be rotated after every 2^32 invocations. For further details on the IV requirement, refer to this answer and the NIST recommendations.


This is the encryption & decryption code I just wrote in Java 8 considering the following points. Hope someone would find this useful:

  1. Encryption Algorithm: Block cipher AES with 256 bits key is considered secure enough. To encrypt a complete message, a mode needs to be selected. Authenticated encryption (which provides both confidentiality and integrity) is recommended. GCM, CCM and EAX are most commonly used authenticated encryption modes. GCM is usually preferred and it performs well in Intel architectures which provide dedicated instructions for GCM. All these three modes are CTR-based (counter-based) modes and therefore they do not need padding. As a result they are not vulnerable to padding related attacks

  2. An initialization Vector (IV) is required for GCM. The IV is not a secret. The only requirement being it has to be random or unpredictable. In Java, the SecuredRandom class is meant to produce cryptographically strong pseudo random numbers. The pseudo-random number generation algorithm can be specified in the getInstance() method. However, since Java 8, the recommended way is to use getInstanceStrong() method which will use the strongest algorithm configured and provided by the Provider

  3. NIST recommends 96 bit IV for GCM to promote interoperability, efficiency, and simplicity of design

  4. To ensure additional security, in the following implementation SecureRandom is re-seeded after producing every 2^16 bytes of pseudo random byte generation

  5. The recipient needs to know the IV to be able to decrypt the cipher text. Therefore the IV needs to be transferred along with the cipher text. Some implementations send the IV as AD (Associated Data) which means that the authentication tag will be calculated on both the cipher text and the IV. However, that is not required. The IV can be simply pre-pended with the cipher text because if the IV is changed during transmission due to a deliberate attack or network/file system error, the authentication tag validation will fail anyway

  6. Strings should not be used to hold the clear text message or the key as Strings are immutable and thus we cannot clear them after use. These uncleared Strings then linger in the memory and may show up in a heap dump. For the same reason, the client calling these encryption or decryption methods should clear all the variables or arrays holding the message or the key after they are no longer needed.

  7. No provider is hard coded in the code following the general recommendations

  8. Finally for transmission over network or storage, the key or the cipher text should be encoded using Base64 encoding. The details of Base64 can be found here. The Java 8 approach should be followed

Byte arrays can be cleared using:

Arrays.fill(clearTextMessageByteArray, Byte.MIN_VALUE);

However, as of Java 8, there is no easy way to clear SecretKeyspec and SecretKey as the implementations of these two interfaces do not seem to have implemented the method destroy() of the interface Destroyable. In the following code, a separate method is written to clear the SecretKeySpec and SecretKey using reflection.

Key should be generated using one of the two approaches mentioned below.

Note that keys are secrets like passwords, but unlike passwords which are meant for human use, keys are meant to be used by cryptographic algorithms and hence should be generated using the above way only.

package com.sapbasu.javastudy;

import java.lang.reflect.Field;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Crypto {

  private static final int AUTH_TAG_SIZE = 128; // bits

  // NIST recommendation: "For IVs, it is recommended that implementations
  // restrict support to the length of 96 bits, to
  // promote interoperability, efficiency, and simplicity of design."
  private static final int IV_LEN = 12; // bytes

  // number of random number bytes generated before re-seeding
  private static final double PRNG_RESEED_INTERVAL = Math.pow(2, 16);

  private static final String ENCRYPT_ALGO = "AES/GCM/NoPadding";

  private static final List<Integer> ALLOWED_KEY_SIZES = Arrays
      .asList(new Integer[] {128, 192, 256}); // bits

  private static SecureRandom prng;

  // Used to keep track of random number bytes generated by PRNG
  // (for the purpose of re-seeding)
  private static int bytesGenerated = 0;

  public byte[] encrypt(byte[] input, SecretKeySpec key) throws Exception {

    Objects.requireNonNull(input, "Input message cannot be null");
    Objects.requireNonNull(key, "key cannot be null");

    if (input.length == 0) {
      throw new IllegalArgumentException("Length of message cannot be 0");
    }

    if (!ALLOWED_KEY_SIZES.contains(key.getEncoded().length * 8)) {
      throw new IllegalArgumentException("Size of key must be 128, 192 or 256");
    }

    Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);

    byte[] iv = getIV(IV_LEN);

    GCMParameterSpec gcmParamSpec = new GCMParameterSpec(AUTH_TAG_SIZE, iv);

    cipher.init(Cipher.ENCRYPT_MODE, key, gcmParamSpec);
    byte[] messageCipher = cipher.doFinal(input);

    // Prepend the IV with the message cipher
    byte[] cipherText = new byte[messageCipher.length + IV_LEN];
    System.arraycopy(iv, 0, cipherText, 0, IV_LEN);
    System.arraycopy(messageCipher, 0, cipherText, IV_LEN,
        messageCipher.length);
    return cipherText;
  }

  public byte[] decrypt(byte[] input, SecretKeySpec key) throws Exception {
    Objects.requireNonNull(input, "Input message cannot be null");
    Objects.requireNonNull(key, "key cannot be null");

    if (input.length == 0) {
      throw new IllegalArgumentException("Input array cannot be empty");
    }

    byte[] iv = new byte[IV_LEN];
    System.arraycopy(input, 0, iv, 0, IV_LEN);

    byte[] messageCipher = new byte[input.length - IV_LEN];
    System.arraycopy(input, IV_LEN, messageCipher, 0, input.length - IV_LEN);

    GCMParameterSpec gcmParamSpec = new GCMParameterSpec(AUTH_TAG_SIZE, iv);

    Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
    cipher.init(Cipher.DECRYPT_MODE, key, gcmParamSpec);

    return cipher.doFinal(messageCipher);
  }

  public byte[] getIV(int bytesNum) {

    if (bytesNum < 1) throw new IllegalArgumentException(
        "Number of bytes must be greater than 0");

    byte[] iv = new byte[bytesNum];

    prng = Optional.ofNullable(prng).orElseGet(() -> {
      try {
        prng = SecureRandom.getInstanceStrong();
      } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Wrong algorithm name", e);
      }
      return prng;
    });

    if (bytesGenerated > PRNG_RESEED_INTERVAL || bytesGenerated == 0) {
      prng.setSeed(prng.generateSeed(bytesNum));
      bytesGenerated = 0;
    }

    prng.nextBytes(iv);
    bytesGenerated = bytesGenerated + bytesNum;

    return iv;
  }

  private static void clearSecret(Destroyable key)
      throws IllegalArgumentException, IllegalAccessException,
      NoSuchFieldException, SecurityException {
    Field keyField = key.getClass().getDeclaredField("key");
    keyField.setAccessible(true);
    byte[] encodedKey = (byte[]) keyField.get(key);
    Arrays.fill(encodedKey, Byte.MIN_VALUE);
  }
}

The encryption key can be generated primarily in two ways:

  • Without any password

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(KEY_LEN, SecureRandom.getInstanceStrong());
    SecretKey secretKey = keyGen.generateKey();
    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(),
        "AES");
    Crypto.clearSecret(secretKey);
    // After encryption or decryption with key
    Crypto.clearSecret(secretKeySpec);
    
  • With password

    SecureRandom random = SecureRandom.getInstanceStrong();
    byte[] salt = new byte[32];
    random.nextBytes(salt);
    PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterations, 
       keyLength);
    SecretKeyFactory keyFactory = 
        SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    SecretKey secretKey = keyFactory.generateSecret(keySpec);
    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(),
        "AES");
    Crypto.clearSecret(secretKey);
    // After encryption or decryption with key
    Crypto.clearSecret(secretKeySpec);
    

Update Based on Comments

As pointed out by @MaartenBodewes, my answer did not handle any String as is required by the question. Therefore, I'll make an attempt to fill that gap just in case someone stumbles upon this answer and leaves wondering about handling String.

As indicated earlier in the answer, handling sensitive information in a String is, in general, not a good idea because String is immutable and thus we cannot clear it off after use. And as we know, even when a String doesn't have a strong reference, the garbage collector does not immediately rush to remove it off heap. Thus, the String continues to be around in the memory for an unknown window of time even though it is not accessible to the program. The issue with that is, a heap dump during that time frame would reveal the sensitive information. Therefore, it is always better to handle all sensitive information in a byte array or char array and then fill the array with 0s once their purpose is served.

However, with all that knowledge, if we still end up in a situation where the sensitive information to be encrypted is in a String, we first need to convert it into a byte array and invoke the encrypt and decrypt functions introduced above. (The other input key can be generated using the code snippet provided above).

A String can be converted into bytes in the following way:

byte[] inputBytes = inputString.getBytes(StandardCharsets.UTF_8);

As of Java 8, String is internally stored in heap with UTF-16 encoding. However, we have used UTF-8 here as it usually takes less space than UTF-16, especially for ASCII characters.

Likewise, the encrypted byte array can also be converted into a String as below:

String encryptedString = new String(encryptedBytes, StandardCharsets.UTF_8);

MVC which submit button has been pressed

Name both your submit buttons the same

<input name="submit" type="submit" id="submit" value="Save" />
<input name="submit" type="submit" id="process" value="Process" />

Then in your controller get the value of submit. Only the button clicked will pass its value.

public ActionResult Index(string submit)
{
    Response.Write(submit);
    return View();
}

You can of course assess that value to perform different operations with a switch block.

public ActionResult Index(string submit)
{
    switch (submit)
    {
        case "Save":
            // Do something
            break;
        case "Process":
            // Do something
            break;
        default:
            throw new Exception();
            break;
    }

    return View();
}

Python-equivalent of short-form "if" in C++

My cryptic version...

a = ['123', '456'][b == True]

Using ZXing to create an Android barcode scanning app

If you want to include into your code and not use the IntentIntegrator that the ZXing library recommend, you can use some of these ports:

I use the first, and it works perfectly! It has a sample project to try it on.

Using sessions & session variables in a PHP Login Script

You need to begin the session at the top of a page or before you call session code

session_start(); 

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

'str' object has no attribute 'decode'. Python 3 error?

If you land here using jwt authentication after the PyJWT v2.0.0 release (22/12/2020), you might want to freeze your version of PyJWT to the previous release in your requirements.txt file.

PyJWT==1.7.1

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

How to use a TRIM function in SQL Server

You are missing two closing parentheses...and I am not sure an ampersand works as a string concatenation operator. Try '+'

SELECT dbo.COL_V_Cost_GEMS_Detail.TNG_SYS_NR AS [EHP Code], 
dbo.COL_TBL_VCOURSE.TNG_NA AS [Course Title], 
LTRIM(RTRIM(FCT_TYP_CD)) + ') AND (' + LTRIM(RTRIM(DEP_TYP_ID)) + ')' AS [Course Owner]

Get a list of all git commits, including the 'lost' ones

When I tackle this issue I use the following command:

git reflog |  awk '{ print $1 }' | xargs gitk

This lets me visualise recent commits which have become headless.

I have this wrapped up in a script helper called ~/bin/git-reflog-gitk.

How to force cp to overwrite without confirmation

I simply used unalias to remove the "cp -i" alias, then do the copy, then set back the alias. :

unalias cp  
cp -f foo foo.copy  
alias cp="cp -i"  

Not the most beautiful code, but easy to set and efficient. I also check the alias is already set back with a simple

alias |grep cp

In R, how to find the standard error of the mean?

A version of John's answer above that removes the pesky NA's:

stderr <- function(x, na.rm=FALSE) {
  if (na.rm) x <- na.omit(x)
  sqrt(var(x)/length(x))
}

Effect of NOLOCK hint in SELECT statements

NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.

NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.

Here is information about all of the isolation levels at your disposal, as well as table hints.

SET TRANSACTION ISOLATION LEVEL

Table Hint (Transact-SQL)

Zsh: Conda/Pip installs command not found

If this problem occurs on a mac, then type the following commands:

source <path to conda>/bin/activate
conda init zsh

This will modify your zshrc accordingly (or create it if it does not exist).

This solution comes from the official anaconda doc.

CSS text-overflow in a table cell?

To clip text with an ellipsis when it overflows a table cell, you will need to set the max-width CSS property on each td class for the overflow to work. No extra layout div elements are required:

td
{
 max-width: 100px;
 overflow: hidden;
 text-overflow: ellipsis;
 white-space: nowrap;
}

For responsive layouts; use the max-width CSS property to specify the effective minimum width of the column, or just use max-width: 0; for unlimited flexibility. Also, the containing table will need a specific width, typically width: 100%;, and the columns will typically have their width set as percentage of the total width

table {width: 100%;}
td
{
 max-width: 0;
 overflow: hidden;
 text-overflow: ellipsis;
 white-space: nowrap;
}
td.column_a {width: 30%;}
td.column_b {width: 70%;}

Historical: For IE 9 (or less) you need to have this in your HTML, to fix an IE-specific rendering issue

<!--[if IE]>
<style>
table {table-layout: fixed; width: 100px;}
</style>
<![endif]-->

Can't build create-react-app project with custom PUBLIC_URL

If the other answers aren't working for you, there's also a homepage field in package.json. After running npm run build you should get a message like the following:

The project was built assuming it is hosted at the server root.
To override this, specify the homepage in your package.json.
For example, add this to build it for GitHub Pages:

  "homepage" : "http://myname.github.io/myapp",

You would just add it as one of the root fields in package.json, e.g.

{
  // ...
  "scripts": {
    // ...
  },
  "homepage": "https://example.com"
}

When it's successfully set, either via homepage or PUBLIC_URL, you should instead get a message like this:

The project was built assuming it is hosted at https://example.com.
You can control this with the homepage field in your package.json.

Do I need <class> elements in persistence.xml?

for JPA 2+ this does the trick

 <jar-file></jar-file>

scan all jars in war for annotated @Entity classes

How to run the sftp command with a password from Bash script?

Combine sshpass with a locked-down credentials file and, in practice, it's as secure as anything - if you've got root on the box to read the credentials file, all bets are off anyway.

Index (zero based) must be greater than or equal to zero

Change this line:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

Android TextView Justify Text

You have to set

android:layout_height="wrap_content"

and

android:layout_centerInParent="true"

An error occurred while collecting items to be installed (Access is denied)

I got this error on my ubuntu box until I ran eclipse as root and installed from there:

$ gksudo eclipse

Eclipse was trying to download the packages to /usr/lib/* where I don't have write permissions

How to save CSS changes of Styles panel of Chrome Developer Tools?

To answer the last part of your question about any extensions that can save changes, there is hotfix

It allows you to save changes from Chrome Dev Tools directly to GitHub. From there you can set up a post-receive hook on GitHub to automatically update your website.

Request exceeded the limit of 10 internal redirects due to probable configuration error

i solved this by http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/ just uncomment or add this:

RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

to your .htaccess file

What is the best regular expression to check if a string is a valid URL?

The best regular expression for URL for me would be:

"(([\w]+:)?//)?(([\d\w]|%[a-fA-F\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?"

Dropping connected users in Oracle database

I was trying to follow the flow described here - but haven't luck to completely kill the session.. Then I fond additional step here:
http://wyding.blogspot.com/2013/08/solution-for-ora-01940-cannot-drop-user.html

What I did:
1. select 'alter system kill session ''' || sid || ',' || serial# || ''';' from v$session where username = '<your_schema>'; - as described below.
Out put will be something like this:
alter system kill session '22,15' immediate;
2. alter system disconnect session '22,15' IMMEDIATE ; - 22-sid, 15-serial - repeat the command for each returned session from previous command
3. Repeat steps 1-2 while select... not return an empty table
4. Call drop user...

What was missed - call alter system disconnect session '22,15' IMMEDIATE ; for each of session returned by select 'alter system kill session '..

How to call javascript function from code-behind

One way of doing it is to use the ClientScriptManager:

Page.ClientScript.RegisterStartupScript(
    GetType(), 
    "MyKey", 
    "Myfunction();", 
    true);

pandas: to_numeric for multiple columns

UPDATE: you don't need to convert your values afterwards, you can do it on-the-fly when reading your CSV:

In [165]: df=pd.read_csv(url, index_col=0, na_values=['(NA)']).fillna(0)

In [166]: df.dtypes
Out[166]:
GeoName                    object
ComponentName              object
IndustryId                  int64
IndustryClassification     object
Description                object
2004                        int64
2005                        int64
2006                        int64
2007                        int64
2008                        int64
2009                        int64
2010                        int64
2011                        int64
2012                        int64
2013                        int64
2014                      float64
dtype: object

If you need to convert multiple columns to numeric dtypes - use the following technique:

Sample source DF:

In [271]: df
Out[271]:
     id    a  b  c  d  e    f
0  id_3  AAA  6  3  5  8    1
1  id_9    3  7  5  7  3  BBB
2  id_7    4  2  3  5  4    2
3  id_0    7  3  5  7  9    4
4  id_0    2  4  6  4  0    2

In [272]: df.dtypes
Out[272]:
id    object
a     object
b      int64
c      int64
d      int64
e      int64
f     object
dtype: object

Converting selected columns to numeric dtypes:

In [273]: cols = df.columns.drop('id')

In [274]: df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')

In [275]: df
Out[275]:
     id    a  b  c  d  e    f
0  id_3  NaN  6  3  5  8  1.0
1  id_9  3.0  7  5  7  3  NaN
2  id_7  4.0  2  3  5  4  2.0
3  id_0  7.0  3  5  7  9  4.0
4  id_0  2.0  4  6  4  0  2.0

In [276]: df.dtypes
Out[276]:
id     object
a     float64
b       int64
c       int64
d       int64
e       int64
f     float64
dtype: object

PS if you want to select all string (object) columns use the following simple trick:

cols = df.columns[df.dtypes.eq('object')]

How to set the component size with GridLayout? Is there a better way?

Don't use GridLayout for something it wasn't meant to do. It sounds to me like GridBagLayout would be a better fit for you, either that or MigLayout (though you'll have to download that first since it's not part of standard Java). Either that or combine layout managers such as BoxLayout for the lines and GridLayout to hold all the rows.

For example, using GridBagLayout:

import java.awt.*;
import javax.swing.*;

public class LayoutEg1 extends JPanel{
    private static final int ROWS = 10;

    public LayoutEg1() {
        setLayout(new GridBagLayout());
        for (int i = 0; i < ROWS; i++) {
            GridBagConstraints gbc = makeGbc(0, i);
            JLabel label = new JLabel("Row Label " + (i + 1));
            add(label, gbc);

            JPanel panel = new JPanel();
            panel.add(new JCheckBox("check box"));
            panel.add(new JTextField(10));
            panel.add(new JButton("Button"));
            panel.setBorder(BorderFactory.createEtchedBorder());
            gbc = makeGbc(1, i);
            add(panel, gbc);
        }
    }

    private GridBagConstraints makeGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.weightx = x;
        gbc.weighty = 1.0;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = (x == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        return gbc;
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("Layout Eg1");
        frame.getContentPane().add(new LayoutEg1());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

Android EditText view Floating Hint in Material Design

Import the Support Libraries, In your project's build.gradle file, add the following lines in the project's dependencies:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support:appcompat-v7:22.2.0'
}

Use following TextInputLayout in your UI Layout:

<android.support.design.widget.TextInputLayout
    android:id="@+id/usernameWrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:hint="Username"/>

</android.support.design.widget.TextInputLayout>

Than, call setHint on TextInputLayout just after setContentView call because, to animate the floating label, you just need to set a hint, using the setHint method.

final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);
usernameWrapper.setHint("Username");

Execute a terminal command from a Cocoa app

Objective-C (see below for Swift)

Cleaned up the code in the top answer to make it more readable, less redundant, added the benefits of the one-line method and made into an NSString category

@interface NSString (ShellExecution)
- (NSString*)runAsCommand;
@end

Implementation:

@implementation NSString (ShellExecution)

- (NSString*)runAsCommand {
    NSPipe* pipe = [NSPipe pipe];

    NSTask* task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/sh"];
    [task setArguments:@[@"-c", [NSString stringWithFormat:@"%@", self]]];
    [task setStandardOutput:pipe];

    NSFileHandle* file = [pipe fileHandleForReading];
    [task launch];

    return [[NSString alloc] initWithData:[file readDataToEndOfFile] encoding:NSUTF8StringEncoding];
}

@end

Usage:

NSString* output = [@"echo hello" runAsCommand];

And if you're having problems with output encoding:

// Had problems with `lsof` output and Japanese-named files, this fixed it
NSString* output = [@"export LANG=en_US.UTF-8;echo hello" runAsCommand];

Hope it's as useful to you as it will be to future me. (Hi, you!)


Swift 4

Here's a Swift example making use of Pipe, Process, and String

extension String {
    func run() -> String? {
        let pipe = Pipe()
        let process = Process()
        process.launchPath = "/bin/sh"
        process.arguments = ["-c", self]
        process.standardOutput = pipe

        let fileHandle = pipe.fileHandleForReading
        process.launch()

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

Usage:

let output = "echo hello".run()

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Convert a date format in PHP

Use:

implode('-', array_reverse(explode('-', $date)));

Without the date conversion overhead, I am not sure it'll matter much.

Strip HTML from strings in Python

You can write your own function:

def StripTags(text):
     finished = 0
     while not finished:
         finished = 1
         start = text.find("<")
         if start >= 0:
             stop = text[start:].find(">")
             if stop >= 0:
                 text = text[:start] + text[start+stop+1:]
                 finished = 0
     return text

g++ undefined reference to typeinfo

I encounter an situation that is rare, but this may help other friends in similar situation. I have to work on an older system with gcc 4.4.7. I have to compile code with c++11 or above support, so I build the latest version of gcc 5.3.0. When building my code and linking to the dependencies if the dependency is build with older compiler, then I got 'undefined reference to' error even though I clearly defined the linking path with -L/path/to/lib -llibname. Some packages such as boost and projects build with cmake usually has a tendency to use the older compiler, and they usually cause such problems. You have to go a long way to make sure they use the newer compiler.

How do I add a new column to a Spark DataFrame (using PySpark)?

To add new column with some custom value or dynamic value calculation which will be populated based on the existing columns.

e.g.

|ColumnA | ColumnB |
|--------|---------|
| 10     | 15      |
| 10     | 20      |
| 10     | 30      |

and new ColumnC as ColumnA+ColumnB

|ColumnA | ColumnB | ColumnC|
|--------|---------|--------|
| 10     | 15      | 25     |
| 10     | 20      | 30     |
| 10     | 30      | 40     |

using

#to add new column
def customColumnVal(row):
rd=row.asDict()
rd["ColumnC"]=row["ColumnA"] + row["ColumnB"]

new_row=Row(**rd)
return new_row
----------------------------
#convert DF to RDD
df_rdd= input_dataframe.rdd

#apply new fucntion to rdd
output_dataframe=df_rdd.map(customColumnVal).toDF()

input_dataframe is the dataframe which will get modified and customColumnVal function is having code to add new column.

How to view query error in PDO PHP

/* Provoke an error -- the BONES table does not exist */

$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);

output

Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)

How to create a .gitignore file

========== In Windows ==========

  1. Open Notepad.
  2. Add the contents of your gitignore file.
  3. Click "Save as" and select "all files".
  4. Save as .gitignore.

======== Easy peasy! No command line required! ========

How can I link to a specific glibc version?

In my opinion, the laziest solution (especially if you don't rely on latest bleeding edge C/C++ features, or latest compiler features) wasn't mentioned yet, so here it is:

Just build on the system with the oldest GLIBC you still want to support.

This is actually pretty easy to do nowadays with technologies like chroot, or KVM/Virtualbox, or docker, even if you don't really want to use such an old distro directly on any pc. In detail, to make a maximum portable binary of your software I recommend following these steps:

  1. Just pick your poison of sandbox/virtualization/... whatever, and use it to get yourself a virtual older Ubuntu LTS and compile with the gcc/g++ it has in there by default. That automatically limits your GLIBC to the one available in that environment.

  2. Avoid depending on external libs outside of foundational ones: like, you should dynamically link ground-level system stuff like glibc, libGL, libxcb/X11/wayland things, libasound/libpulseaudio, possibly GTK+ if you use that, but otherwise preferrably statically link external libs/ship them along if you can. Especially mostly self-contained libs like image loaders, multimedia decoders, etc can cause less breakage on other distros (breakage can be caused e.g. if only present somewhere in a different major version) if you statically ship them.

With that approach you get an old-GLIBC-compatible binary without any manual symbol tweaks, without doing a fully static binary (that may break for more complex programs because glibc hates that, and which may cause licensing issues for you), and without setting up any custom toolchain, any custom glibc copy, or whatever.

Ways to eliminate switch in code

Everybody loves HUGE if else blocks. So easy to read! I am curious as to why you would want to remove switch statements, though. If you need a switch statement, you probably need a switch statement. Seriously though, I'd say it depends on what the code's doing. If all the switch is doing is calling functions (say) you could pass function pointers. Whether it's a better solution is debatable.

Language is an important factor here also, I think.

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

How to quietly remove a directory with content in PowerShell

2018 Update

In the current version of PowerShell (tested with v5.1 on Windows 10 1809) one can use the simpler Unix syntax rm -R .\DirName to silently delete the directory .\DirName with all subdirectories and files it may contain. In fact many common Unix commands work in the same way in PowerShell as in a Linux command line.

Can't clone a github repo on Linux via HTTPS

The answer was simple but not obvious:

Instead of:

git clone https://github.com/org/project.git

do:

git clone https://[email protected]/org/project.git

or (insecure)

git clone https://username:[email protected]/org/project.git

(Note that in the later case, your password will may be visible by other users on your machine by running ps u -u $you and will appear cleartext in your shell's history by default)

All 3 ways work on my Mac, but only the last 2 worked on the remote Linux box. (Thinking back on this, it's probably because I had a global git username set up on my Mac, whereas on the remote box I did not? That might have been the case, but the lack of prompt for a username tripped me up... )

Haven't seen this documented anywhere, so here it is.

Is it possible to play music during calls so that the partner can hear it ? Android

You failed to find an app that does this because it is not possible.

The documentation clearly states (here):

Note: You can play back the audio data only to the standard output device. Currently, that is the mobile device speaker or a Bluetooth headset. You cannot play sound files in the conversation audio during a call.

The reason behind this decision has probably something to do with security: there are several scenarios where this capability could be used for cons.

(the OP is highly similar to this, hence I'm basically giving the same answer)

Setting up MySQL and importing dump within Dockerfile

edit: I had misunderstand the question here. My following answer explains how to run sql commands at container creation time, but not at image creation time as desired by OP.

I'm not quite fond of Kuhess's accepted answer as the sleep 5 seems a bit hackish to me as it assumes that the mysql db daemon has correctly loaded within this time frame. That's an assumption, no guarantee. Also if you use a provided mysql docker image, the image itself already takes care about starting up the server; I would not interfer with this with a custom /usr/bin/mysqld_safe.

I followed the other answers around here and copied bash and sql scripts into the folder /docker-entrypoint-initdb.d/ within the docker container as this is clearly the intended way by the mysql image provider. Everything in this folder is executed once the db daemon is ready, hence you should be able rely on it.

As an addition to the others - since no other answer explicitely mentions this: besides sql scripts you can also copy bash scripts into that folder which might give you more control.

This is what I had needed for example as I also needed to import a dump, but the dump alone was not sufficient as it did not provide which database it should import into. So in my case I have a script named db_custom_init.sh with this content:

mysql -u root -p$MYSQL_ROOT_PASSWORD -e 'create database my_database_to_import_into'
mysql -u root -p$MYSQL_ROOT_PASSWORD my_database_to_import_into < /home/db_dump.sql

and this Dockerfile copying that script:

FROM mysql/mysql-server:5.5.62
ENV MYSQL_ROOT_PASSWORD=XXXXX
COPY ./db_dump.sql /home/db_dump.sql
COPY ./db_custom_init.sh /docker-entrypoint-initdb.d/

How to restore SQL Server 2014 backup in SQL Server 2008

Pretty old question... but I had the same problem today and solved with script, a little bit slow and complex but worked. I did this:

Let's start from the source DB (SQL 2014) right click on the database you would like to backup -> Generate Scripts -> "Script entire database and all database objet" (or u can select only some table if u want) -> the most important step is in the "Set Scripting Options" tab, here you have to click on "Advanced" and look for the option "Script for Server version" and in my case I could select everything from SQL 2005, also pay attention to the option "Types of data to script" I advice "Schema and data" and also Script Triggers and Script Full-text Indexes (if you need, it's false by default) and finally click ok and next. Should look like this:

Set Scripting Options

Now transfer your generated script into your SQL 2008, open it and last Important Step: You must change mdf and ldf location!!

That's all folks, happy F5!! :D

Where can I find MySQL logs in phpMyAdmin?

I had the same problem of @rutherford, today the new phpMyAdmin's 3.4.11.1 GUI is different, so I figure out it's better if someone improves the answers with updated info.

Full mysql logs can be found in:

"Status"->"Binary Log"

This is the answer, doesn't matter if you're using MAMP, XAMPP, LAMP, etc.

Gradle DSL method not found: 'runProguard'

runProguard has been renamed to minifyEnabled in version 0.14.0 (2014/10/31) or more in Gradle.

To fix this, you need to change runProguard to minifyEnabled in the build.gradle file of your project.

enter image description here

Android SDK location

press WIN+R and from the run dialog run dialog Execute the following: **%appdata%..\Local\Android**

You should now be presented with Folder Explorer displaying the parent directory of the SDK.

How to restart Activity in Android

I used this code so I still could support older Android versions and use recreate() on newer Android versions.

Code:

public static void restartActivity(Activity activity){
    if (Build.VERSION.SDK_INT >= 11) {
        activity.recreate();
    } else {
        activity.finish();
        activity.startActivity(activity.getIntent());
    }
}

Sample:

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Activity mActivity;

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

        mActivity = MainActivity.this;

        Button button = (Button) findViewById(R.id.restart_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                restartActivity(mActivity);
            }
        });
    }

    public static void restartActivity(Activity activity) {
        if (Build.VERSION.SDK_INT >= 11) {
            activity.recreate();
        } else {
            activity.finish();
            activity.startActivity(activity.getIntent());
        }
    }
}

Printing hexadecimal characters in C

You can create an unsigned char:

unsigned char c = 0xc5;

Printing it will give C5 and not ffffffc5.

Only the chars bigger than 127 are printed with the ffffff because they are negative (char is signed).

Or you can cast the char while printing:

char c = 0xc5; 
printf("%x", (unsigned char)c);

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):

CREATE OR REPLACE FUNCTION get_allitems
  RETURN SYS_REFCURSOR
AS
  my_cursor SYS_REFCURSOR;
BEGIN
  OPEN my_cursor FOR SELECT * FROM allitems;
  RETURN my_cursor;
END get_allitems;

This will return the cursor.

Make sure not to put your SELECT-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.


If you really need to use dynamic SQL you can put your query in single quotes:

  OPEN my_cursor FOR 'SELECT * FROM allitems';

This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.

Make sure to use bind-variables where possible to avoid hard parses:

  OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

SQLite3 database or disk is full / the database disk image is malformed

To avoid getting "database or disk is full" in the first place, try this if you have lots of RAM:

sqlite> pragma temp_store = 2;

That tells SQLite to put temp files in memory. (The "database or disk is full" message does not mean either that the database is full or that the disk is full! It means the temp directory is full.) I have 256G of RAM but only 2G of /tmp, so this works great for me. The more RAM you have, the bigger db files you can work with.

If you haven't got a lot of ram, try this:

sqlite> pragma temp_store = 1;
sqlite> pragma temp_store_directory = '/directory/with/lots/of/space';

temp_store_directory is deprecated (which is silly, since temp_store is not deprecated and requires temp_store_directory), so be wary of using this in code.

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

I believe fcntl() is a POSIX function. Where as ioctl() is a standard UNIX thing. Here is a list of POSIX io. ioctl() is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl() stuff might only work on certain OS or even certain revs of it's kernel.

How to see local history changes in Visual Studio Code?

I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.

Remove the last character from a string

An alternative to substr is the following, as a function:

substr_replace($string, "", -1)

Is it the fastest? I don't know, but I'm willing to bet these alternatives are all so fast that it just doesn't matter.

What is the most accurate way to retrieve a user's correct IP address in PHP?

/**
 * Sanitizes IPv4 address according to Ilia Alshanetsky's book
 * "php|architect?s Guide to PHP Security", chapter 2, page 67.
 *
 * @param string $ip An IPv4 address
 */
public static function sanitizeIpAddress($ip = '')
{
if ($ip == '')
    {
    $rtnStr = '0.0.0.0';
    }
else
    {
    $rtnStr = long2ip(ip2long($ip));
    }

return $rtnStr;
}

//---------------------------------------------------

/**
 * Returns the sanitized HTTP_X_FORWARDED_FOR server variable.
 *
 */
public static function getXForwardedFor()
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
    $rtnStr = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
elseif (isset($HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR']))
    {
    $rtnStr = $HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'];
    }
elseif (getenv('HTTP_X_FORWARDED_FOR'))
    {
    $rtnStr = getenv('HTTP_X_FORWARDED_FOR');
    }
else
    {
    $rtnStr = '';
    }

// Sanitize IPv4 address (Ilia Alshanetsky):
if ($rtnStr != '')
    {
    $rtnStr = explode(', ', $rtnStr);
    $rtnStr = self::sanitizeIpAddress($rtnStr[0]);
    }

return $rtnStr;
}

//---------------------------------------------------

/**
 * Returns the sanitized REMOTE_ADDR server variable.
 *
 */
public static function getRemoteAddr()
{
if (isset($_SERVER['REMOTE_ADDR']))
    {
    $rtnStr = $_SERVER['REMOTE_ADDR'];
    }
elseif (isset($HTTP_SERVER_VARS['REMOTE_ADDR']))
    {
    $rtnStr = $HTTP_SERVER_VARS['REMOTE_ADDR'];
    }
elseif (getenv('REMOTE_ADDR'))
    {
    $rtnStr = getenv('REMOTE_ADDR');
    }
else
    {
    $rtnStr = '';
    }

// Sanitize IPv4 address (Ilia Alshanetsky):
if ($rtnStr != '')
    {
    $rtnStr = explode(', ', $rtnStr);
    $rtnStr = self::sanitizeIpAddress($rtnStr[0]);
    }

return $rtnStr;
}

//---------------------------------------------------

/**
 * Returns the sanitized remote user and proxy IP addresses.
 *
 */
public static function getIpAndProxy()
{
$xForwarded = self::getXForwardedFor();
$remoteAddr = self::getRemoteAddr();

if ($xForwarded != '')
    {
    $ip    = $xForwarded;
    $proxy = $remoteAddr;
    }
else
    {
    $ip    = $remoteAddr;
    $proxy = '';
    }

return array($ip, $proxy);
}

How can I format a nullable DateTime with ToString()?

I think you have to use the GetValueOrDefault-Methode. The behaviour with ToString("yy...") is not defined if the instance is null.

dt2.GetValueOrDefault().ToString("yyy...");

How to embed a video into GitHub README.md?

Even though this is an old post, I thought it would be helpful to mention an additional (partial and tangential) solution to this question on top of the very helpful workarounds that are already present in this thread.

At the time of writing (6 January 2021), GitHub has released a feature to upload .mp4 and .mov files up to 10 MB in size to issues, pull requests and discussion comments (as shared here). This is a direct embed, instead of "linking" it to external URLs as what we usually do. It is already out of public beta. You can attach files by dragging and dropping, selecting or pasting them. A preview of GitHub's new notice can be seen here:

Preview of GitHub's notice on video support

Perhaps, in the future, we can slowly nudge GitHub to eventually extend this native feature to READMEs as well.

load json into variable

  • this will get JSON file externally to your javascript variable.
  • now this sample_data will contain the values of JSON file.

var sample_data = '';
$.getJSON("sample.json", function (data) {
    sample_data = data;
    $.each(data, function (key, value) {
        console.log(sample_data);
    });
});

What's the difference between .NET Core, .NET Framework, and Xamarin?

You should use .NET Core, instead of .NET Framework or Xamarin, in the following 6 typical scenarios according to the documentation here.

1. Cross-Platform needs

Clearly, if your goal is to have an application (web/service) that should be able to run across platforms (Windows, Linux and MacOS), the best choice in the .NET ecosystem is to use .NET Core as its runtime (CoreCLR) and libraries are cross-platform. The other choice is to use the Mono Project.

Both choices are open source, but .NET Core is directly and officially supported by Microsoft and will have a heavy investment moving forward.

When using .NET Core across platforms, the best development experience exists on Windows with the Visual Studio IDE which supports many productivity features including project management, debugging, source control, refactoring, rich editing including Intellisense, testing and much more. But rich development is also supported using Visual Studio Code on Mac, Linux and Windows including intellisense and debugging. Even third party editors like Sublime, Emacs, VI and more work well and can get editor intellisense using the open source Omnisharp project.

2. Microservices

When you are building a microservices oriented system composed of multiple independent, dynamically scalable, stateful or stateless microservices, the great advantage that you have here is that you can use different technologies/frameworks/languages at a microservice level. That allows you to use the best approach and technology per micro areas in your system, so if you want to build very performant and scalable microservices, you should use .NET Core. Eventually, if you need to use any .NET Framework library that is not compatible with .NET Core, there’s no issue, you can build that microservice with the .NET Framework and in the future you might be able to substitute it with the .NET Core.

The infrastructure platform you could use are many. Ideally, for large and complex microservice systems, you should use Azure Service Fabric. But for stateless microservices you can also use other products like Azure App Service or Azure Functions.

Note that as of June 2016, not every technology within Azure supports the .NET Core, but .NET Core support in Azure will be increasing dramatically now that .NET Core is RTM released.

3. Best performant and scalable systems

When your system needs the best possible performance and scalability so you get the best responsiveness no matter how many users you have, then is where .NET Core and ASP.NET Core really shine. The more you can do with the same amount of infrastructure/hardware, the richer the experience you’ll have for your end users – at a lower cost.

The days of Moore’s law performance improvements for single CPUs does not apply anymore; yet you need to do more while your system is growing and need higher scalability and performance for everyday’ s more demanding users which are growing exponentially in numbers. You need to get more efficient, optimize everywhere, and scale better across clusters of machines, VMs and CPU cores, ultimately. It is not just a matter of user’s satisfaction; it can also make a huge difference in cost/TCO. This is why it is important to strive for performance and scalability.

As mentioned, if you can isolate small pieces of your system as microservices or any other loosely-coupled approach, it’ll be better as you’ll be able to not just evolve each small piece/microservice independently and have a better long-term agility and maintenance, but also you’ll be able to use any other technology at a microservice level if what you need to do is not compatible with .NET Core. And eventually you’d be able to refactor it and bring it to .NET Core when possible.

4. Command line style development for Mac, Linux or Windows.

This approach is optional when using .NET Core. You can also use the full Visual Studio IDE, of course. But if you are a developer that wants to develop with lightweight editors and heavy use of command line, .NET Core is designed for CLI. It provides simple command line tools available on all supported platforms, enabling developers to build and test applications with a minimal installation on developer, lab or production machines. Editors like Visual Studio Code use the same command line tools for their development experiences. And IDE’s like Visual Studio use the same CLI tools but hide them behind a rich IDE experience. Developers can now choose the level they want to interact with the tool chain from CLI to editor to IDE.

5. Need side by side of .NET versions per application level.

If you want to be able to install applications with dependencies on different versions of frameworks in .NET, you need to use .NET Core which provides 100% side-by side as explained previously in this document.

6. Windows 10 UWP .NET apps.

In addition, you may also want to read:

  1. When should I NOT use .NET Core?
  2. When should I still use .NET Framework 4.x, instead of .NET Core?
  3. When should I use Xamarin, instead of .NET Core?

Generating a PNG with matplotlib when DISPLAY is undefined

I got the error while using matplotlib through Spark. matplotlib.use('Agg') doesn't work for me. In the end, the following code works for me. More here

import matplotlib.pyplot as plt.
plt.switch_backend('agg')

Find the index of a char in string?

Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains("d") Then
        numberString = myString.IndexOf("d")
    End If
End Sub

Another sample with TextBox

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains(me.TextBox1.Text) Then
        numberString = myString.IndexOf(Me.TextBox1.Text)
    End If
End Sub

Regards

Alternative for frames in html5 using iframes

Frames have been deprecated because they caused trouble for url navigation and hyperlinking, because the url would just take to you the index page (with the frameset) and there was no way to specify what was in each of the frame windows. Today, webpages are often generated by server-side technologies such as PHP, ASP.NET, Ruby etc. So instead of using frames, pages can simply be generated by merging a template with content like this:

Template File

<html>
<head>
<title>{insert script variable for title}</title>
</head>

<body>
  <div class="menu">
   {menu items inserted here by server-side scripting}
  </div>
  <div class="main-content">
   {main content inserted here by server-side scripting}
  </div>
</body>
</html>

If you don't have full support for a server-side scripting language, you could also use server-side includes (SSI). This will allow you to do the same thing--i.e. generate a single web page from multiple source documents.

But if you really just want to have a section of your webpage be a separate "window" into which you can load other webpages that are not necessarily located on your own server, you will have to use an iframe.

You could emulate your example like this:

Frames Example

<html>
<head>
  <title>Frames Test</title>
  <style>
   .menu {
      float:left;
      width:20%;
      height:80%;
    }
    .mainContent {
      float:left;
      width:75%;
      height:80%;
    }
  </style>
</head>
<body>
  <iframe class="menu" src="menu.html"></iframe>
  <iframe class="mainContent" src="events.html"></iframe>
</body>
</html>

There are probably better ways to achieve the layout. I've used the CSS float attribute, but you could use tables or other methods as well.

Trigger an event on `click` and `enter`

$('#usersSearch').keyup(function() { // handle keyup event on search input field

    var key = e.which || e.keyCode;  // store browser agnostic keycode

    if(key == 13) 
        $(this).closest('form').submit(); // submit parent form
}

What's the difference between a web site and a web application?

I say a website can be a web application, but more often a website has multiple web applications. the relationship between the two is one of composition: website composed of applications.

a dating site might have a photo upload web application, a calendar one so you can mark when you're dating who.

These applications are embedded throughout the website.

Is there a MessageBox equivalent in WPF?

As the others say, there is a MessageBox in the WPF namespace (System.Windows).

The problem is that it is the same old messagebox with OK, Cancel, etc. Windows Vista and Windows 7 have moved on to use Task Dialogs instead.

Unfortunately there is no easy standard interface for task dialogs. I use an implementation from CodeProject KB.

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

With my Android 5 tablet, every time I attempt to use adb, to install a signed release apk, I get the [INSTALL_FAILED_ALREADY_EXISTS] error.

I have to uninstall the debug package first. But, I cannot uninstall using the device's Application Manager!

If do uninstall the debug version with the Application Manager, then I have to re-run the debug build variant from Android Studio, then uninstall it using adb uninstall com.example.mypackagename

Finally, I can use adb install myApp.apk to install the signed release apk.

How to convert .pem into .key?

openssl x509 -outform der -in your-cert.pem -out your-cert.crt

How to import existing Android project into Eclipse?

Solved: If you want to "Create project from existing source", you need to create a new directory and then put the project directory tree into that new directory. Then point to the new directory when importing.

What's the difference between tilde(~) and caret(^) in package.json?

Semver

<major>.<minor>.<patch>-beta.<beta> == 1.2.3-beta.2
  • Use npm semver calculator for testing. Although the explanations for ^ (include everything greater than a particular version in the same major range) and ~ (include everything greater than a particular version in the same minor range) aren't a 100% correct, the calculator seems to work fine.
  • Alternatively, use SemVer Check instead, which doesn't require you to pick a package and also offers explanations.

Allow or disallow changes

  • Pin version: 1.2.3.
  • Use ^ (like head). Allows updates at the second non-zero level from the left: ^0.2.3 means 0.2.3 <= v < 0.3.
  • Use ~ (like tail). Generally freeze right-most level or set zero if omitted:
  • ~1 means 1.0.0 <= v < 2.0.0
  • ~1.2 means 1.2.0 <= v < 1.3.0.
  • ~1.2.4 means 1.2.4 <= v < 1.3.0.
  • Ommit right-most level: 0.2 means 0.2 <= v < 1. Differs from ~ because:
    • Starting omitted level version is always 0
    • You can set starting major version without specifying sublevels.

All (hopefully) possibilities

Set starting major-level and allow updates upward

*  or "(empty string)   any version
1                         v >= 1

Freeze major-level

~0 (0)            0.0 <= v < 1
0.2               0.2 <= v < 1          // Can't do that with ^ or ~ 
~1 (1, ^1)        1 <= v < 2
^1.2              1.2 <= v < 2
^1.2.3            1.2.3 <= v < 2
^1.2.3-beta.4     1.2.3-beta.4 <= v < 2

Freeze minor-level

^0.0 (0.0)        0 <= v < 0.1
~0.2              0.2 <= v < 0.3
~1.2              1.2 <= v < 1.3
~0.2.3 (^0.2.3)   0.2.3 <= v < 0.3
~1.2.3            1.2.3 <= v < 1.3

Freeze patch-level

~1.2.3-beta.4     1.2.3-beta.4 <= v < 1.2.4 (only beta or pr allowed)
^0.0.3-beta       0.0.3-beta.0 <= v < 0.0.4 or 0.0.3-pr.0 <= v < 0.0.4 (only beta or pr allowed)
^0.0.3-beta.4     0.0.3-beta.4 <= v < 0.0.4 or 0.0.3-pr.4 <= v < 0.0.4 (only beta or pr allowed)

Disallow updates

1.2.3             1.2.3
^0.0.3 (0.0.3)    0.0.3

Notice: Missing major, minor, patch or specifying beta without number, is the same as any for the missing level.

Notice: When you install a package which has 0 as major level, the update will only install new beta/pr level version! That's because npm sets ^ as default in package.json and when installed version is like 0.1.3, it freezes all major/minor/patch levels.

Parse DateTime string in JavaScript

If you are using jQuery UI, you can format any date with:

<html>
    <body>
        Your date formated: <span id="date1"></span><br/>
    </body>
</html>

 

var myDate = '30.11.2011';
var parsedDate = $.datepicker.parseDate('dd.mm.yy', myDate);

$('#date1').text($.datepicker.formatDate('M d, yy', parsedDate));

http://jsfiddle.net/mescalito2345/ND2Qg/14/

Convert Array to Object

You could use a function like this:

var toObject = function(array) {
    var o = {};
    for (var property in array) {
        if (String(property >>> 0) == property && property >>> 0 != 0xffffffff) {
            o[i] = array[i];
        }
    }
    return o;
};

This one should handle sparse arrays more efficiently.

Adding a default value in dropdownlist after binding with database

design

<asp:DropDownList ID="ddlArea" DataSourceID="ldsArea" runat="server" ondatabound="ddlArea_DataBound" />

codebehind

protected void ddlArea_DataBound(object sender, EventArgs e)
{
    ddlArea.Items.Insert(0, new ListItem("--Select--", "0"));
}

Configure Flask dev server to be visible across the network

For me i followed the above answer and modified it a bit:

  1. Just grab your ipv4 address using ipconfig on command prompt
  2. Go to the file in which flask code is present
  3. In main function write app.run(host= 'your ipv4 address')

Eg:

enter image description here

Python: OSError: [Errno 2] No such file or directory: ''

I had this error because I was providing a string of arguments to subprocess.call instead of an array of arguments. To prevent this, use shlex.split:

import shlex, subprocess
command_line = "ls -a"
args = shlex.split(command_line)
p = subprocess.Popen(args)

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

Go to Phone Settings --> Developer Options --> Simulate Secondary Displays and turn it to None. If you don't see Developer Options in the settings menu (it should be at the bottom, go Settings ==> About phone and tap on the Build number a lot of times)

Sending mass email using PHP

Why don't you rather use phplist? It's also built on top of PHP Mailer and a lot of industry leaders are using it. I've used it myself a couple of times to send out bulk mails to my clients. The nice thing about phplist is that you can throttle your messages on a domain level plus a time limit level.

What we've also done with a couple of internal capture systems we've got was to push our user base to the mailling list and then have a cron entry triggering a given mail each day. The possibilities are endless, that's the awesome thing about open source!

String was not recognized as a valid DateTime " format dd/MM/yyyy"

use this to convert string to datetime:

Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)

How do I reset a jquery-chosen select option with jQuery?

The first option should sufice: http://jsfiddle.net/sFCg3/

jQuery('#autoship_option').val('');

But you have to make sure you are runing this on an event like click of a button or ready or document, like on the jsfiddle.

Also make sure that theres always a value attribute on the option tags. If not, some browsers always return empty on val().

Edit:
Now that you have clarifyed the use of the Chosen plugin, you have to call

$("#autoship_option").trigger("liszt:updated");

after changing the value for it to update the intereface.

http://harvesthq.github.com/chosen/

"’" showing on page instead of " ' "

You have a mismatch in your character encoding; your string is encoded in one encoding (UTF-8) and whatever is interpreting this page is using another (say ASCII).

Always specify your encoding in your http headers and make sure this matches your framework's definition of encoding.

Sample http header:

Content-Type    text/html; charset=utf-8

Setting encoding in asp.net

<configuration>
  <system.web>
    <globalization
      fileEncoding="utf-8"
      requestEncoding="utf-8"
      responseEncoding="utf-8"
      culture="en-US"
      uiCulture="de-DE"
    />
  </system.web>
</configuration>

Setting encoding in jsp

Install php-mcrypt on CentOS 6

Try

yum clean all
yum remove epel-release
yum install epel-release

and finally

yum install php-mcrypt

How to get the selected radio button value using js

Possibly not the most efficient way... but I have used an ID on each radio button (this is just because I'm not passing it as an actual form, it is just the raw fields).

I then call a function with a button, which checks each radio button to see if it is checked. It does this using the .checked function. If this is set to true I can change the value of another variable.

_x000D_
_x000D_
function createOutput() {_x000D_
  var order = "in";_x000D_
  if (document.getElementById('radio1').checked == true) {_x000D_
    order = "pre";_x000D_
  } else if (document.getElementById('radio2').checked == true) {_x000D_
    order = "in";_x000D_
  } else if (document.getElementById('radio3').checked == true) {_x000D_
    order = "post";_x000D_
  }_x000D_
  document.getElementById('outputBox').innerHTML = order;_x000D_
}
_x000D_
<input id="radio1" type="radio" name="order" value="preorder" />Preorder_x000D_
<input id="radio2" type="radio" name="order" value="inorder" checked="true" />Inorder_x000D_
<input id="radio3" type="radio" name="order" value="postorder" />Postorder_x000D_
<button onclick="createOutput();">Generate Output</button>_x000D_
<textarea id="outputBox" rows="10" cols="50"></textarea>
_x000D_
_x000D_
_x000D_

Hope this is useful, in someway,

Beanz

HttpListener Access Denied

Yes you can run HttpListener in non-admin mode. All you need to do is grant permissions to the particular URL. e.g.

netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user

Documentation is here.

Request UAC elevation from within a Python script?

A variation on Jorenko's work above allows the elevated process to use the same console (but see my comment below):

def spawn_as_administrator():
    """ Spawn ourself with administrator rights and wait for new process to exit
        Make the new process use the same console as the old one.
          Raise Exception() if we could not get a handle for the new re-run the process
          Raise pywintypes.error() if we could not re-spawn
        Return the exit code of the new process,
          or return None if already running the second admin process. """
    #pylint: disable=no-name-in-module,import-error
    import win32event, win32api, win32process
    import win32com.shell.shell as shell
    if '--admin' in sys.argv:
        return None
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + ['--admin'])
    SEE_MASK_NO_CONSOLE = 0x00008000
    SEE_MASK_NOCLOSE_PROCESS = 0x00000040
    process = shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params, fMask=SEE_MASK_NO_CONSOLE|SEE_MASK_NOCLOSE_PROCESS)
    hProcess = process['hProcess']
    if not hProcess:
        raise Exception("Could not identify administrator process to install drivers")
    # It is necessary to wait for the elevated process or else
    #  stdin lines are shared between 2 processes: they get one line each
    INFINITE = -1
    win32event.WaitForSingleObject(hProcess, INFINITE)
    exitcode = win32process.GetExitCodeProcess(hProcess)
    win32api.CloseHandle(hProcess)
    return exitcode

How to find pg_config path

I had exactly the same error, but I installed postgreSQL through brew and re-run the original command and it worked perfectly :

brew install postgresql

Pass request headers in a jQuery AJAX GET call

Use beforeSend:

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
         success: function() { alert('Success!' + authHeader); }
      });

http://api.jquery.com/jQuery.ajax/

http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

Get latest from Git branch

Although git pull origin yourbranch works, it's not really a good idea

You can alternatively do the following:

git fetch origin
git merge origin/yourbranch

The first line fetches all the branches from origin, but doesn't merge with your branches. This simply completes your copy of the repository.

The second line merges your current branch with that of yourbranch that you fetched from origin (which is one of your remotes).

This is assuming origin points to the repository at address ssh://11.21.3.12:23211/dir1/dir2

Installing and Running MongoDB on OSX

Updated answer (9/2/2019):

Homebrew has removed mongodb formula from its core repository, see this pull request.

The new way to install mongodb using Homebrew is as follows:

~> brew tap mongodb/brew
~> brew install mongodb-community

After installation you can start the mongodb service by following the caveats:

~> brew info mongodb-community
mongodb/brew/mongodb-community: stable 4.2.0
High-performance, schema-free, document-oriented database
https://www.mongodb.com/
Not installed
From: https://github.com/mongodb/homebrew-brew/blob/master/Formula/mongodb-community.rb
==> Caveats
To have launchd start mongodb/brew/mongodb-community now and restart at login:
  brew services start mongodb/brew/mongodb-community
Or, if you don't want/need a background service you can just run:
  mongod --config /usr/local/etc/mongod.conf

Deprecated answer (8/27/2019):

I assume you are using Homebrew. You can see the additional information that you need using brew info $FORMULA

~> brew info mongo                                                           255
mongodb: stable 2.4.6, devel 2.5.1
http://www.mongodb.org/
/usr/local/Cellar/mongodb/2.4.5-x86_64 (20 files, 287M) *
  Built from source
From: https://github.com/mxcl/homebrew/commits/master/Library/Formula/mongodb.rb
==> Caveats
To reload mongodb after an upgrade:
    launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist

Caveats is what you need to follow after installation.

How to set a variable inside a loop for /F

I know this isn't what's asked but I benefited from this method, when trying to set a variable within a "loop". Uses an array. Alternative implementation option.

SETLOCAL ENABLEDELAYEDEXPANSION

...

set Services[0]=SERVICE1
set Services[1]=SERVICE2
set Services[2]=SERVICE3

set "i=0"

:ServicesLoop
if defined Services[%i%] (
    set SERVICE=!Services[%i%]!

    echo CurrentService: !SERVICE!

    set /a "i+=1"
    GOTO :ServicesLoop
)

webpack is not recognized as a internal or external command,operable program or batch file

Maybe a clean install will fix the problem. This "command" removes all previous modules and re-installs them, perhaps while the webpack module is incompletely downloaded and installed.

npm clean-install

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

How to initialize java.util.date to empty

It's not clear how you want your Date logic to behave? Usually a good way to deal with default behaviour is the Null Object pattern.

What's the purpose of git-mv?

Git is just trying to guess for you what you are trying to do. It is making every attempt to preserve unbroken history. Of course, it is not perfect. So git mv allows you to be explicit with your intention and to avoid some errors.

Consider this example. Starting with an empty repo,

git init
echo "First" >a
echo "Second" >b
git add *
git commit -m "initial commit"
mv a c
mv b a
git status

Result:

# On branch master
# Changes not staged for commit:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   a
#   deleted:    b
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   c
no changes added to commit (use "git add" and/or "git commit -a")

Autodetection failed :( Or did it?

$ git add *
$ git commit -m "change"
$ git log c

commit 0c5425be1121c20cc45df04734398dfbac689c39
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:24:56 2013 -0400

    change

and then

$ git log --follow c

Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:24:56 2013 -0400

    change

commit 50c2a4604a27be2a1f4b95399d5e0f96c3dbf70a
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:24:45 2013 -0400

    initial commit

Now try instead (remember to delete the .git folder when experimenting):

git init
echo "First" >a
echo "Second" >b
git add *
git commit -m "initial commit"
git mv a c
git status

So far so good:

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   renamed:    a -> c


git mv b a
git status

Now, nobody is perfect:

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   a
#   deleted:    b
#   new file:   c
#

Really? But of course...

git add *
git commit -m "change"
git log c
git log --follow c

...and the result is the same as above: only --follow shows the full history.


Now, be careful with renaming, as either option can still produce weird effects. Example:

git init
echo "First" >a
git add a
git commit -m "initial a"
echo "Second" >b
git add b
git commit -m "initial b"

git mv a c
git commit -m "first move"
git mv b a
git commit -m "second move"

git log --follow a

commit 81b80f5690deec1864ebff294f875980216a059d
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:35:58 2013 -0400

    second move

commit f284fba9dc8455295b1abdaae9cc6ee941b66e7f
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:34:54 2013 -0400

    initial b

Contrast it with:

git init
echo "First" >a
git add a
git commit -m "initial a"
echo "Second" >b
git add b
git commit -m "initial b"

git mv a c
git mv b a
git commit -m "both moves at the same time"

git log --follow a

Result:

commit 84bf29b01f32ea6b746857e0d8401654c4413ecd
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:37:13 2013 -0400

    both moves at the same time

commit ec0de3c5358758ffda462913f6e6294731400455
Author: Sergey Orshanskiy <*****@gmail.com>
Date:   Sat Oct 12 00:36:52 2013 -0400

    initial a

Ups... Now the history is going back to initial a instead of initial b, which is wrong. So when we did two moves at a time, Git became confused and did not track the changes properly. By the way, in my experiments the same happened when I deleted/created files instead of using git mv. Proceed with care; you've been warned...

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

Even after 9 years of the original post, this helped me.

If you are receiving these types of errors without any clue, there should be a trigger, function related to the table, and obviously it should end up with an SP, or function with selecting/filtering data NOT USING Primary Unique column. If you are searching/filtering using the Primary Unique column there won't be any multiple results. Especially when you are assigning value for a declared variable. The SP never gives you en error but only an runtime error.

 "System.Data.SqlClient.SqlException (0x80131904): Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
    The statement has been terminated."

In my case obviously there was no clue, but only this error message. There was a trigger connected to the table and the table updating by the trigger also had another trigger likewise it ended up with two triggers and in the end with an SP. The SP was having a select clause which was resulting in multiple rows.

SET @Variable1 =(
        SELECT column_gonna_asign
        FROM dbo.your_db
        WHERE Non_primary_non_unique_key= @Variable2

If this returns multiple rows, you are in trouble.

How to send a JSON object over Request with Android?

Nothing could be simple than this. Use OkHttpLibrary

Create your json

JSONObject requestObject = new JSONObject();
requestObject.put("Email", email);
requestObject.put("Password", password);

and send it like this.

OkHttpClient client = new OkHttpClient();

RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
            .addHeader("Content-Type","application/json")
            .url(url)
            .post(requestObject.toString())
            .build();

okhttp3.Response response = client.newCall(request).execute();

How to apply shell command to each line of a command output?

for s in `cmd`; do echo $s; done

If cmd has a large output:

cmd | xargs -L1 echo

font-family is inherit. How to find out the font-family in chrome developer pane?

The inherit value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.

The font-family property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.

If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family set to inherit or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.

This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.

How to force a SQL Server 2008 database to go Offline

You need to use WITH ROLLBACK IMMEDIATE to boot other conections out with no regards to what or who is is already using it.

Or use WITH NO_WAIT to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details

How do I escape ampersands in XML so they are rendered as entities in HTML?

&amp; is the way to represent an ampersand in most sections of an XML document.

If you want to have XML displayed within HTML, you need to first create properly encoded XML (which involves changing & to &amp;) and then use that to create properly encoded HTML (which involves again changing & to &amp;). That results in:

&amp;amp;

For a more thorough explanation of XML encoding, see:

What characters do I need to escape in XML documents?

Jquery array.push() not working

another workaround:

var myarray = [];
$("#test").click(function() {
    myarray[index]=$("#drop").val();
    alert(myarray);
});

i wanted to add all checked checkbox to array. so example, if .each is used:

var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
   if (this.checked) {
       var p=$('.pp').eq(idx).val();
       vpp[incr]=(p);
       incr++;
   }
});
//do what ever with vpp array;

Function to get yesterday's date in Javascript in format DD/MM/YYYY

Try this:

function getYesterdaysDate() {
    var date = new Date();
    date.setDate(date.getDate()-1);
    return date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
}

How might I force a floating DIV to match the height of another floating DIV?

You should wrap them in a div with no float.

<div style="float:none;background:#FDD017;" class="clearfix">
    <div id="response" style="float:left; width:65%;">Response with two lines</div>
    <div id="note" style="float:left; width:35%;">single line note</div>
</div>

I also use the clearfix patch on here http://www.webtoolkit.info/css-clearfix.html

Setting up PostgreSQL ODBC on Windows

As I see PostgreSQL installer doesn't include 64 bit version of ODBC driver, which is necessary in your case. Download psqlodbc_09_00_0310-x64.zip and install it instead. I checked that on Win 7 64 bit and PostgreSQL 9.0.4 64 bit and it looks ok:

enter image description here

Test connection:

enter image description here

How to check if an object implements an interface?

If you want a method like public void doSomething([Object implements Serializable]) you can just type it like this public void doSomething(Serializable serializableObject). You can now pass it any object that implements Serializable but using the serializableObject you only have access to the methods implemented in the object from the Serializable interface.

json_decode to array

This will also change it into an array:

<?php
    print_r((array) json_decode($object));
?>

Matplotlib discrete colorbar

You could follow this example:

#!/usr/bin/env python
"""
Use a pcolor or imshow with a custom colormap to make a contour plot.

Since this example was initially written, a proper contour routine was
added to matplotlib - see contour_demo.py and
http://matplotlib.sf.net/matplotlib.pylab.html#-contour.
"""

from pylab import *


delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians

cmap = cm.get_cmap('PiYG', 11)    # 11 discrete colors

im = imshow(Z, cmap=cmap, interpolation='bilinear',
            vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()

show()

which produces the following image:

poormans_contour

python: Appending a dictionary to a list - I see a pointer like behavior

Also with dict

a = []
b = {1:'one'}

a.append(dict(b))
print a
b[1]='iuqsdgf'
print a

result

[{1: 'one'}]
[{1: 'one'}]

HTML5 Canvas 100% Width Height of Viewport?

http://jsfiddle.net/mqFdk/10/

<!DOCTYPE html>
<html>
<head>
    <title>aj</title>
</head>
<body>

    <canvas id="c"></canvas>

</body>
</html>

with CSS

body { 
       margin: 0; 
       padding: 0
     }
#c { 
     position: absolute; 
     width: 100%; 
     height: 100%; 
     overflow: hidden
   }

enum - getting value of enum on string conversion

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

Calendar Recurring/Repeating Events - Best Storage Method

Enhancement: replace timestamp with date

As a small enhancement to the accepted answer that was subsequently refined by ahoffner - it is possible to use a date format rather than timestamp. The advantages are:

  1. readable dates in the database
  2. no issue with the years > 2038 and timestamp
  3. removes need to be careful with timestamps that are based on seasonally adjusted dates i.e. in the UK 28th June starts one hour earlier than 28th December so deriving a timestamp from a date can break the recursion algorithm.

to do this, change the DB repeat_start to be stored as type 'date' and repeat_interval now hold days rather than seconds. i.e. 7 for a repeat of 7 days.

change the sql line:

WHERE (( 1370563200 - repeat_start) % repeat_interval = 0 )

to:

WHERE ( DATEDIFF( '2013-6-7', repeat_start ) % repeat_interval = 0)

everything else remains the same. Simples!

Postgres Error: More than one row returned by a subquery used as an expression

This error means that the SELECT store_key FROM store query has returned two or more rows in the SERVER1 database. If you would like to update all customers, use a join instead of a scalar = operator. You need a condition to "connect" customers to store items in order to do that.

If you wish to update all customer_ids to the same store_key, you need to supply a WHERE clause to the remotely executed SELECT so that the query returns a single row.

Is it possible to ping a server from Javascript?

You could try using PHP in your web page...something like this:

<html><body>
<form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Host to ping:</h1>
<input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br>
<input type="submit" name="submit" value="Submit" >
</form></body>
</html>
<?php

$tgt_host = $_POST['tgt_host'];
$output = shell_exec('ping -c 10 '. $tgt_host.');

echo "<html><body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script>
</body></html>";

?>

This is not tested so it may have typos etc...but I am confident it would work. Could be improved too...

Date in to UTC format Java

java.time

It’s about time someone provides the modern answer. The modern solution uses java.time, the modern Java date and time API. The classes SimpleDateFormat and Date used in the question and in a couple of the other answers are poorly designed and long outdated, the former in particular notoriously troublesome. TimeZone is poorly designed to. I recommend you avoid those.

    ZoneId utc = ZoneId.of("Etc/UTC");
    DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern(
            "MM/dd/yyyy hh:mm:ss a zzz", Locale.ENGLISH);

    String itsAlarmDttm = "2013-10-22T01:37:56";
    ZonedDateTime utcDateTime = LocalDateTime.parse(itsAlarmDttm)
            .atZone(ZoneId.systemDefault())
            .withZoneSameInstant(utc);
    String formatterUtcDateTime = utcDateTime.format(targetFormatter);
    System.out.println(formatterUtcDateTime);

When running in my time zone, Europe/Copenhagen, the output is:

10/21/2013 11:37:56 PM UTC

I have assumed that the string you got was in the default time zone of your JVM, a fragile assumption since that default setting can be changed at any time from another part of your program or another programming running in the same JVM. If you can, instead specify time zone explicitly, for example ZoneId.of("Europe/Podgorica") or ZoneId.of("Asia/Kolkata").

I am exploiting the fact that you string is in ISO 8601 format, the format the the modern classes parse as their default, that is, without any explicit formatter.

I am using a ZonedDateTime for the result date-time because it allows us to format it with UTC in the formatted string to eliminate any and all doubt. For other purposes one would typically have wanted an OffsetDateTime or an Instant instead.

Links

Python Sets vs Lists

from datetime import datetime
listA = range(10000000)
setA = set(listA)
tupA = tuple(listA)
#Source Code

def calc(data, type):
start = datetime.now()
if data in type:
print ""
end = datetime.now()
print end-start

calc(9999, listA)
calc(9999, tupA)
calc(9999, setA)

Output after comparing 10 iterations for all 3 : Comparison

How to tell which commit a tag points to in Git?

How about this:

git log -1 $TAGNAME

OR

git log -1 origin/$TAGNAME

Pair/tuple data type in Go

There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.

Nick's answer shows how you can do something similar that handles arbitrary types using interface{}. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{} type)

My other answer shows how you can do something similar that avoids creating a type using anonymous structs.

These techniques have some properties of tuples, but no, they are not tuples.

javascript: using a condition in switch case

Although in the particular example of the OP's question, switch is not appropriate, there is an example where switch is still appropriate/beneficial, but other evaluation expressions are also required. This can be achieved by using the default clause for the expressions:

switch (foo) {
  case 'bar':
    // do something
    break;
  case 'foo':
    // do something
    break;
  ... // other plain comparison cases
  default:
    if (foo.length > 16) {
      // something specific
    } else if (foo.length < 2) {
      // maybe error
    } else {
      // default action for everything else
    }
}

Get JSON Data from URL Using Android?

private class GetProfileRequestAsyncTasks extends AsyncTask<String, Void, JSONObject> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected JSONObject doInBackground(String... urls) {
        if (urls.length > 0) {
            String url = urls[0];
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            httpget.setHeader("x-li-format", "json");
            try {
                HttpResponse response = httpClient.execute(httpget);
                if (response != null) {
                    //If status is OK 200
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String result = EntityUtils.toString(response.getEntity());
                        //Convert the string result to a JSON Object
                        return new JSONObject(result);
                    }
                }
            } catch (IOException e) {

            } catch (JSONException e) {
            }
        }
        return null;
    }
    @Override
    protected void onPostExecute(JSONObject data) {
        if (data != null) {
            Log.d(TAG, String.valueOf(data));
        }
    }

}

Plot smooth line with PyPlot

See the scipy.interpolate documentation for some examples.

The following example demonstrates its use, for linear and cubic spline interpolation:

>>> from scipy.interpolate import interp1d

>>> x = np.linspace(0, 10, num=11, endpoint=True)
>>> y = np.cos(-x**2/9.0)
>>> f = interp1d(x, y)
>>> f2 = interp1d(x, y, kind='cubic')

>>> xnew = np.linspace(0, 10, num=41, endpoint=True)
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
>>> plt.legend(['data', 'linear', 'cubic'], loc='best')
>>> plt.show()

enter image description here

Location of GlassFish Server Logs

tail -f /path/to/glassfish/domains/YOURDOMAIN/logs/server.log

You can also upload log from admin console : http://yoururl:4848

enter image description here

Implement an input with a mask

Input masks can be implemented using a combination of the keyup event, and the HTMLInputElement value, selectionStart, and selectionEnd properties. Here's a very simple implementation which does some of what you want. It's certainly not perfect, but works well enough to demonstrate the principle:

_x000D_
_x000D_
Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);_x000D_
_x000D_
function applyDataMask(field) {_x000D_
    var mask = field.dataset.mask.split('');_x000D_
    _x000D_
    // For now, this just strips everything that's not a number_x000D_
    function stripMask(maskedData) {_x000D_
        function isDigit(char) {_x000D_
            return /\d/.test(char);_x000D_
        }_x000D_
        return maskedData.split('').filter(isDigit);_x000D_
    }_x000D_
    _x000D_
    // Replace `_` characters with characters from `data`_x000D_
    function applyMask(data) {_x000D_
        return mask.map(function(char) {_x000D_
            if (char != '_') return char;_x000D_
            if (data.length == 0) return char;_x000D_
            return data.shift();_x000D_
        }).join('')_x000D_
    }_x000D_
    _x000D_
    function reapplyMask(data) {_x000D_
        return applyMask(stripMask(data));_x000D_
    }_x000D_
    _x000D_
    function changed() {   _x000D_
        var oldStart = field.selectionStart;_x000D_
        var oldEnd = field.selectionEnd;_x000D_
        _x000D_
        field.value = reapplyMask(field.value);_x000D_
        _x000D_
        field.selectionStart = oldStart;_x000D_
        field.selectionEnd = oldEnd;_x000D_
    }_x000D_
    _x000D_
    field.addEventListener('click', changed)_x000D_
    field.addEventListener('keyup', changed)_x000D_
}
_x000D_
ISO Date: <input type="text" value="____-__-__" data-mask="____-__-__"/><br/>_x000D_
Telephone: <input type="text" value="(___) ___-____" data-mask="(___) ___-____"/><br/>
_x000D_
_x000D_
_x000D_

(View in JSFiddle)

There are also a number of libraries out there which perform this function. Some examples include:

Simple pthread! C++

You should declare the thread main as:

void* print_message(void*) // takes one parameter, unnamed if you aren't using it

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

I had faced this similar error too. In my case it was one of my picture files in my drawable folder. Removing the picture that was unused solved the problem for me. So, make sure to remove any unused items from drawable folder.

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

For OSX your path needs to include /Users/yourusername

their example: /Development/adt-bundle/sdk/platform-tools
needs to be: /Users/yourusername/Development/adt-bundle/sdk/platform-tools

Making a Bootstrap table column fit to content

You can wrap your table around the div tag like this as it helped me too.

<div class="col-md-3">

<table>
</table>

</div>

is of a type that is invalid for use as a key column in an index

A unique constraint can't be over 8000 bytes per row and will only use the first 900 bytes even then so the safest maximum size for your keys would be:

create table [misc_info]
( 
    [id] INTEGER PRIMARY KEY IDENTITY NOT NULL, 
    [key] nvarchar(450) UNIQUE NOT NULL, 
    [value] nvarchar(max) NOT NULL
)

i.e. the key can't be over 450 characters. If you can switch to varchar instead of nvarchar (e.g. if you don't need to store characters from more than one codepage) then that could increase to 900 characters.

Why isn't this code to plot a histogram on a continuous value Pandas column working?

Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing

#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

Not 100% what you were looking for, but kind of an inside-out way of doing it:

SQL> CREATE TABLE mytable (id NUMBER, status VARCHAR2(50));

Table created.

SQL> INSERT INTO mytable VALUES (1,'Finished except pouring water on witch');

1 row created.

SQL> INSERT INTO mytable VALUES (2,'Finished except clicking ruby-slipper heels');

1 row created.

SQL> INSERT INTO mytable VALUES (3,'You shall (not?) pass');

1 row created.

SQL> INSERT INTO mytable VALUES (4,'Done');

1 row created.

SQL> INSERT INTO mytable VALUES (5,'Done with it.');

1 row created.

SQL> INSERT INTO mytable VALUES (6,'In Progress');

1 row created.

SQL> INSERT INTO mytable VALUES (7,'In progress, OK?');

1 row created.

SQL> INSERT INTO mytable VALUES (8,'In Progress Check Back In Three Days'' Time');

1 row created.

SQL> SELECT *
  2  FROM   mytable m
  3  WHERE  +1 NOT IN (INSTR(m.status,'Done')
  4            ,       INSTR(m.status,'Finished except')
  5            ,       INSTR(m.status,'In Progress'));

        ID STATUS
---------- --------------------------------------------------
         3 You shall (not?) pass
         7 In progress, OK?

SQL>

How to connect from windows command prompt to mysql command line

Following commands will connect to any MySQL database

shell> mysql --host=localhost --user=myname --password=mypass mydb

or

shell> mysql -h localhost -u myname -pmypass mydb

Since it shows the password in plain text, you can type password later as prompted. So, the command will be as follows

shell> mysql --host=localhost --user=myname --password mydb
shell> mysql -h localhost -u myname -p mydb

HTML5 Video not working in IE 11

I've been having similar issues of a video not playing in IE11 on Windows 8.1. What I didn't realize was that I was running an N version of Windows, meaning no media features were installed. After installing the Media Feature Pack for N and KN versions of Windows 8.1 and rebooting my PC it was working fine.

As a side-note, the video worked fine in Chrome, Firefox, etc, since those browsers properly fell back to the webm file.

How to check if mod_rewrite is enabled in php?

Copy this piece of code and run it to find out.


<?php
 if(!function_exists('apache_get_modules') ){ phpinfo(); exit; }
 $res = 'Module Unavailable';
 if(in_array('mod_rewrite',apache_get_modules())) 
 $res = 'Module Available';
?>
<html>
<head>
<title>A mod_rewrite availability check !</title></head>
<body>
<p><?php echo apache_get_version(),"</p><p>mod_rewrite $res"; ?></p>
</body>
</html>

What is the difference between MacVim and regular Vim?

MacVim is just Vim. Anything you are used to do in Vim will work exactly the same way in MacVim.

MacVim is more integrated in the whole OS than Vim in the Terminal or even GVim in Linux, it follows a lot of Mac OS X's conventions.

If you work mainly with GUI apps (YummyFTP + GitX + Charles, for example) you may prefer MacVim.

If you work mainly with CLI apps (ssh + svn + tcpdump, for example) you may prefer vim in the terminal.

Entering and leaving one realm (CLI) for the other (GUI) and vice-versa can be "expensive".

I use both MacVim and Vim depending on the task and the context: if I'm in CLI-land I'll just type vim filename and if I'm in GUI-land I'll just invoke Quicksilver and launch MacVim.

When I switched from TextMate I kind of liked the fact that MacVim supported almost all of the regular shortcuts Mac users are accustomed to. I added some of my own, mimiking TextMate but, since I was working in multiple environments I forced my self to learn the vim way. Now I use both MacVim and Vim almost exactly the same way. Using one or the other is just a question of context for me.

Also, like El Isra said, the default vim (CLI) in OS X is slightly outdated. You may install an up-to-date version via MacPorts or you can install MacVim and add an alias to your .profile:

alias vim='/path/to/MacVim.app/Contents/MacOS/Vim'

to have the same vim in MacVim and Terminal.app.

Another difference is that many great colorschemes out there work out of the box in MacVim but look terrible in the Terminal.app which only supports 8 colors (+ highlights) but you can use iTerm — which can be set up to support 256 colors — instead of Terminal.

So… basically my advice is to just use both.

EDIT: I didn't try it but the latest version of Terminal.app (in 10.7) is supposed to support 256 colors. I'm still on 10.6.x at work so I'll still use iTerm2 for a while.

EDIT: An even better way to use MacVim's CLI executable in your shell is to move the mvim script bundled with MacVim somewhere in your $PATH and use this command:

$ mvim -v

EDIT: Yes, Terminal.app now supports 256 colors. So if you don't need iTerm2's advanced features you can safely use the default terminal emulator.

Error: Configuration with name 'default' not found in Android Studio

If suppose you spotted this error after removing certain node modules, ideally should not be present the library under build.gradle(Module:app) . It can be removed manually and sync the project again.

How to ensure a <select> form field is submitted when it is disabled?

Same solution suggested by Tres without using jQuery

<form onsubmit="document.getElementById('mysel').disabled = false;" action="..." method="GET">

   <select id="mysel" disabled="disabled">....</select>

   <input name="submit" id="submit" type="submit" value="SEND FORM">
</form>

This might help someone understand more, but obviously is less flexible than the jQuery one.

Node JS Error: ENOENT

To expand a bit on why the error happened: A forward slash at the beginning of a path means "start from the root of the filesystem, and look for the given path". No forward slash means "start from the current working directory, and look for the given path".

The path

/tmp/test.jpg

thus translates to looking for the file test.jpg in the tmp folder at the root of the filesystem (e.g. c:\ on windows, / on *nix), instead of the webapp folder. Adding a period (.) in front of the path explicitly changes this to read "start from the current working directory", but is basically the same as leaving the forward slash out completely.

./tmp/test.jpg = tmp/test.jpg

Representing EOF in C code?

EOF is not a character. It can't be: A (binary) file can contain any character. Assume you have a file with ever-increasing bytes, going 0 1 2 3 ... 255 and once again 0 1 ... 255, for a total of 512 bytes. Whichever one of those 256 possible bytes you deem EOF, the file will be cut short.

That's why getchar() et al. return an int. The range of possible return values are those that a char can have, plus a genuine int value EOF (defined in stdio.h). That's also why converting the return value to a char before checking for EOF will not work.

Note that some protocols have "EOF" "characters." ASCII has "End of Text", "End of Transmission", "End of Transmission Block" and "End of Medium". Other answers have mentioned old OS'es. I myself input ^D on Linux and ^Z on Windows consoles to stop giving programs input. (But files read via pipes can have ^D and ^Z characters anywhere and only signal EOF when they run out of bytes.) C strings are terminated with the '\0' character, but that also means they cannot contain the character '\0'. That's why all C non-string data functions work using a char array (to contain the data) and a size_t (to know where the data ends).

Edit: The C99 standard §7.19.1.3 states:

The macros are [...]
EOF
which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-?le, that is, no more input from a stream;

How to submit a form with JavaScript by clicking a link?

here's the best solution to your question: inside the form you have these code:

<li><a href="#">Singup</a></li>
<button type="submit" id="haha"></button>

in the CSS file, do this:

button{
  display: none;
}

in JS you do this:

$("a").click(function(){
   $("button").trigger("click");
})

There you go.

POST unchecked HTML checkboxes

function SubmitCheckBox(obj) {
     obj.value   = obj.checked ? "on" : "off";
     obj.checked = true;
     return obj.form.submit();
}

<input type=checkbox name="foo" onChange="return SubmitCheckBox(this);">

Initialize Array of Objects using NSArray

This might not really answer the question, but just in case someone just need to quickly send a string value to a function that require a NSArray parameter.

NSArray *data = @[@"The String Value"];

if you need to send more than just 1 string value, you could also use

NSArray *data = @[@"The String Value", @"Second String", @"Third etc"];

then you can send it to the function like below

theFunction(data);

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

Anyone facing this while using cmake build, the solution is to make sure you have included the four supported platforms in your app module's android{} block:

 externalNativeBuild {
            cmake {
                cppFlags "-std=c++14"
                abiFilters "arm64-v8a", "x86", "armeabi-v7a", "x86_64"
            }
        }

Single Line Nested For Loops

Below code for best examples for nested loops, while using two for loops please remember the output of the first loop is input for the second loop. Loop termination also important while using the nested loops

for x in range(1, 10, 1):
     for y in range(1,x):
             print y,
        print
OutPut :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8

Hadoop "Unable to load native-hadoop library for your platform" warning

Just append word native to your HADOOP_OPTS like this:

export HADOOP_OPTS="$HADOOP_OPTS -Djava.library.path=$HADOOP_HOME/lib/native"

PS: Thank Searene

Removing elements with Array.map in JavaScript

Array Filter method

_x000D_
_x000D_
var arr = [1, 2, 3]_x000D_
_x000D_
// ES5 syntax_x000D_
arr = arr.filter(function(item){ return item != 3 })_x000D_
_x000D_
// ES2015 syntax_x000D_
arr = arr.filter(item => item != 3)_x000D_
_x000D_
console.log( arr )
_x000D_
_x000D_
_x000D_

Select max value of each group

SELECT DISTINCT (t1.ProdId), t1.Quantity FROM Dummy t1 INNER JOIN
       (SELECT ProdId, MAX(Quantity) as MaxQuantity FROM Dummy GROUP BY ProdId) t2
    ON t1.ProdId = t2.ProdId
   AND t1.Quantity = t2.MaxQuantity
 ORDER BY t1.ProdId

this will give you the idea.

Retrofit 2 - Dynamic URL

If you already have your code setup and you don’t want to make changes on the different interfaces you can, use the solution described in this link. The main point is the method changeApiBaseUrl that updates the URL and recreates the Retrofit builder.

public class ServiceGenerator {  
public static String apiBaseUrl = "http://futurestud.io/api";
private static Retrofit retrofit;

private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(apiBaseUrl);

private static OkHttpClient.Builder httpClient =
        new OkHttpClient.Builder();

// No need to instantiate this class.
private ServiceGenerator() {
}

public static void changeApiBaseUrl(String newApiBaseUrl) {
    apiBaseUrl = newApiBaseUrl;

    builder = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(apiBaseUrl);
}

public static <S> S createService(Class<S> serviceClass, AccessToken token) {
    String authToken = token.getTokenType().concat(token.getAccessToken());
    return createService(serviceClass, authToken);
}

// more methods
// ...
}

You can use it as follows:

public class DynamicBaseUrlActivity extends AppCompatActivity {

public static final String TAG = "CallInstances";
private Callback<ResponseBody> downloadCallback;

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

    downloadCallback = new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d(TAG, "server contacted at: " + call.request().url());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d(TAG, "call failed against the url: " + call.request().url());
        }
    };

    // first request
    FileDownloadService downloadService = ServiceGenerator.create(FileDownloadService.class);
    Call<ResponseBody> originalCall = downloadService.downloadFileWithFixedUrl();
    originalCall.enqueue(downloadCallback);

    // change base url
    ServiceGenerator.changeApiBaseUrl("http://development.futurestud.io/api");

    // new request against new base url
    FileDownloadService newDownloadService = ServiceGenerator.create(FileDownloadService.class);
    Call<ResponseBody> newCall = newDownloadService.downloadFileWithFixedUrl();
    newCall.enqueue(downloadCallback);
    }
}

Convert boolean result into number/integer

When JavaScript is expecting a number value but receives a boolean instead it converts that boolean into a number: true and false convert into 1 and 0 respectively. So you can take advantage of this;

_x000D_
_x000D_
var t = true;_x000D_
var f = false;_x000D_
_x000D_
console.log(t*1); // t*1 === 1_x000D_
console.log(f*1); // f*1 === 0 _x000D_
_x000D_
console.log(+t); // 0+t === 1 or shortened to +t === 1_x000D_
console.log(+f); //0+f === 0 or shortened to +f === 0
_x000D_
_x000D_
_x000D_

Further reading Type Conversions Chapter 3.8 of The Definitive Guide to Javascript.

Stopping Docker containers by image name - Ubuntu

Adding on top of @VonC superb answer, here is a ZSH function that you can add into your .zshrc file:

dockstop() {
  docker rm $(docker stop $(docker ps -a -q --filter ancestor="$1" --format="{{.ID}}"))
}

Then in your command line, simply do dockstop myImageName and it will stop and remove all containers that were started from an image called myImageName.

R command for setting working directory to source file location in Rstudio

I realize that this is an old thread, but I had a similar problem with needing to set the working directory and couldn't get any of the solutions to work for me. Here's what did work, in case anyone else stumbles across this later on:

# SET WORKING DIRECTORY TO CURRENT DIRECTORY:
system("pwd=`pwd`; $pwd 2> dummyfile.txt")
dir <- fread("dummyfile.txt")
n<- colnames(dir)[2]
n2 <- substr(n, 1, nchar(n)-1)
setwd(n2)

It's a bit convoluted, but basically this uses system commands to get the working directory and save it to dummyfile.txt, then R reads that file using data.table::fread. The rest is just cleaning up what got printed to the file so that I'm left with just the directory path.

I needed to run R on a cluster, so there was no way to know what directory I'd end up in (jobs get assigned a number and a compute node). This did the trick for me.

Auto-increment on partial primary key with Entity Framework Core

Specifying the column type as serial for PostgreSQL to generate the id.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order=1, TypeName="serial")]
public int ID { get; set; }

https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL

How store a range from excel into a Range variable?

What is currentWorksheet? It works if you use the built-in ActiveSheet.

dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

error: package com.android.annotations does not exist

In my case I had to use

import androidx.annotation...

instead of

import android.annotation...

I migrated to AndroidX and forgot to change that.

Cannot find or open the PDB file in Visual Studio C++ 2010

you just add the path of .pdb to work directory of VS!

Use :hover to modify the css of another class?

There are two approaches you can take, to have a hovered element affect (E) another element (F):

  1. F is a child-element of E, or
  2. F is a later-sibling (or sibling's descendant) element of E (in that E appears in the mark-up/DOM before F):

To illustrate the first of these options (F as a descendant/child of E):

.item:hover .wrapper {
    color: #fff;
    background-color: #000;
}?

To demonstrate the second option, F being a sibling element of E:

.item:hover ~ .wrapper {
    color: #fff;
    background-color: #000;
}?

In this example, if .wrapper was an immediate sibling of .item (with no other elements between the two) you could also use .item:hover + .wrapper.

JS Fiddle demonstration.

References:

How to append data to div using JavaScript?

java script

document.getElementById("divID").html("this text will be added to div");

jquery

$("#divID").html("this text will be added to div");

Use .html() without any arguments to see that you have entered. You can use the browser console to quickly test these functions before using them in your code.

How do I negate a test with regular expressions in a bash script?

I like to simplify the code without using conditional operators in such cases:

TEMP=/mnt/silo/bin
[[ ${PATH} =~ ${TEMP} ]] || PATH=$PATH:$TEMP

How to include js file in another js file?

It is not possible directly. You may as well write some preprocessor which can handle that.

If I understand it correctly then below are the things that can be helpful to achieve that:

  • Use a pre-processor which will run through your JS files for example looking for patterns like "@import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)

  • If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.

  • Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.

JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( @import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".

Hope it helps.

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

Live video streaming using Java?

You could always check out JMF (Java Media Framework). It is pretty old and abandoned, but it works and I've used it for apps before. Looks like it handles what you're asking for.

Moment JS - check if a date is today or in the future

check with following:

let isContinue = moment().diff('2020-04-04T20:06:11+05:30')/1000

it is returning in seconds..

If will check as 2 mins condition then

if (isContinue < 120) {
  ..To check otp details or further logic
} else {
   // otp is getting invalid
}

Can I obtain method parameter name using Java reflection?

While it is not possible (as others have illustrated), you could use an annotation to carry over the parameter name, and obtain that though reflection.

Not the cleanest solution, but it gets the job done. Some webservices actually do this to keep parameter names (ie: deploying WSs with glassfish).

Get the contents of a table row with a button click

The object of the exercise is to find the row that contains the information. When we get there, we can easily extract the required information.

Answer

$(".use-address").click(function() {
    var $item = $(this).closest("tr")   // Finds the closest row <tr> 
                       .find(".nr")     // Gets a descendent with class="nr"
                       .text();         // Retrieves the text within <td>

    $("#resultas").append($item);       // Outputs the answer
});

VIEW DEMO

Now let's focus on some frequently asked questions in such situations.

How to find the closest row?

Using .closest():

var $row = $(this).closest("tr");

Using .parent():

You can also move up the DOM tree using .parent() method. This is just an alternative that is sometimes used together with .prev() and .next().

var $row = $(this).parent()             // Moves up from <button> to <td>
                  .parent();            // Moves up from <td> to <tr>

Getting all table cell <td> values

So we have our $row and we would like to output table cell text:

var $row = $(this).closest("tr"),       // Finds the closest row <tr> 
    $tds = $row.find("td");             // Finds all children <td> elements

$.each($tds, function() {               // Visits every single <td> element
    console.log($(this).text());        // Prints out the text within the <td>
});

VIEW DEMO

Getting a specific <td> value

Similar to the previous one, however we can specify the index of the child <td> element.

var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
    $tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element

$.each($tds, function() {                // Visits every single <td> element
    console.log($(this).text());         // Prints out the text within the <td>
});

VIEW DEMO

Useful methods

  • .closest() - get the first element that matches the selector
  • .parent() - get the parent of each element in the current set of matched elements
  • .parents() - get the ancestors of each element in the current set of matched elements
  • .children() - get the children of each element in the set of matched elements
  • .siblings() - get the siblings of each element in the set of matched elements
  • .find() - get the descendants of each element in the current set of matched elements
  • .next() - get the immediately following sibling of each element in the set of matched elements
  • .prev() - get the immediately preceding sibling of each element in the set of matched elements

_tkinter.TclError: no display name and no $DISPLAY environment variable

You can solve it by adding these two lines in the VERY beginning of your .py script.

import matplotlib
matplotlib.use('Agg')

PS: The error will still exists if these two lines are not added in the very beginning of the source code.

python's re: return True if string contains regex pattern

import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
  print 'matched'

Python logging not outputting anything

For anyone here that wants a super-simple answer: just set the level you want displayed. At the top of all my scripts I just put:

import logging
logging.basicConfig(level = logging.INFO)

Then to display anything at or above that level:

logging.info("Hi you just set your fleeb to level plumbus")

It is a hierarchical set of five levels so that logs will display at the level you set, or higher. So if you want to display an error you could use logging.error("The plumbus is broken").

The levels, in increasing order of severity, are DEBUG, INFO, WARNING, ERROR, and CRITICAL. The default setting is WARNING.

This is a good article containing this information expressed better than my answer:
https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3

Import Certificate to Trusted Root but not to Personal [Command Line]

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx this works but still a password is needed to be typed in manually for private key. Including -p and "password" cause error too many arguments for certutil on XP

Converting PKCS#12 certificate into PEM using OpenSSL

Try:

openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys
openssl pkcs12 -in path.p12 -out newfile.key.pem -nocerts -nodes

After that you have:

  • certificate in newfile.crt.pem
  • private key in newfile.key.pem

To put the certificate and key in the same file without a password, use the following, as an empty password will cause the key to not be exported:

openssl pkcs12 -in path.p12 -out newfile.pem -nodes

Or, if you want to provide a password for the private key, omit -nodes and input a password:

openssl pkcs12 -in path.p12 -out newfile.pem

If you need to input the PKCS#12 password directly from the command line (e.g. a script), just add -passin pass:${PASSWORD}:

openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys -passin 'pass:P@s5w0rD'

Set Canvas size using javascript

Try this:

var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
xS = w.innerWidth || e.clientWidth || g.clientWidth,
yS = w.innerHeight|| e.clientHeight|| g.clientHeight;
alert(xS + ' × ' + yS);

document.write('')

works for iframe and well.

What is a StackOverflowError?

Like you say, you need to show some code. :-)

A stack overflow error usually happens when your function calls nest too deeply. See the Stack Overflow Code Golf thread for some examples of how this happens (though in the case of that question, the answers intentionally cause stack overflow).

How can I invert color using CSS?

I think the only way to handle this is to use JavaScript

Try this Invert text color of a specific element

If you do this with css3 it's only compatible with the newest browser versions.

ImportError: No module named 'selenium'

If you have pip installed you can install selenium like so.

pip install selenium

or depending on your permissions:

sudo pip install selenium

For python3:

sudo pip3 install selenium

As you can see from this question pip vs easy_install pip is a more reliable package installer as it was built to improve easy_install.

I would also suggest that when creating new projects you do so in virtual environments, even a simple selenium project. You can read more about virtual environments here. In fact pip is included out of the box with virtualenv!

Resource from src/main/resources not found after building with maven

FileReader reads from files on the file system.

Perhaps you intended to use something like this to load a file from the class path

// this will look in src/main/resources before building and myjar.jar! after building.
InputStream is = MyClass.class.getClassloader()
                     .getResourceAsStream("config.txt");

Or you could extract the file from the jar before reading it.

Passing html values into javascript functions

Here is the JSfiddle Demo

I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order so you can check if it's greater than zero:

<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p> 

function verifyorder() {
        var order = document.getElementById('value').value;
        if (+order > 0) {
            alert(+order);
            return true;
        }
        else {
            alert("Sorry, you need to enter a positive integer value, try again");
            document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
        }
    }

How can I set response header on express.js assets

Short Answer:

  • res.setHeaders - calls the native Node.js method

  • res.set - sets headers

  • res.headers - an alias to res.set

How can I check if a View exists in a Database?

For people checking the existence to drop View use this

From SQL Server 2016 CTP3 you can use new DIE statements instead of big IF wrappers

syntax

DROP VIEW [ IF EXISTS ] [ schema_name . ] view_name [ ...,n ] [ ; ]

Query :

DROP VIEW IF EXISTS view_name

More info here

Pandas: ValueError: cannot convert float NaN to integer

if you have null value then in doing mathematical operation you will get this error to resolve it use df[~df['x'].isnull()]df[['x']].astype(int) if you want your dataset to be unchangeable.

Regular expression to match standard 10 digit phone number

I find this regular expression most useful for me for 10 digit contact number :

^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$

Reference: https://regex101.com/r/QeQewP/1

Explanation:

enter image description here

How to get an object's methods?

You can use console.dir(object) to write that objects properties to the console.

Parse an URL in JavaScript

If your string is called s then

var id = s.match(/img_id=([^&]+)/)[1]

will give it to you.

MySQL how to join tables on two fields

JOIN t2 ON (t2.id = t1.id AND t2.date = t1.date)

How do I fetch only one branch of a remote Git repository?

The simplest way to do that

  git fetch origin <branch> && git checkout <branch>

Example: I want to fetch uat branch from origin and switch to this as the current working branch.

   git fetch origin uat && git checkout uat

What command shows all of the topics and offsets of partitions in Kafka?

You might want to try kt. It's also quite faster than the bundled kafka-topics.

This is the current most complete info description you can get out of a topic with kt:

kt topic -brokers localhost:9092 -filter my_topic_name -partitions -leaders -replicas

It also outputs as JSON, so you can pipe it to jq for further flexibility.

ASP.Net MVC: How to display a byte array image from model

You need to have a byte[] in your DB.

My byte[] is in my Person object:

public class Person
{
    public byte[] Image { get; set; }
}


You need to convert your byte[] in a String. So, I have in my controller :

String img = Convert.ToBase64String(person.Image);


Next, in my .cshtml file, my Model is a ViewModel. This is what I have in :

 public String Image { get; set; }


I use it like this in my .cshtml file:

<img src="@String.Format("data:image/jpg;base64,{0}", Model.Image)" />

"data:image/image file extension;base64,{0}, your image String"

I wish it will help someone !

onclick go full screen

so simple try this

_x000D_
_x000D_
<div dir="ltr" style="text-align: left;" trbidi="on">_x000D_
<!-- begin snippet: js hide: false console: true babel: null -->
_x000D_
_x000D_
_x000D_

Make the current commit the only (initial) commit in a Git repository?

Variant of larsmans's proposed method:

Save your untrackfiles list:

git ls-files --others --exclude-standard > /tmp/my_untracked_files

Save your git configuration:

mv .git/config /tmp/

Then perform larsmans's first steps:

rm -rf .git
git init
git add .

Restore your config:

mv /tmp/config .git/

Untrack you untracked files:

cat /tmp/my_untracked_files | xargs -0 git rm --cached

Then commit:

git commit -m "Initial commit"

And finally push to your repository:

git push -u --force origin master

How do I use itertools.groupby()?

This basic implementation helped me understand this function. Hope it helps others as well:

arr = [(1, "A"), (1, "B"), (1, "C"), (2, "D"), (2, "E"), (3, "F")]

for k,g in groupby(arr, lambda x: x[0]):
    print("--", k, "--")
    for tup in g:
        print(tup[1])  # tup[0] == k
-- 1 --
A
B
C
-- 2 --
D
E
-- 3 --
F

How do I send a POST request as a JSON?

You have to add header,or you will get http 400 error. The code works well on python2.6,centos5.4

code:

    import urllib2,json

    url = 'http://www.google.com/someservice'
    postdata = {'key':'value'}

    req = urllib2.Request(url)
    req.add_header('Content-Type','application/json')
    data = json.dumps(postdata)

    response = urllib2.urlopen(req,data)

What's the difference between integer class and numeric class in R

There are multiple classes that are grouped together as "numeric" classes, the 2 most common of which are double (for double precision floating point numbers) and integer. R will automatically convert between the numeric classes when needed, so for the most part it does not matter to the casual user whether the number 3 is currently stored as an integer or as a double. Most math is done using double precision, so that is often the default storage.

Sometimes you may want to specifically store a vector as integers if you know that they will never be converted to doubles (used as ID values or indexing) since integers require less storage space. But if they are going to be used in any math that will convert them to double, then it will probably be quickest to just store them as doubles to begin with.

increase font size of hyperlink text html

You can do like this:

a {font-size: 100px}

Try avoid using font tag because it's deprecated. Use CSS like above instead. You can give your anchors specific class and apply any style for them.

What are the differences between .gitignore and .gitkeep?

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