Programs & Examples On #Lpbyte

Shorter syntax for casting from a List<X> to a List<Y>?

dynamic data = List<x> val;  
List<y> val2 = ((IEnumerable)data).Cast<y>().ToList();

How to Allow Remote Access to PostgreSQL database

In order to remotely access a PostgreSQL database, you must set the two main PostgreSQL configuration files:

postgresql.conf
pg_hba.conf

Here is a brief description about how you can set them (note that the following description is purely indicative: To configure a machine safely, you must be familiar with all the parameters and their meanings)

First of all configure PostgreSQL service to listen on port 5432 on all network interfaces in Windows 7 machine:
open the file postgresql.conf (usually located in C:\Program Files\PostgreSQL\9.2\data) and sets the parameter

listen_addresses = '*'

Check the network address of WindowsXP virtual machine, and sets parameters in pg_hba.conf file (located in the same directory of postgresql.conf) so that postgresql can accept connections from virtual machine hosts.
For example, if the machine with Windows XP have 192.168.56.2 IP address, add in the pg_hba.conf file:

host all all 192.168.56.1/24 md5

this way, PostgreSQL will accept connections from all hosts on the network 192.168.1.XXX.

Restart the PostgreSQL service in Windows 7 (Services-> PosgreSQL 9.2: right click and restart sevice). Install pgAdmin on windows XP machine and try to connect to PostgreSQL.

Why is enum class preferred over plain enum?

C++ has two kinds of enum:

  1. enum classes
  2. Plain enums

Here are a couple of examples on how to declare them:

 enum class Color { red, green, blue }; // enum class
 enum Animal { dog, cat, bird, human }; // plain enum 

What is the difference between the two?

  • enum classes - enumerator names are local to the enum and their values do not implicitly convert to other types (like another enum or int)

  • Plain enums - where enumerator names are in the same scope as the enum and their values implicitly convert to integers and other types

Example:

enum Color { red, green, blue };                    // plain enum 
enum Card { red_card, green_card, yellow_card };    // another plain enum 
enum class Animal { dog, deer, cat, bird, human };  // enum class
enum class Mammal { kangaroo, deer, human };        // another enum class

void fun() {

    // examples of bad use of plain enums:
    Color color = Color::red;
    Card card = Card::green_card;

    int num = color;    // no problem

    if (color == Card::red_card) // no problem (bad)
        cout << "bad" << endl;

    if (card == Color::green)   // no problem (bad)
        cout << "bad" << endl;

    // examples of good use of enum classes (safe)
    Animal a = Animal::deer;
    Mammal m = Mammal::deer;

    int num2 = a;   // error
    if (m == a)         // error (good)
        cout << "bad" << endl;

    if (a == Mammal::deer) // error (good)
        cout << "bad" << endl;

}

Conclusion:

enum classes should be preferred because they cause fewer surprises that could potentially lead to bugs.

How to read files from resources folder in Scala?

Resources in Scala work exactly as they do in Java. It is best to follow the Java best practices and put all resources in src/main/resources and src/test/resources.

Example folder structure:

testing_styles/
+-- build.sbt
+-- src
¦   +-- main
¦       +-- resources
¦       ¦   +-- readme.txt

Scala 2.12.x && 2.13.x reading a resource

To read resources the object Source provides the method fromResource.

import scala.io.Source
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines

reading resources prior 2.12 (still my favourite due to jar compatibility)

To read resources you can use getClass.getResource and getClass.getResourceAsStream .

val stream: InputStream = getClass.getResourceAsStream("/readme.txt")
val lines: Iterator[String] = scala.io.Source.fromInputStream( stream ).getLines

nicer error feedback (2.12.x && 2.13.x)

To avoid undebuggable Java NPEs, consider:

import scala.util.Try
import scala.io.Source
import java.io.FileNotFoundException

object Example {

  def readResourceWithNiceError(resourcePath: String): Try[Iterator[String]] = 
    Try(Source.fromResource(resourcePath).getLines)
      .recover(throw new FileNotFoundException(resourcePath))
 }

good to know

Keep in mind that getResourceAsStream also works fine when the resources are part of a jar, getResource, which returns a URL which is often used to create a file can lead to problems there.

in Production

In production code I suggest to make sure that the source is closed again.

Leverage browser caching, how on apache or .htaccess?

I was doing the same thing a couple days ago. Added this to my .htaccess file:

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif¦jpe?g¦png¦ico¦css¦js¦swf)$">
Header set Cache-Control "public"
</FilesMatch>

And now when I run google speed page, leverage browwer caching is no longer a high priority.

Hope this helps.

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

Ok, I finally resolved this, by completely de-installing Android-Studio, and then installing the latest (0.2.0) from scratch.

EDIT: I also had to use the Android SDK-Manager, and install the component in the 'Extras' section called the Android Support Repository (as mentioned elsewhere).

Note: This does NOT fix my old existing project...that one still will not build, as indicated above.

But, it DOES solve the issue of now being able to at least create NEW projects going forward, that build ok using 'Gradle'. (So, basically, I re-created my proj from scratch under a new name, and copied all my code and project xml-files, etc, from the old project, into the newly-created one.)

[As an aside: I've got an idea, Google! Why don't you refer to versions of Android-Studio using numbers like 0.1.9 and 0.2.0, but then when users click on 'About' menu item, or search elsewhere for what version they are running, you could baffle them with crap like 'the July 11th build' or aka, some build number with 6 or 8 digits of numbering, and make them wonder what version they actually have! That will keep the developers guessing...really will sort the wheat from the chaff, etc.]

For example, I originally installed a kit named: android-studio-bundle-130.687321-windows.exe

Today, I got the "0.2.0" kit???, and it has a name like: android-studio-bundle-130.737825-windows.exe

Yep, this version #ing system is about as clear as mud.
Why bother with the illusion of version#s, when you don't use them!!!???

Optimistic vs. Pessimistic locking

Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.

If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.

This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.

Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection.

In the latter case you open the transaction with the TxID and then reconnect using that ID. The DBMS maintains the locks and allows you to pick the session back up through the TxID. This is how distributed transactions using two-phase commit protocols (such as XA or COM+ Transactions) work.

How can I check out a GitHub pull request with git?

If you're following the "github fork" workflow, where you create a fork and add the remote upstream repo:

14:47 $ git remote -v
origin  [email protected]:<yourname>/<repo_name>.git (fetch)
origin  [email protected]:<yourname>/<repo_name>.git (push)
upstream        [email protected]:<repo_owrer>/<repo_name>.git (fetch)
upstream        [email protected]:<repo_owner>/<repo_name>.git (push)

to pull into your current branch your command would look like:

git pull upstream pull/<pull_request_number>/head

to pull into a new branch the code would look like:

git fetch upstream pull/<pull_request_number>/head:newbranch

How to set a class attribute to a Symfony2 form input

You can do it with FormBuilder. Add this to the array in your FormBuilder:

'attr'=> array('class'=>'span2')

System has not been booted with systemd as init system (PID 1). Can't operate

This worked for me (using WSL)

sudo /etc/init.d/redis start

(for any other service, check the init.d folder for filenames)

Get the distance between two geo points

you can get distance and time using google Map API Google Map API

just pass downloaded JSON to this method you will get real time Distance and Time between two latlong's

void parseJSONForDurationAndKMS(String json) throws JSONException {

    Log.d(TAG, "called parseJSONForDurationAndKMS");
    JSONObject jsonObject = new JSONObject(json);
    String distance;
    String duration;
    distance = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text");
    duration = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("duration").getString("text");

    Log.d(TAG, "distance : " + distance);
    Log.d(TAG, "duration : " + duration);

    distanceBWLats.setText("Distance : " + distance + "\n" + "Duration : " + duration);


}

HTML - how can I show tooltip ONLY when ellipsis is activated

Here's a pure CSS solution. No need for jQuery. It won't show a tooltip, instead it'll just expand the content to its full length on mouseover.

Works great if you have content that gets replaced. Then you don't have to run a jQuery function every time.

.might-overflow {
    text-overflow: ellipsis;
    overflow : hidden;
    white-space: nowrap;
}

.might-overflow:hover {
    text-overflow: clip;
    white-space: normal;
    word-break: break-all;
}

Getting HTTP code in PHP using curl

use this hitCurl method for fetch all type of api response i.e. Get / Post

        function hitCurl($url,$param = [],$type = 'POST'){
        $ch = curl_init();
        if(strtoupper($type) == 'GET'){
            $param = http_build_query((array)$param);
            $url = "{$url}?{$param}";
        }else{
            curl_setopt_array($ch,[
                CURLOPT_POST => (strtoupper($type) == 'POST'),
                CURLOPT_POSTFIELDS => (array)$param,
            ]);
        }
        curl_setopt_array($ch,[
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
        ]);
        $resp = curl_exec($ch);
        $statusCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);
        return [
            'statusCode' => $statusCode,
            'resp' => $resp
        ];
    }

Demo function to test api

 function fetchApiData(){
        $url = 'https://postman-echo.com/get';
        $resp = $this->hitCurl($url,[
            'foo1'=>'bar1',
            'foo2'=>'bar2'
        ],'get');
        $apiData = "Getting header code {$resp['statusCode']}";
        if($resp['statusCode'] == 200){
            $apiData = json_decode($resp['resp']);
        }
        echo "<pre>";
        print_r ($apiData);
        echo "</pre>";
    }

Best practice for localization and globalization of strings and labels

When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:

  • Conceptualize the specific problem as a set of smaller sub-problems.
  • Solve each smaller problem.
  • Combine the results into a solution of the specific problem.

But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:

  • Conceptualize the specific problem as a special case of a more general problem.
  • Somehow solve the general problem.
  • Adapt the solution of the general problem to the specific problem.

- Eric Lippert

I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.

I've outlined some of the major aspects of the problem

  • Issue: We need to load data only for the desired language

    Solution: For this purpose we save data to a separate files for each language

ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)

  • Issue: Resource files for each page should be separated so we only get the data we need

    Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload

  • Issue: We need a key/value pair structure to save our data

    Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE

  • Issue: General members should be stored in a public file and all pages should access them

    Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'

  • Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope

    Solution: I considered a file for each

Application Structure

root/
    Global_Resources/
        default.js
        default.fr.js
    UserManagementSystem/
        Local_Resources/
            default.js
            default.fr.js
            createUser.js
        Login.htm
        CreateUser.htm

The corresponding code for the files:

Global_Resources/default.js

var res = {
    Create : "Create",
    Update : "Save Changes",
    Delete : "Delete"
};

Global_Resources/default.fr.js

var res = {
    Create : "créer",
    Update : "Enregistrer les modifications",
    Delete : "effacer"
};

The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.

UserManagementSystem/Local_Resources/default.js

res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";

UserManagementSystem/Local_Resources/default.fr.js

res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";

UserManagementSystem/Local_Resources/createUser.js

// Override res.Create on Global_Resources/default.js
res.Create = "Create User"; 

UserManagementSystem/Local_Resources/createUser.fr.js

// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";

manager.js file (this file should be load last)

res.lang = "fr";

var globalResourcePath = "Global_Resources";
var resourceFiles = [];

var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;

if(!IsFileExist(currentFile))
    currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");

resourceFiles.push(currentFile);

// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
    currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";

    if(!IsExist(currentFile))
        currentFile = folder + "\\Local_Resource\\default.js";
    if(!IsExist(currentFile)) throw new Exception("File Not Found");

    resourceFiles.push(currentFile);
}

for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }

// Get current page name
var pageNameWithoutExtension = "SomePage";

currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;

if(!IsExist(currentFile))
    currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");

Hope it helps :)

Display the binary representation of a number in C?

Yes (write your own), something like the following complete function.

#include <stdio.h> /* only needed for the printf() in main(). */
#include <string.h>

/* Create a string of binary digits based on the input value.
   Input:
       val:  value to convert.
       buff: buffer to write to must be >= sz+1 chars.
       sz:   size of buffer.
   Returns address of string or NULL if not enough space provided.
*/
static char *binrep (unsigned int val, char *buff, int sz) {
    char *pbuff = buff;

    /* Must be able to store one character at least. */
    if (sz < 1) return NULL;

    /* Special case for zero to ensure some output. */
    if (val == 0) {
        *pbuff++ = '0';
        *pbuff = '\0';
        return buff;
    }

    /* Work from the end of the buffer back. */
    pbuff += sz;
    *pbuff-- = '\0';

    /* For each bit (going backwards) store character. */
    while (val != 0) {
        if (sz-- == 0) return NULL;
        *pbuff-- = ((val & 1) == 1) ? '1' : '0';

        /* Get next bit. */
        val >>= 1;
    }
    return pbuff+1;
}

Add this main to the end of it to see it in operation:

#define SZ 32
int main(int argc, char *argv[]) {
    int i;
    int n;
    char buff[SZ+1];

    /* Process all arguments, outputting their binary. */
    for (i = 1; i < argc; i++) {
        n = atoi (argv[i]);
        printf("[%3d] %9d -> %s (from '%s')\n", i, n,
            binrep(n,buff,SZ), argv[i]);
    }

    return 0;
}

Run it with "progname 0 7 12 52 123" to get:

[  1]         0 -> 0 (from '0')
[  2]         7 -> 111 (from '7')
[  3]        12 -> 1100 (from '12')
[  4]        52 -> 110100 (from '52')
[  5]       123 -> 1111011 (from '123')

PHP: How to check if a date is today, yesterday or tomorrow

This worked for me, where I wanted to display keyword "today" or "yesterday" only if date was today and previous day otherwise display date in d-M-Y format

<?php
function findDayDiff($date){
   $param_date=date('d-m-Y',strtotime($date);
   $response  = $param_date;
   if($param_date==date('d-m-Y',strtotime("now"))){
       $response = 'Today';
   }else if($param_date==date('d-m-Y',strtotime("-1 days"))){
       $response = 'Yesterday'; 
   }
   return $response;
}
?>

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

Insted of

drawer.setDrawerListener(toggle);

You can use

drawer.addDrawerListener(toggle);

How do I change the color of radio buttons?

A radio button is a native element specific to each OS/browser. There is no way to change its color/style, unless you want to implement custom images or use a custom Javascript library which includes images (e.g. this - cached link)

Cast Object to Generic Type for returning

I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException.

I have the code which is pretty much the same as OP's code:

public static <T> T convertInstanceOfObject(Object o) {
    try {
       return (T) o;
    } catch (ClassCastException e) {
        return null;
    }
}

public static void main(String[] args) {
    String k = convertInstanceOfObject(345435.34);
    System.out.println(k);
}

and the corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object);
    Code:
       0: aload_0
       1: areturn
       2: astore_1
       3: aconst_null
       4: areturn
    Exception table:
       from    to  target type
           0     1     2   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #3                  // double 345435.34d
       3: invokestatic  #5                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: invokestatic  #6                  // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
       9: checkcast     #7                  // class java/lang/String
      12: astore_1
      13: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      16: aload_1
      17: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      20: return

Notice that checkcast byte code instruction happens in the main method not the convertInstanceOfObject and convertInstanceOfObject method does not have any instruction that can throw ClassCastException. Because the main method does not catch the ClassCastException hence when you execute the main method you will get a ClassCastException and not the expectation of printing null.

Now I modify the code to the accepted answer:

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
        try {
            return clazz.cast(o);
        } catch (ClassCastException e) {
            return null;
        }
    }
    public static void main(String[] args) {
        String k = convertInstanceOfObject(345435.34, String.class);
        System.out.println(k);
    }

The corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
    Code:
       0: aload_1
       1: aload_0
       2: invokevirtual #2                  // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
       5: areturn
       6: astore_2
       7: aconst_null
       8: areturn
    Exception table:
       from    to  target type
           0     5     6   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #4                  // double 345435.34d
       3: invokestatic  #6                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: ldc           #7                  // class java/lang/String
       8: invokestatic  #8                  // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
      11: checkcast     #7                  // class java/lang/String
      14: astore_1
      15: getstatic     #9                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: aload_1
      19: invokevirtual #10                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      22: return

Notice that there is an invokevirtual instruction in the convertInstanceOfObject method that calls Class.cast() method which throws ClassCastException which will be catch by the catch(ClassCastException e) bock and return null; hence, "null" is printed to console without any exception.

sqlite3.OperationalError: unable to open database file

For any one who has a problem with airflow linked to this issue.

In my case, I've initialized airflow in /root/airflow and run its scheduler as root. I used the run_as_user parameter to impersonate the web user while running task instances. However airflow was always failing to trigger my DAG with the following errors in logs:

sqlite3.OperationalError: unable to open database file
...
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file

I also found once I triggered a DAG manually, a new airflow resource directory was automatically created under /home/web. I'm not clear about this behavior, but I make it work by removing the entire airflow resources from /root, reinitializing airflow database under /home/web and running the scheduler as web under:

[root@host ~]# rm -rf airflow
[web@host ~]$ airflow initdb
[web@host ~]$ airflow scheduler -D

If you want to try this approach, I may need to backup your data before doing anything.

IF statement: how to leave cell blank if condition is false ("" does not work)

You could try this.

=IF(A1=1,B1,TRIM(" "))

If you put this formula in cell C1, then you could test if this cell is blank in another cells

=ISBLANK(C1)

You should see TRUE. I've tried on Microsoft Excel 2013. Hope this helps.

Delete all rows in an HTML table

Assign an id or a class for your tbody.

document.querySelector("#tbodyId").remove();
document.querySelectorAll(".tbodyClass").remove();

You can name your id or class how you want, not necessarily #tbodyId or .tbodyClass.

Hide all elements with class using plain Javascript

There are many ways to hide all elements which has certain class in javascript one way is to using for loop but here i want to show you other ways to doing it.

1.forEach and querySelectorAll('.classname')

document.querySelectorAll('.classname').forEach(function(el) {
   el.style.display = 'none';
});

2.for...of with getElementsByClassName

for (let element of document.getElementsByClassName("classname")){
   element.style.display="none";
}

3.Array.protoype.forEach getElementsByClassName

Array.prototype.forEach.call(document.getElementsByClassName("classname"), function(el) {
    // Do something amazing below
    el.style.display = 'none';
});

4.[ ].forEach and getElementsByClassName

[].forEach.call(document.getElementsByClassName("classname"), function (el) {
    el.style.display = 'none';
});

i have shown some of the possible ways, there are also more ways to do it, but from above list you can Pick whichever suits and easy for you.

Note: all above methods are supported in modern browsers but may be some of them will not work in old age browsers like internet explorer.

Using Cookie in Asp.Net Mvc 4

userCookie.Expires.AddDays(365); 

This line of code doesn't do anything. It is the equivalent of:

DateTime temp = userCookie.Expires.AddDays(365); 
//do nothing with temp

You probably want

userCookie.Expires = DateTime.Now.AddDays(365); 

Reading a UTF8 CSV file with Python

If you want to read a CSV File with encoding utf-8, a minimalistic approach that I recommend you is to use something like this:

with open(file_name, encoding="utf8") as csv_file:

With that statement, you can use later a CSV reader to work with.

Get form data in ReactJS

If all your inputs / textarea have a name, then you can filter all from event.target:

onSubmit(event){
  const fields = Array.prototype.slice.call(event.target)
      .filter(el => el.name)
      .reduce((form, el) => ({
        ...form,
        [el.name]: el.value,
      }), {})
}

Totally uncontrolled form without onChange methods, value, defaultValue...

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

This error message can be thrown in the application logs when the actual issue is that the oracle database server ran out of space.

After correcting the space issue, this particular error message disappeared.

Format date as dd/MM/yyyy using pipes

I am using this Temporary Solution:

import {Pipe, PipeTransform} from "angular2/core";
import {DateFormatter} from 'angular2/src/facade/intl';

@Pipe({
    name: 'dateFormat'
})
export class DateFormat implements PipeTransform {
    transform(value: any, args: string[]): any {
        if (value) {
            var date = value instanceof Date ? value : new Date(value);
            return DateFormatter.format(date, 'pt', 'dd/MM/yyyy');
        }
    }
}

Automapper missing type map configuration or unsupported mapping - Error

I was trying to map an IEnumerable to an object. This is way I got this error. Maybe it helps.

jQuery-- Populate select from json

fiddle

var $select = $('#down'); 
$select.find('option').remove();  
$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

How do I pass multiple parameters in Objective-C?

You need to delimit each parameter name with a ":" at the very least. Technically the name is optional, but it is recommended for readability. So you could write:

- (NSMutableArray*)getBusStops:(NSString*)busStop :(NSSTimeInterval*)timeInterval;

or what you suggested:

- (NSMutableArray*)getBusStops:(NSString*)busStop forTime:(NSSTimeInterval*)timeInterval;

Using stored procedure output parameters in C#

Stored Procedure.........

CREATE PROCEDURE usp_InsertContract
    @ContractNumber varchar(7)
AS
BEGIN

    INSERT into [dbo].[Contracts] (ContractNumber)
        VALUES (@ContractNumber)

    SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
END

C#

pvCommand.CommandType = CommandType.StoredProcedure;

pvCommand.Parameters.Clear();
pvCommand.Parameters.Add(new SqlParameter("@ContractNumber", contractNumber));
object uniqueId;
int id;
    try
    {
    uniqueId = pvCommand.ExecuteScalar();
     id = Convert.ToInt32(uniqueId);
    }
    catch (Exception e)
    {
        Debug.Print("  Message: {0}", e.Message);
    }
}

EDIT: "I still get back a DBNull value....Object cannot be cast from DBNull to other types. I'll take this up again tomorrow. I'm off to my other job,"

I believe the Id column in your SQL Table isn't a identity column.

enter image description here

how to change text box value with jQuery?

You could just use this very simple way

<script>
  $(function() {

    $('#cd').click(function() {
      $('#dsf').val("any thing here");
    });

  });
</script>

How many bytes in a JavaScript string?

These are 3 ways I use:

  1. TextEncoder
new TextEncoder().encode("myString").length
  1. Blob
new Blob(["myString"]).size
  1. Buffer
Buffer.byteLength("myString", 'utf8')

How to update PATH variable permanently from Windows command line?

I caution against using the command

setx PATH "%PATH%;C:\Something\bin"

to modify the PATH variable because of a "feature" of its implementation. On many (most?) installations these days the variable will be lengthy - setx will truncate the stored string to 1024 bytes, potentially corrupting the PATH (see the discussion here).

(I signed up specifically to flag this issue, and so lack the site reputation to directly comment on the answer posted on May 2 '12. My thanks to beresfordt for adding such a comment)

How to remove all non-alpha numeric characters from a string in MySQL?

None of these answers worked for me. I had to create my own function called alphanum which stripped the chars for me:

DROP FUNCTION IF EXISTS alphanum; 
DELIMITER | 
CREATE FUNCTION alphanum( str CHAR(255) ) RETURNS CHAR(255) DETERMINISTIC
BEGIN 
  DECLARE i, len SMALLINT DEFAULT 1; 
  DECLARE ret CHAR(255) DEFAULT ''; 
  DECLARE c CHAR(1);
  IF str IS NOT NULL THEN 
    SET len = CHAR_LENGTH( str ); 
    REPEAT 
      BEGIN 
        SET c = MID( str, i, 1 ); 
        IF c REGEXP '[[:alnum:]]' THEN 
          SET ret=CONCAT(ret,c); 
        END IF; 
        SET i = i + 1; 
      END; 
    UNTIL i > len END REPEAT; 
  ELSE
    SET ret='';
  END IF;
  RETURN ret; 
END | 
DELIMITER ; 

Now I can do:

select 'This works finally!', alphanum('This works finally!');

and I get:

+---------------------+---------------------------------+
| This works finally! | alphanum('This works finally!') |
+---------------------+---------------------------------+
| This works finally! | Thisworksfinally                |
+---------------------+---------------------------------+
1 row in set (0.00 sec)

Hurray!

SQL Server 2008 can't login with newly created user

You'll likely need to check the SQL Server error logs to determine the actual state (it's not reported to the client for security reasons.) See here for details.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

In my case, we had several projects in one solution and had selected a different start project than in the package manager console when running the "Update-Database" Command with Code-First Migrations. Make sure to select the proper start project.

What is the syntax for Typescript arrow functions with generics?

If you're in a .tsx file you cannot just write <T>, but this works:

const foo = <T, >(x: T) => x;

As opposed to the extends {} hack, this hack at least preserves the intent.

Convert a String to int?

Well, no. Why there should be? Just discard the string if you don't need it anymore.

&str is more useful than String when you need to only read a string, because it is only a view into the original piece of data, not its owner. You can pass it around more easily than String, and it is copyable, so it is not consumed by the invoked methods. In this regard it is more general: if you have a String, you can pass it to where an &str is expected, but if you have &str, you can only pass it to functions expecting String if you make a new allocation.

You can find more on the differences between these two and when to use them in the official strings guide.

How can I make IntelliJ IDEA update my dependencies from Maven?

Uncheck

"Work Offline"

in Settings -> Maven ! It worked for me ! :D

Using Thymeleaf when the value is null

Also worth to look at documentation for #objects build-in helper: https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#objects

There is useful: ${#objects.nullSafe(obj, default)}

Fix columns in horizontal scrolling

Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/

HTML

<h2>TableHeadFixer Fix Left Column</h2>

<div id="parent">
    <table id="fixTable" class="table">
        <thead>
            <tr>
                <th>Ano</th>
                <th>Jan</th>
                <th>Fev</th>
                <th>Mar</th>
                <th>Abr</th>
                <th>Maio</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
        </tbody>
    </table>
</div>

JS

    $(document).ready(function() {
        $("#fixTable").tableHeadFixer({"head" : false, "right" : 1}); 
    });

CSS

    #parent {
        height: 300px;
    }

    #fixTable {
        width: 1800px !important;
    }

https://jsfiddle.net/5gfuqqc4/

Node.js/Express.js App Only Works on Port 3000

In the lastest version of code with express-generator (4.13.1) app.js is an exported module and the server is started in /bin/www using app.set('port', process.env.PORT || 3001) in app.js will be overridden by a similar statement in bin/www. I just changed the statement in bin/www.

How to return data from PHP to a jQuery ajax call

Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.

$.ajax({
    type: "POST",
    url: "somescript.php",
    datatype: "html",
    data: dataString,
    success: function(data) {
        doSomething(data);
    }
});

Get file path of image on Android

Try out with mImageCaptureUri.getPath(); By Below Way :

if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  

            //Get your Image Path
            String Path=mImageCaptureUri.getPath();

            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
            knop.setVisibility(Button.VISIBLE);
            System.out.println(mImageCaptureUri);
        }  

How to create a XML object from String in Java?

try something like

public static Document loadXML(String xml) throws Exception
{
   DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
   DocumentBuilder bldr = fctr.newDocumentBuilder();
   InputSource insrc = new InputSource(new StringReader(xml));
   return bldr.parse(insrc);
}

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.

putting a php variable in a HTML form value

value="<?php echo htmlspecialchars($name); ?>"

Is std::vector copying the objects with a push_back?

From C++11 onwards, all the standard containers (std::vector, std::map, etc) support move semantics, meaning that you can now pass rvalues to standard containers and avoid a copy:

// Example object class.
class object
{
private:
    int             m_val1;
    std::string     m_val2;

public:
    // Constructor for object class.
    object(int val1, std::string &&val2) :
        m_val1(val1),
        m_val2(std::move(val2))
    {

    }
};

std::vector<object> myList;

// #1 Copy into the vector.
object foo1(1, "foo");
myList.push_back(foo1);

// #2 Move into the vector (no copy).
object foo2(1024, "bar");
myList.push_back(std::move(foo2));

// #3 Move temporary into vector (no copy).
myList.push_back(object(453, "baz"));

// #4 Create instance of object directly inside the vector (no copy, no move).
myList.emplace_back(453, "qux");

Alternatively you can use various smart pointers to get mostly the same effect:

std::unique_ptr example

std::vector<std::unique_ptr<object>> myPtrList;

// #5a unique_ptr can only ever be moved.
auto pFoo = std::make_unique<object>(1, "foo");
myPtrList.push_back(std::move(pFoo));

// #5b unique_ptr can only ever be moved.
myPtrList.push_back(std::make_unique<object>(1, "foo"));

std::shared_ptr example

std::vector<std::shared_ptr<object>> objectPtrList2;

// #6 shared_ptr can be used to retain a copy of the pointer and update both the vector
// value and the local copy simultaneously.
auto pFooShared = std::make_shared<object>(1, "foo");
objectPtrList2.push_back(pFooShared);
// Pointer to object stored in the vector, but pFooShared is still valid.

How to correctly display .csv files within Excel 2013?

Taken from https://superuser.com/questions/238944/how-to-force-excel-to-open-csv-files-with-data-arranged-in-columns

The behavior of Excel when opening CSV files heavily depends on your local settings and the selected list separator under Region and language » Formats » Advanced. By default Excel will assume every CSV was saved with that separator. Which is true as long as the CSV doesn't come from another country!

If your customers are in other countries, they may see other results then you think.

For example, here you see that a German Excel will use semicolon instead of comma like in the U.S.

Regional Settings

How to capture UIView to UIImage without loss of quality on retina display

To improve answers by @Tommy and @Dima, use the following category to render UIView into UIImage with transparent background and without loss of quality. Working on iOS7. (Or just reuse that method in implementation, replacing self reference with your image)

UIView+RenderViewToImage.h

#import <UIKit/UIKit.h>

@interface UIView (RenderToImage)

- (UIImage *)imageByRenderingView;

@end

UIView+RenderViewToImage.m

#import "UIView+RenderViewToImage.h"

@implementation UIView (RenderViewToImage)

- (UIImage *)imageByRenderingView
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

@end

How do I add a tool tip to a span element?

the "title" attribute will be used as the text for tooltip by the browser, if you want to apply style to it consider using some plugins

Is there a simple, elegant way to define singletons?

I think that forcing a class or an instance to be a singleton is overkill. Personally, I like to define a normal instantiable class, a semi-private reference, and a simple factory function.

class NothingSpecial:
    pass

_the_one_and_only = None

def TheOneAndOnly():
    global _the_one_and_only
    if not _the_one_and_only:
        _the_one_and_only = NothingSpecial()
    return _the_one_and_only

Or if there is no issue with instantiating when the module is first imported:

class NothingSpecial:
    pass

THE_ONE_AND_ONLY = NothingSpecial()

That way you can write tests against fresh instances without side effects, and there is no need for sprinkling the module with global statements, and if needed you can derive variants in the future.

How do I install soap extension?

In Ubuntu with php7.3:

sudo apt install php7.3-soap 
sudo service apache2 restart

How to convert base64 string to image?

Try this:

import base64
imgdata = base64.b64decode(imgstring)
filename = 'some_image.jpg'  # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
    f.write(imgdata)
# f gets closed when you exit the with statement
# Now save the value of filename to your database

TokenMismatchException in VerifyCsrfToken.php Line 67

By default session cookies will only be sent back to the server if the browser has a HTTPS connection. You can turn it off in your .env file (discouraged for production)

SESSION_SECURE_COOKIE=false

Or you can turn it off in config/session.php

'secure' => false,

Boolean operators ( &&, -a, ||, -o ) in Bash

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

How to solve ADB device unauthorized in Android ADB host device?

Experience With: ASUS ZENFONE

If at all you have faced Missing Driver for Asus Zenfones Follow This Link (http://donandroid.com/how-to-install-adb-interface-drivers-windows-7-xp-vista-623)

I tried with

1) Killing and starting adb server at adb cmd.

2) Switching Usb Debugging on and Off and ...

This is What WORKED with me.

Step 1:Remove Connection with Device and Close Eclipse

Step 2:Navigate to C:/Users/User_name/.android/

Step 3:You Will Find adb_key

Step 4:Just delete it.

Step 5.Connect again and System will ask you Again.

Step 6.Ask Device to remember RSA Key when it Prompts. I think its done.

If you Face The Same Problem after couple of days, just disable and enable USB debugging

How can I check whether an array is null / empty?

I tested as below. Hope it helps.

Integer[] integers1 = new Integer[10];
        System.out.println(integers1.length); //it has length 10 but it is empty. It is not null array
        for (Integer integer : integers1) {
            System.out.println(integer); //prints all 0s
        }

//But if I manually add 0 to any index, now even though array has all 0s elements
//still it is not empty
//        integers1[2] = 0;
        for (Integer integer : integers1) {
            System.out.println(integer); //Still it prints all 0s but it is not empty
            //but that manually added 0 is different
        }

//Even we manually add 0, still we need to treat it as null. This is semantic logic.

        Integer[] integers2 = new Integer[20];
        integers2 = null; //array is nullified
//        integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line. 
        if (integers2 == null) {
            System.out.println("null Array");
        }   

How do I escape a percentage sign in T-SQL?

You can use the ESCAPE keyword with LIKE. Simply prepend the desired character (e.g. '!') to each of the existing % signs in the string and then add ESCAPE '!' (or your character of choice) to the end of the query.

For example:

SELECT *
FROM prices
WHERE discount LIKE '%80!% off%'
ESCAPE '!'

This will make the database treat 80% as an actual part of the string to search for and not 80(wildcard).

MSDN Docs for LIKE

FAIL - Application at context path /Hello could not be started

I've had the same problem, was missing a slash in servlet url in web.xml

replace

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>jsonservice</url-pattern>
</servlet-mapping>

with

<servlet-mapping>
    <servlet-name>jsonservice</servlet-name>
    <url-pattern>/jsonservice</url-pattern>
</servlet-mapping>

git push rejected: error: failed to push some refs

If you are the only the person working on the project, what you can do is:

 git checkout master
 git push origin +HEAD

This will set the tip of origin/master to the same commit as master (and so delete the commits between 41651df and origin/master)

MySQL Select Multiple VALUES

Try this -

 select * from table where id in (3,4) or [name] in ('andy','paul');

Add centered text to the middle of a <hr/>-like line

Looking at above, I modified to:

CSS

.divider {
    font: 33px sans-serif;
    margin-top: 30px;
    text-align:center;
    text-transform: uppercase;
}
.divider span {
    position:relative;
}
.divider span:before, .divider span:after {
    border-top: 2px solid #000;
    content:"";
    position: absolute;
    top: 15px;
    right: 10em;
    bottom: 0;
    width: 80%;
}
.divider span:after {
    position: absolute;
    top: 15px;
    left:10em;
    right:0;
    bottom: 0;
}

HTML

<div class="divider">
    <span>This is your title</span></div>

Seems to work fine.

button image as form input submit button?

Late to the conversation...

But, why not use css? That way you can keep the button as a submit type.

html:

<input type="submit" value="go" />

css:

button, input[type="submit"] {
    background:url(/images/submit.png) no-repeat;"
}

Works like a charm.

EDIT: If you want to remove the default button styles, you can use the following css:

button, input[type="submit"]{
    color: inherit;
    border: none;
    padding: 0;
    font: inherit;
    cursor: pointer;
    outline: inherit;
}

from this SO question

convert string to number node.js

You do not have to install something.

parseInt(req.params.year, 10);

should work properly.

console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

Matplotlib scatter plot legend

2D scatter plot

Using the scatter method of the matplotlib.pyplot module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use scatterpoints=1 rather than numpoints=1 in the legend call to have only one point for each legend entry.

In the code below I've used random values rather than plotting the same range over and over, making all the plots visible (i.e. not overlapping each other).

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1])
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2])
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3])
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])

plt.legend((lo, ll, l, a, h, hh, ho),
           ('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
           scatterpoints=1,
           loc='lower left',
           ncol=3,
           fontsize=8)

plt.show()

enter image description here

3D scatter plot

To plot a scatter in 3D, use the plot method, as the legend does not support Patch3DCollection as is returned by the scatter method of an Axes3D instance. To specify the markerstyle you can include this as a positional argument in the method call, as seen in the example below. Optionally one can include argument to both the linestyle and marker parameters.

import matplotlib.pyplot as plt
from numpy.random import random
from mpl_toolkits.mplot3d import Axes3D

colors=['b', 'c', 'y', 'm', 'r']

ax = plt.subplot(111, projection='3d')

ax.plot(random(10), random(10), random(10), 'x', color=colors[0], label='Low Outlier')
ax.plot(random(10), random(10), random(10), 'o', color=colors[0], label='LoLo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[1], label='Lo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[2], label='Average')
ax.plot(random(10), random(10), random(10), 'o', color=colors[3], label='Hi')
ax.plot(random(10), random(10), random(10), 'o', color=colors[4], label='HiHi')
ax.plot(random(10), random(10), random(10), 'x', color=colors[4], label='High Outlier')

plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))

plt.show()

enter image description here

Why does .NET foreach loop throw NullRefException when collection is null?

Because a null collection is not the same thing as an empty collection. An empty collection is a collection object with no elements; a null collection is a nonexistent object.

Here's something to try: Declare two collections of any sort. Initialize one normally so that it's empty, and assign the other the value null. Then try adding an object to both collections and see what happens.

How to display and hide a div with CSS?

Html Code :

    <a id="f">Show First content!</a>
    <br/>
    <a id="s">Show Second content!!</a>
    <div class="a">Default Content</div>
    <div class="ab hideDiv">First content</div>
    <div class="abc hideDiv">Second content</div>

Script code:

$(document).ready(function() {
    $("#f").mouseover(function(){
        $('.a,.abc').addClass('hideDiv');
        $('.ab').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });

    $("#s").mouseover(function(){
        $('.a,.ab').addClass('hideDiv');
        $('.abc').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });
});

css code:

.hideDiv
{
    display:none;
}

PHP Warning: PHP Startup: ????????: Unable to initialize module

This is an old thread, but I stumbled across it when trying to solve a similar problem.

For me, I got this particular error relating to the php_wincache.dll. I was in the process of updating PHP from 5.5.38 to 5.6.31 on a Windows server. For some reason, not all of the DLL files updated with the newest versions. Most did, but some didn't.

So, if you get an error similar to this, make sure all the extensions are in place and updated.

Understanding React-Redux and mapStateToProps()

Yes, you can do this. You can also even process the state and return the object.

function mapStateToProps(state){  
  let completed = someFunction (state);
   return {
     completed : completed,  
   }
}
 

This would be useful if you want to shift the logic related to state from render function to outside of it.

Select row with most recent date per user

Query:

SQLFIDDLEExample

SELECT t1.*
FROM lms_attendance t1
WHERE t1.time = (SELECT MAX(t2.time)
                 FROM lms_attendance t2
                 WHERE t2.user = t1.user)

Result:

| ID | USER |       TIME |  IO |
--------------------------------
|  2 |    9 | 1370931664 | out |
|  3 |    6 | 1370932128 | out |
|  5 |   12 | 1370933037 |  in |

Solution which gonna work everytime:

SQLFIDDLEExample

SELECT t1.*
FROM lms_attendance t1
WHERE t1.id = (SELECT t2.id
                 FROM lms_attendance t2
                 WHERE t2.user = t1.user            
                 ORDER BY t2.id DESC
                 LIMIT 1)

std::string to float or double

You can use std::stringstream:

   #include <sstream>
   #include <string>
   template<typename T>
   T StringToNumber(const std::string& numberAsString)
   {
      T valor;

      std::stringstream stream(numberAsString);
      stream >> valor;
      if (stream.fail()) {
         std::runtime_error e(numberAsString);
         throw e;
      }
      return valor;
   }

Usage:

double number= StringToNumber<double>("0.6");

What is the easiest way to ignore a JPA field during persistence?

There are multiple solutions depending on the entity attribute type.

Basic attributes

Consider you have the following account table:

The account table

The account table is mapped to the Account entity like this:

@Entity(name = "Account")
public class Account {

    @Id
    private Long id;

    @ManyToOne
    private User owner;

    private String iban;

    private long cents;

    private double interestRate;

    private Timestamp createdOn;

    @Transient
    private double dollars;

    @Transient
    private long interestCents;

    @Transient
    private double interestDollars;

    @PostLoad
    private void postLoad() {
        this.dollars = cents / 100D;

        long months = createdOn.toLocalDateTime()
            .until(LocalDateTime.now(), ChronoUnit.MONTHS);
        double interestUnrounded = ( ( interestRate / 100D ) * cents * months ) / 12;
        this.interestCents = BigDecimal.valueOf(interestUnrounded)
            .setScale(0, BigDecimal.ROUND_HALF_EVEN).longValue();

        this.interestDollars = interestCents / 100D;
    }

    //Getters and setters omitted for brevity
}

The basic entity attributes are mapped to table columns, so properties like id, iban, cents are basic attributes.

But the dollars, interestCents, and interestDollars are computed properties, so you annotate them with @Transient to exclude them from SELECT, INSERT, UPDATE, and DELETE SQL statements.

So, for basic attributes, you need to use @Transient in order to exclude a given property from being persisted.

Associations

Assuming you have the following post and post_comment tables:

The post and post_comment tables

You want to map the latestComment association in the Post entity to the latest PostComment entity that was added.

To do that, you can use the @JoinFormula annotation:

@Entity(name = "Post")
@Table(name = "post")
public class Post {
 
    @Id
    private Long id;
 
    private String title;
 
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinFormula("(" +
        "SELECT pc.id " +
        "FROM post_comment pc " +
        "WHERE pc.post_id = id " +
        "ORDER BY pc.created_on DESC " +
        "LIMIT 1" +
    ")")
    private PostComment latestComment;
 
    //Getters and setters omitted for brevity
}

When fetching the Post entity, you can see that the latestComment is fetched, but if you want to modify it, the change is going to be ignored.

So, for associations, you can use @JoinFormula to ignore the write operations while still allowing reading the association.

@MapsId

Another way to ignore associations that are already mapped by the entity identifier is to use @MapsId.

For instance, consider the following one-to-one table relationship:

The post and post_details tables

The PostDetails entity is mapped like this:

@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {
 
    @Id
    private Long id;
 
    @Column(name = "created_on")
    private Date createdOn;
 
    @Column(name = "created_by")
    private String createdBy;
 
    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Post post;
 
    public PostDetails() {}
 
    public PostDetails(String createdBy) {
        createdOn = new Date();
        this.createdBy = createdBy;
    }
 
    //Getters and setters omitted for brevity
}

Notice that both the id attribute and the post association map the same database column, which is the post_details Primary Key column.

To exclude the id attribute, the @MapsId annotation will tell Hibernate that the post association takes care of the table Primary Key column value.

So, when the entity identifier and an association share the same column, you can use @MapsId to ignore the entity identifier attribute and use the association instead.

Using insertable = false, updatable = false

Another option is to use insertable = false, updatable = false for the association which you want to be ignored by Hibernate.

For instance, we can map the previous one-to-one association like this:

@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {

    @Id
    @Column(name = "post_id")
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne
    @JoinColumn(name = "post_id", insertable = false, updatable = false)
    private Post post;

    //Getters and setters omitted for brevity

    public void setPost(Post post) {
        this.post = post;
        if (post != null) {
            this.id = post.getId();
        }
    }
}

The insertable and updatable attributes of the @JoinColumn annotation will instruct Hibernate to ignore the post association since the entity identifier takes care of the post_id Primary Key column.

A fast way to delete all rows of a datatable at once

Here is a clean and modern way to do it using Entity FW and without SQL Injection or TSQL..

using (Entities dbe = new Entities())
{
    dbe.myTable.RemoveRange(dbe.myTable.ToList());
    dbe.SaveChanges();
}

Force "portrait" orientation mode

I think you want to add android:configChanges="orientation|keyboardHidden" to your activity? Otherwise the activity is restarted on config-change. The onConfigurationChanged would not be called then, only the onCreate

Javascript reduce() on Object

ES6 implementation: Object.entries()

const o = {
  a: {value: 1},
  b: {value: 2},
  c: {value: 3}
};

const total = Object.entries(o).reduce(function (total, pair) {
  const [key, value] = pair;
  return total + value;
}, 0);

How to define an enum with string value?

You can't - enum values have to be integral values. You can either use attributes to associate a string value with each enum value, or in this case if every separator is a single character you could just use the char value:

enum Separator
{
    Comma = ',',
    Tab = '\t',
    Space = ' '
}

(EDIT: Just to clarify, you can't make char the underlying type of the enum, but you can use char constants to assign the integral value corresponding to each enum value. The underlying type of the above enum is int.)

Then an extension method if you need one:

public string ToSeparatorString(this Separator separator)
{
    // TODO: validation
    return ((char) separator).ToString();
}

What are the uses of the exec command in shell scripts?

The exec built-in command mirrors functions in the kernel, there are a family of them based on execve, which is usually called from C.

exec replaces the current program in the current process, without forking a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;

  1. We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile, the last statement says something like:

     exec appln-program
    

    so now there is no shell to go back to. Even if appln-program crashes, the end-user cannot get to a shell, because it is not there - the exec replaced it.

  2. We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh, and everyone just put into their .login (csh start-up file) a call to ksh. While that worked, it left a stray csh process running, and the logout was two stage which could get confusing. So we changed it to exec ksh which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh is not a login-shell).

  3. Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4 etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.

You have obviously seen exec used somewhere, perhaps if you showed the code that's bugging you we could justify its use.

Edit: I realised that my answer above is incomplete. There are two uses of exec in shells like ksh and bash - used for opening file descriptors. Here are some examples:

exec 3< thisfile          # open "thisfile" for reading on file descriptor 3
exec 4> thatfile          # open "thatfile" for writing on file descriptor 4
exec 8<> tother           # open "tother" for reading and writing on fd 8
exec 6>> other            # open "other" for appending on file descriptor 6
exec 5<&0                 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4                 # copy write file descriptor 4 onto 7
exec 3<&-                 # close the read file descriptor 3
exec 6>&-                 # close the write file descriptor 6

Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec reverts to the original meaning:

  exec 3 < thisfile       # oops, overwrite the current program with command "3"

There are several ways you can use these, on ksh use read -u or print -u, on bash, for example:

read <&3
echo stuff >&4

increase font size of hyperlink text html

There is a way simpler way. You put the href in a paragraph just created for that href. For example:

HREF name

Javascript Print iframe contents only

I would not expect that to work

try instead

window.frames["printf"].focus();
window.frames["printf"].print();

and use

<iframe id="printf" name="printf"></iframe>

Alternatively try good old

var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();

if jQuery cannot hack it

Live Demo

Fatal Error :1:1: Content is not allowed in prolog

Someone should mark Johannes Weiß's comment as the answer to this question. That is exactly why xml documents can't just be loaded in a DOM Document class.

http://en.wikipedia.org/wiki/Byte_order_mark

Creating a PHP header/footer

Just create the header.php file, and where you want to use it do:

<?php
include('header.php');
?>

Same with the footer. You don't need php tags in these files if you just have html.

See more about include here:

http://php.net/manual/en/function.include.php

How can I change the remote/target repository URL on Windows?

The easiest way to tweak this in my opinion (imho) is to edit the .git/config file in your repository. Look for the entry you messed up and just tweak the URL.

On my machine in a repo I regularly use it looks like this:

KidA% cat .git/config 
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    autocflg = true
[remote "origin"]
    url = ssh://localhost:8888/opt/local/var/git/project.git
    #url = ssh://xxx.xxx.xxx.xxx:80/opt/local/var/git/project.git
    fetch = +refs/heads/*:refs/remotes/origin/*

The line you see commented out is an alternative address for the repository that I sometimes switch to simply by changing which line is commented out.

This is the file that is getting manipulated under-the-hood when you run something like git remote rm or git remote add but in this case since its only a typo you made it might make sense to correct it this way.

how to read certain columns from Excel using Pandas - Python

parse_cols is deprecated, use usecols instead

that is:

df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")

Is there a C++ decompiler?

Depending on how large and how well-written the original code was, it might be worth starting again in your favourite language (which might still be C++) and learning from any mistakes made in the last version. Didn't someone once say about writing one to throw away?

n.b. Clearly if this is a huge product, then it may not be worth the time.

How to check if an object is a certain type

Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.

First, some definitions:

  1. There are TypeNames, which are string representations of the type of an object, interface, etc. For example, Bar is a TypeName in Public Class Bar, or in Dim Foo as Bar. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described.
  2. There are System.Type objects which contain a value. This value indicates a type; just like a String would take some text or an Int would take a number, except we are storing types instead of text or numbers. Type objects contain the type definitions, as well as its corresponding TypeName.

Second, the theory:

  1. Foo.GetType() returns a Type object which contains the type for the variable Foo. In other words, it tells you what Foo is an instance of.
  2. GetType(Bar) returns a Type object which contains the type for the TypeName Bar.
  3. In some instances, the type an object has been Cast to is different from the type an object was first instantiated from. In the following example, MyObj is an Integer cast into an Object:

    Dim MyVal As Integer = 42 Dim MyObj As Object = CType(MyVal, Object)

So, is MyObj of type Object or of type Integer? MyObj.GetType() will tell you it is an Integer.

  1. But here comes the Type Of Foo Is Bar feature, which allows you to ascertain a variable Foo is compatible with a TypeName Bar. Type Of MyObj Is Integer and Type Of MyObj Is Object will both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it. More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarks

The test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.

Public Sub TestMethod1()

    Dim MyValInt As Integer = 42
    Dim MyValDble As Double = CType(MyValInt, Double)
    Dim MyObj As Object = CType(MyValDble, Object)

    Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
    Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
    Debug.Print(MyObj.GetType.ToString) 'Returns System.Double

    Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
    Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
    Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False

    Debug.Print(TypeOf MyObj Is Integer) 'Returns False
    Debug.Print(TypeOf MyObj Is Double) '# Returns True
    Debug.Print(TypeOf MyObj Is Object) '# Returns True


End Sub

EDIT

You can also use Information.TypeName(Object) to get the TypeName of a given object. For example,

Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"

Most efficient way to concatenate strings in JavaScript?

I wonder why String.prototype.concat is not getting any love. In my tests (assuming you already have an array of strings), it outperforms all other methods.

perf.link test

Test code:

const numStrings = 100;
const strings = [...new Array(numStrings)].map(() => Math.random().toString(36).substring(6));

const concatReduce = (strs) => strs.reduce((a, b) => a + b);

const concatLoop = (strs) => {
  let result = ''
  for (let i = 0; i < strings.length; i++) {
    result += strings[i];
  }
  return result;
}

// Case 1: 52,570 ops/s
concatLoop(strings);

// Case 2: 96,450 ops/s
concatReduce(strings)

// Case 3: 138,020 ops/s
strings.join('')

// Case 4: 169,520 ops/s
''.concat(...strings)

Variables declared outside function

Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global, nonlocal, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.

Here are some examples regarding global:-

>>> global_var = 5
>>> def fn():
...     print(global_var)
... 
>>> fn()
5
>>> def fn_2():
...     global_var += 2
...     print(global_var)
... 
>>> fn_2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
...     global global_var
...     global_var += 2
...     print(global_var)
... 
>>> fn_3()
7

The same patterns can be applied to nonlocal variables too, but this keyword is only available to the latter Python versions.

In case you're wondering, nonlocal is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def within a def, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...

Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner defs using the same variable names as the outer ones, which just should just be avoided to be honest.

Erasing elements from a vector

Depending on why you are doing this, using a std::set might be a better idea than std::vector.

It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.

This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.

How to install package from github repo in Yarn

I use this short format for github repositories:

yarn add github_user/repository_name#commit_hash

BackgroundWorker vs background Thread

The basic difference is, like you stated, generating GUI events from the BackgroundWorker. If the thread does not need to update the display or generate events for the main GUI thread, then it can be a simple thread.

how to permit an array with strong parameters

when you want to permit multiple array fields you will have to list array fields at last while permitting ,as given -

params.require(:questions).permit(:question, :user_id, answers: [], selected_answer: [] )

(this works)

How to use jQuery to select a dropdown option?

Use the following code if you want to select an option with a specific value:

$('select>option[value="' + value + '"]').prop('selected', true);

Change all files and folders permissions of a directory to 644/755

Easiest for me to remember is two operations:

chmod -R 644 dirName
chmod -R +X dirName

The +X only affects directories.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

I believe I have encountered the same quandary. I started encountering the problem when I changed to:

</system.web>
<httpRuntime targetFramework="4.5"/>

Which gives the error message you describe above.

adding:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

Solves the issue, but then it makes your validation controls/scripts throw Javascript runtime errors. If you change to:

</system.web>
<httpRuntime targetFramework="4.0"/>

You should be OK, but you’ll have to make sure the rest of your code does/ behaves as desired. You might also have to forgo some new features only available in 4.5 onward.

P.S. It is highly recommended that you read the following before implementing this solution. Especially, if you use Async functionality:

https://blogs.msdn.microsoft.com/webdev/2012/11/19/all-about-httpruntime-targetframework/

UPDATE April 2017: After some some experimentation and testing I have come up with a combination that works:

<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<httpRuntime targetFramework="4.5.1" />

with:

jQuery version 1.11.3

How to cast an object in Objective-C

Casting for inclusion is just as important as casting for exclusion for a C++ programmer. Type casting is not the same as with RTTI in the sense that you can cast an object to any type and the resulting pointer will not be nil.

Node.js Write a line into a .txt file

Inserting data into the middle of a text file is not a simple task. If possible, you should append it to the end of your file.

The easiest way to append data some text file is to use build-in fs.appendFile(filename, data[, options], callback) function from fs module:

var fs = require('fs')
fs.appendFile('log.txt', 'new data', function (err) {
  if (err) {
    // append failed
  } else {
    // done
  }
})

But if you want to write data to log file several times, then it'll be best to use fs.createWriteStream(path[, options]) function instead:

var fs = require('fs')
var logger = fs.createWriteStream('log.txt', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

logger.write('some data') // append string to your file
logger.write('more data') // again
logger.write('and more') // again

Node will keep appending new data to your file every time you'll call .write, until your application will be closed, or until you'll manually close the stream calling .end:

logger.end() // close string

Psql could not connect to server: No such file or directory, 5432 error?

I had similar problems just a while ago. After trying more than 5 suggestions I decided to go back to the basics and start from the beginning. Which meant removing my postgresql installation and following this guide upon re-installing postgresql. https://help.ubuntu.com/lts/serverguide/postgresql.html

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

So I solved in this way, from MySQL 5.6 to MySQL 5.5:

$ mysqldump -u username -p --compatible=mysql4 database_name > database_name.sql
$ sed -i 's/TYPE=InnoDB/ENGINE=InnoDB/g' database_name.sql

(Optional) Create a .sql.gz file:

$ gzip database_name.sql 

Explanation

$ mysqldump -u username -p --compatible=mysql4 database_name > database_name.sql

As explained in this answer, this is just the equivalent of this options from phpMyAdmin: "Database system or older MySQL server to maximize output compatibility with:" dropdown select "MYSQL 40".

$ sed -i 's/TYPE=InnoDB/ENGINE=InnoDB/g' database_name.sql

We needs this, to solve this issue:

ERROR 1064 (42000) at line 18: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TYPE=InnoDB' at line 9

ContractFilter mismatch at the EndpointDispatcher exception

I had the same issue. The problem was that I copied the code from another service as a starting point and did not change the service class in .svc file

Open the .svc file an make sure that the Service attribute is correct.

 <%@ ServiceHost Language="C#" Debug="true" Service="SME.WCF.ApplicationServices.ReportRenderer" CodeBehind="ReportRenderer.svc.cs" %>

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

PHP preg_match - only allow alphanumeric strings and - _ characters

Code:

if(preg_match('/[^a-z_\-0-9]/i', $string))
{
  echo "not valid string";
}

Explanation:

  • [] => character class definition
  • ^ => negate the class
  • a-z => chars from 'a' to 'z'
  • _ => underscore
  • - => hyphen '-' (You need to escape it)
  • 0-9 => numbers (from zero to nine)

The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z

How can I use an ES6 import in Node.js?

If you are using the modules system on the server side, you do not need to use Babel at all. To use modules in Node.js ensure that:

  1. Use a version of node that supports the --experimental-modules flag
  2. Your *.js files must then be renamed to *.mjs

That's it.

However and this is a big however, while your shinny pure ES6 code will run in an environment like Node.js (e.g., 9.5.0) you will still have the craziness of transpilling just to test. Also bear in mind that Ecma has stated that release cycles for JavaScript are going to be faster, with newer features delivered on a more regular basis. Whilst this will be no problems for single environments like Node.js, it's a slightly different proposition for browser environments. What is clear is that testing frameworks have a lot to do in catching up. You will still need to probably transpile for testing frameworks. I'd suggest using Jest.

Also be aware of bundling frameworks. You will be running into problems there.

Declare and initialize a Dictionary in Typescript

If you want to ignore a property, mark it as optional by adding a question mark:

interface IPerson {
    firstName: string;
    lastName?: string;
}

Sass Nesting for :hover does not work

You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".

http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

How do I calculate the MD5 checksum of a file in Python?

You can calculate the checksum of a file by reading the binary data and using hashlib.md5().hexdigest(). A function to do this would look like the following:

def File_Checksum_Dis(dirname):
    
    if not os.path.exists(dirname):
        print(dirname+" directory is not existing");
    
    for fname in os.listdir(dirname):
        if not fname.endswith('~'):
            fnaav = os.path.join(dirname, fname);
            fd = open(fnaav, 'rb');
            data = fd.read();
            fd.close();
        
            print("-"*70);
            print("File Name is: ",fname);          
            print(hashlib.md5(data).hexdigest())
            print("-"*70);
                

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

I had same error, I think the problem is that the error text is confusing, because its giving a false key name.

In your case It should say "There is no ViewData item of type 'IEnumerable' that has the key "Submarkets"".

My error was a misspelling in the view code (your "Submarkets"), but the error text made me go crazy.

I post this answer because I want to say people looking for this error, like I was, that the problem is that its not finding the IENumerable, but in the var that its supposed to look for it ("Submarkets" in this case), not in the one showed in error ("submarket_0").

Accepted answer is very interesting, but as you said the convention is applied if you dont specify the 2nd parameter, in this case it was specified, but the var was not found (in your case because the viewdata had not it, in my case because I misspelled the var name)

Hope this helps!

Add element to a JSON file?

alternatively you can do

iter(data).next()['f'] = var

Android and setting alpha for (image) view alpha

Use this form to ancient version of android.

ImageView myImageView;
myImageView = (ImageView) findViewById(R.id.img);

AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F);
alpha.setDuration(0); 
alpha.setFillAfter(true); 
myImageView.startAnimation(alpha);

Converting a column within pandas dataframe from int to string

In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))

In [17]: df
Out[17]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [18]: df.dtypes
Out[18]: 
A    int64
B    int64
dtype: object

Convert a series

In [19]: df['A'].apply(str)
Out[19]: 
0    0
1    2
2    4
3    6
4    8
Name: A, dtype: object

In [20]: df['A'].apply(str)[0]
Out[20]: '0'

Don't forget to assign the result back:

df['A'] = df['A'].apply(str)

Convert the whole frame

In [21]: df.applymap(str)
Out[21]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [22]: df.applymap(str).iloc[0,0]
Out[22]: '0'

df = df.applymap(str)

Xcopy Command excluding files and folders

Like Andrew said /exclude parameter of xcopy should be existing file that has list of excludes.

Documentation of xcopy says:

Using /exclude

List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

Example:

xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

and list-of-excluded-files.txt should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:

exclusion.txt

How to make an inline element appear on new line, or block element not occupy the whole line?

I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.

.feature_wrapper span {
    float: left;
    clear: left;
    display:inline
}

EDIT: now browsers have better support you can make use of the do inline-block.

.feature_wrapper span {
    display:inline-block;
    *display:inline; *zoom:1;
}

Depending on the text-align this will appear as through its inline while also acting like a block element.

Get the position of a div/span tag

For anyone needing just top or left position, slight modifications to @Nickf's readable code does the trick.

function getTopPos(el) {
    for (var topPos = 0;
        el != null;
        topPos += el.offsetTop, el = el.offsetParent);
    return topPos;
}

and

function getLeftPos(el) {
    for (var leftPos = 0;
        el != null;
        leftPos += el.offsetLeft, el = el.offsetParent);
    return leftPos;
}

Restrict varchar() column to specific values?

Personally, I'd code it as tinyint and:

  • Either: change it to text on the client, check constraint between 1 and 4
  • Or: use a lookup table with a foreign key

Reasons:

  • It will take on average 8 bytes to store text, 1 byte for tinyint. Over millions of rows, this will make a difference.

  • What about collation? Is "Daily" the same as "DAILY"? It takes resources to do this kind of comparison.

  • Finally, what if you want to add "Biweekly" or "Hourly"? This requires a schema change when you could just add new rows to a lookup table.

How do I protect javascript files?

Forget it, this is not doable.

No matter what you try it will not work. All a user needs to do to discover your code and it's location is to look in the net tab in firebug or use fiddler to see what requests are being made.

python pandas extract year from datetime: df['year'] = df['date'].year is not working

If you're running a recent-ish version of pandas then you can use the datetime attribute dt to access the datetime components:

In [6]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month
df
Out[6]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

EDIT

It looks like you're running an older version of pandas in which case the following would work:

In [18]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].apply(lambda x: x.year), df['date'].apply(lambda x: x.month)
df
Out[18]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

Regarding why it didn't parse this into a datetime in read_csv you need to pass the ordinal position of your column ([0]) because when True it tries to parse columns [1,2,3] see the docs

In [20]:

t="""date   Count
6/30/2010   525
7/30/2010   136
8/31/2010   125
9/30/2010   84
10/29/2010  4469"""
df = pd.read_csv(io.StringIO(t), sep='\s+', parse_dates=[0])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 2 columns):
date     5 non-null datetime64[ns]
Count    5 non-null int64
dtypes: datetime64[ns](1), int64(1)
memory usage: 120.0 bytes

So if you pass param parse_dates=[0] to read_csv there shouldn't be any need to call to_datetime on the 'date' column after loading.

Reading integers from binary file in Python

As you are reading the binary file, you need to unpack it into a integer, so use struct module for that

import struct
fin = open("hi.bmp", "rb")
firm = fin.read(2)  
file_size, = struct.unpack("i",fin.read(4))

Is it possible to auto-format your code in Dreamweaver?

ctrl+a->(click)commands->cleanup word HTML

How do I calculate someone's age in Java?

The correct answer using JodaTime is:

public int getAge() {
    Years years = Years.yearsBetween(new LocalDate(getBirthDate()), new LocalDate());
    return years.getYears();
}

You could even shorten it into one line if you like. I copied the idea from BrianAgnew's answer, but I believe this is more correct as you see from the comments there (and it answers the question exactly).

How to chain scope queries with OR instead of AND?

Rails 4 + Scope + Arel

class Creature < ActiveRecord::Base
    scope :is_good_pet, -> {
        where(
            arel_table[:is_cat].eq(true)
            .or(arel_table[:is_dog].eq(true))
            .or(arel_table[:eats_children].eq(false))
        )
    }
end

I tried chaining named scopes with .or and no luck, but this worked for finding anything with those booleans set. Generates SQL like

SELECT 'CREATURES'.* FROM 'CREATURES' WHERE ((('CREATURES'.'is_cat' = 1 OR 'CREATURES'.'is_dog' = 1) OR 'CREATURES'.'eats_children' = 0))

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

How to watch for array changes?

The most upvoted Override push method solution by @canon has some side-effects that were inconvenient in my case:

  • It makes the push property descriptor different (writable and configurable should be set true instead of false), which causes exceptions in a later point.

  • It raises the event multiple times when push() is called once with multiple arguments (such as myArray.push("a", "b")), which in my case was unnecessary and bad for performance.

So this is the best solution I could find that fixes the previous issues and is in my opinion cleaner/simpler/easier to understand.

Object.defineProperty(myArray, "push", {
    configurable: true,
    enumerable: false,
    writable: true, // Previous values based on Object.getOwnPropertyDescriptor(Array.prototype, "push")
    value: function (...args)
    {
        let result = Array.prototype.push.apply(this, args); // Original push() implementation based on https://github.com/vuejs/vue/blob/f2b476d4f4f685d84b4957e6c805740597945cde/src/core/observer/array.js and https://github.com/vuejs/vue/blob/daed1e73557d57df244ad8d46c9afff7208c9a2d/src/core/util/lang.js

        RaiseMyEvent();

        return result; // Original push() implementation
    }
});

Please see comments for my sources and for hints on how to implement the other mutating functions apart from push: 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'.

Count cells that contain any text

COUNTIF function can count cell which specific condition where as COUNTA will count all cell which contain any value

Example: Function in A7: =COUNTA(A1:A6)

Range:

A1| a

A2| b

A3| banana

A4| 42

A5|

A6|

A7| 4 (result)

How do you underline a text in Android XML?

Use this:

TextView txt = (TextView) findViewById(R.id.Textview1);
txt.setPaintFlags(txt.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

Convert ArrayList<String> to String[] array

Use like this.

List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");

String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);

for(String s : stockArr)
    System.out.println(s);

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

if you need to change your column output date format just use to_char this well get you a string, not a date.

How can I print variable and string on same line in Python?

On a current python version you have to use parenthesis, like so :

print ("If there was a birth every 7 seconds", X)

"No Content-Security-Policy meta tag found." error in my phonegap application

For me it was enough to reinstall whitelist plugin:

cordova plugin remove cordova-plugin-whitelist

and then

cordova plugin add cordova-plugin-whitelist

It looks like updating from previous versions of Cordova was not succesful.

Using .NET, how can you find the mime type of a file based on the file signature not the extension

This answer is a copy of the author's answer (Richard Gourlay), but improved to solve issues on IIS 8 / win2012 (where function would cause app pool to crash), based on Rohland's comment pointing to http://www.pinvoke.net/default.aspx/urlmon.findmimefromdata

using System.Runtime.InteropServices;

...

public static string GetMimeFromFile(string filename)
{

    if (!File.Exists(filename))
        throw new FileNotFoundException(filename + " not found");

    const int maxContent = 256;

    var buffer = new byte[maxContent];
    using (var fs = new FileStream(filename, FileMode.Open))
    {
        if (fs.Length >= maxContent)
            fs.Read(buffer, 0, maxContent);
        else
            fs.Read(buffer, 0, (int) fs.Length);
    }

    var mimeTypePtr = IntPtr.Zero;
    try
    {
        var result = FindMimeFromData(IntPtr.Zero, null, buffer, maxContent, null, 0, out mimeTypePtr, 0);
        if (result != 0)
        {
            Marshal.FreeCoTaskMem(mimeTypePtr);
            throw Marshal.GetExceptionForHR(result);
        }

        var mime = Marshal.PtrToStringUni(mimeTypePtr);
        Marshal.FreeCoTaskMem(mimeTypePtr);
        return mime;
    }
    catch (Exception e)
    {
        if (mimeTypePtr != IntPtr.Zero)
        {
            Marshal.FreeCoTaskMem(mimeTypePtr);
        }
        return "unknown/unknown";
    }
}

[DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
private static extern int FindMimeFromData(IntPtr pBC,
    [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
    [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeParamIndex = 3)] byte[] pBuffer,
    int cbSize,
    [MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,
    int dwMimeFlags,
    out IntPtr ppwzMimeOut,
    int dwReserved);

How to style icon color, size, and shadow of Font Awesome Icons

Simply you can define a class in your css file and cascade it into html file like

<i class="fa fa-plus fa-lg green"></i> 

now write down in css

.green{ color:green}

Convert char* to string C++

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

str.assign(s);

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

Reference/s here.

JavaScript Nested function

It is called closure.

Basically, the function defined within other function is accessible only within this function. But may be passed as a result and then this result may be called.

It is a very powerful feature. You can see more explanation here:

javascript_closures_for_dummies.html mirror on Archive.org

LF will be replaced by CRLF in git - What is that and is it important?

In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.

If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line

git config core.autocrlf true

If you want to make an intelligent decision how git should handle this, read the documentation

Here is a snippet

Formatting and Whitespace

Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.

core.autocrlf

If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.

Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:

$ git config --global core.autocrlf true

If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:

$ git config --global core.autocrlf input

This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.

If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:

$ git config --global core.autocrlf false

Write in body request with HttpClient

Extending your code (assuming that the XML you want to send is in xmlString) :

String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);

how to check if the input is a number or not in C?

The sscanf() solution is better in terms of code lines. My answer here is a user-build function that does almost the same as sscanf(). Stores the converted number in a pointer and returns a value called "val". If val comes out as zero, then the input is in unsupported format, hence conversion failed. Hence, use the pointer value only when val is non-zero.

It works only if the input is in base-10 form.

#include <stdio.h>
#include <string.h>
int CONVERT_3(double* Amt){

    char number[100];

    // Input the Data
    printf("\nPlease enter the amount (integer only)...");
    fgets(number,sizeof(number),stdin);

    // Detection-Conversion begins
    int iters = strlen(number)-2;
    int val = 1;
    int pos;
    double Amount = 0;
    *Amt = 0;
    for(int i = 0 ; i <= iters ; i++ ){
        switch(i){
            case 0:
                if(number[i]=='+'){break;}
                if(number[i]=='-'){val = 2; break;}
                if(number[i]=='.'){val = val + 10; pos = 0; break;}
                if(number[i]=='0'){Amount = 0; break;}
                if(number[i]=='1'){Amount = 1; break;}
                if(number[i]=='2'){Amount = 2; break;}
                if(number[i]=='3'){Amount = 3; break;}
                if(number[i]=='4'){Amount = 4; break;}
                if(number[i]=='5'){Amount = 5; break;}
                if(number[i]=='6'){Amount = 6; break;}
                if(number[i]=='7'){Amount = 7; break;}
                if(number[i]=='8'){Amount = 8; break;}
                if(number[i]=='9'){Amount = 9; break;}
            default:
                switch(number[i]){
                    case '.':
                        val = val + 10;
                        pos = i;
                        break;
                    case '0':
                        Amount = (Amount)*10;
                        break;
                    case '1':
                        Amount = (Amount)*10 + 1;
                        break;
                    case '2':
                        Amount = (Amount)*10 + 2;
                        break;
                    case '3':
                        Amount = (Amount)*10 + 3;
                        break;
                    case '4':
                        Amount = (Amount)*10 + 4;
                        break;
                    case '5':
                        Amount = (Amount)*10 + 5;
                        break;
                    case '6':
                        Amount = (Amount)*10 + 6;
                        break;
                    case '7':
                        Amount = (Amount)*10 + 7;
                        break;
                    case '8':
                        Amount = (Amount)*10 + 8;
                        break;
                    case '9':
                        Amount = (Amount)*10 + 9;
                        break;
                    default:
                        val = 0;
                }
        }
        if( (!val) | (val>20) ){val = 0; break;}// val == 0
    }

    if(val==1){*Amt = Amount;}
    if(val==2){*Amt = 0 - Amount;}
    if(val==11){
        int exp = iters - pos;
        long den = 1;
        for( ; exp-- ; ){
            den = den*10;
        }
        *Amt = Amount/den;
    }
    if(val==12){
        int exp = iters - pos;
        long den = 1;
        for( ; exp-- ; ){
            den = den*10;
        }
        *Amt = 0 - (Amount/den);
    }

    return val;
}


int main(void) {
    double AM = 0;
    int c = CONVERT_3(&AM);
    printf("\n\n%d    %lf\n",c,AM);

    return(0);
}

detect back button click in browser

best way I know

         window.onbeforeunload = function (e) {
            var e = e || window.event;
            var msg = "Do you really want to leave this page?"

            // For IE and Firefox
            if (e) {
                e.returnValue = msg;
            }

            // For Safari / chrome
            return msg;
         };

Add item to Listview control

Add items:

arr[0] = "product_1";
arr[1] = "100";
arr[2] = "10";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);

Retrieve items:

productName = listView1.SelectedItems[0].SubItems[0].Text;
price = listView1.SelectedItems[0].SubItems[1].Text;
quantity = listView1.SelectedItems[0].SubItems[2].Text;

source code

How to make two plots side-by-side using Python?

You can use - matplotlib.gridspec.GridSpec

Check - https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html

The below code displays a heatmap on right and an Image on left.

#Creating 1 row and 2 columns grid
gs = gridspec.GridSpec(1, 2) 
fig = plt.figure(figsize=(25,3))

#Using the 1st row and 1st column for plotting heatmap
ax=plt.subplot(gs[0,0])
ax=sns.heatmap([[1,23,5,8,5]],annot=True)

#Using the 1st row and 2nd column to show the image
ax1=plt.subplot(gs[0,1])
ax1.grid(False)
ax1.set_yticklabels([])
ax1.set_xticklabels([])

#The below lines are used to display the image on ax1
image = io.imread("https://images-na.ssl-images- amazon.com/images/I/51MvhqY1qdL._SL160_.jpg")

plt.imshow(image)
plt.show()

Output image

Include CSS,javascript file in Yii Framework

You can do so by adding

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/script');

How to change the cursor into a hand when a user hovers over a list item?

CSS:

.auto            { cursor: auto; }
.default         { cursor: default; }
.none            { cursor: none; }
.context-menu    { cursor: context-menu; }
.help            { cursor: help; }
.pointer         { cursor: pointer; }
.progress        { cursor: progress; }
.wait            { cursor: wait; }
.cell            { cursor: cell; }
.crosshair       { cursor: crosshair; }
.text            { cursor: text; }
.vertical-text   { cursor: vertical-text; }
.alias           { cursor: alias; }
.copy            { cursor: copy; }
.move            { cursor: move; }
.no-drop         { cursor: no-drop; }
.not-allowed     { cursor: not-allowed; }
.all-scroll      { cursor: all-scroll; }
.col-resize      { cursor: col-resize; }
.row-resize      { cursor: row-resize; }
.n-resize        { cursor: n-resize; }
.e-resize        { cursor: e-resize; }
.s-resize        { cursor: s-resize; }
.w-resize        { cursor: w-resize; }
.ns-resize       { cursor: ns-resize; }
.ew-resize       { cursor: ew-resize; }
.ne-resize       { cursor: ne-resize; }
.nw-resize       { cursor: nw-resize; }
.se-resize       { cursor: se-resize; }
.sw-resize       { cursor: sw-resize; }
.nesw-resize     { cursor: nesw-resize; }
.nwse-resize     { cursor: nwse-resize; }

You can also have the cursor be an image:

.img-cur {
   cursor: url(images/cursor.png), auto;
}

PHP: How to remove specific element from an array?

I was looking for the answer to the same question and came across this topic. I see two main ways: the combination of array_search & unset and the use of array_diff. At first glance, it seemed to me that the first method would be faster, since does not require the creation of an additional array (as when using array_diff). But I wrote a small benchmark and made sure that the second method is not only more concise, but also faster! Glad to share this with you. :)

https://glot.io/snippets/f6ow6biaol

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

Just check for the current Facebook user id $user and if it returned null then you need to reauthorize the user (or use the custom $_SESSION user id value - not recommended)

require 'facebook/src/facebook.php';


// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => 'APP_ID',
  'secret' => 'APP_SECRET',
));

$user = $facebook->getUser();

$photo_details = array('message' => 'my place');
$file='photos/my.jpg'; //Example image file
$photo_details['image'] = '@' . realpath($file);

if ($user) {
  try {
    // We have a valid FB session, so we can use 'me'
    $upload_photo = $facebook->api('/me/photos', 'post', $photo_details);
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}


// login or logout url will be needed depending on current user state.
if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
// redirect to Facebook login to get a fresh user access_token
  $loginUrl = $facebook->getLoginUrl();
  header('Location: ' . $loginUrl);
}

I've written a tutorial on how to upload a picture to the user's wall.

Simple file write function in C++

There are two solutions to this. You can either place the method above the method that calls it:

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int writeFile () 
{
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

int main()
{
    writeFile();
}

Or declare a prototype:

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int writeFile();

int main()
{
    writeFile();
}

int writeFile () 
{
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

MySQL CREATE FUNCTION Syntax

MySQL create function syntax:

DELIMITER //

CREATE FUNCTION GETFULLNAME(fname CHAR(250),lname CHAR(250))
    RETURNS CHAR(250)
    BEGIN
        DECLARE fullname CHAR(250);
        SET fullname=CONCAT(fname,' ',lname);
        RETURN fullname;
    END //

DELIMITER ;

Use This Function In Your Query

SELECT a.*,GETFULLNAME(a.fname,a.lname) FROM namedbtbl as a


SELECT GETFULLNAME("Biswarup","Adhikari") as myname;

Watch this Video how to create mysql function and how to use in your query

Create Mysql Function Video Tutorial

What is event bubbling and capturing?

As other said, bubbling and capturing describe in which order some nested elements receive a given event.

I wanted to point out that for the innermost element may appear something strange. Indeed, in this case the order in which the event listeners are added does matter.

In the following example, capturing for div2 will be executed first than bubbling; while bubbling for div4 will be executed first than capturing.

_x000D_
_x000D_
function addClickListener (msg, num, type) {
  document.querySelector("#div" + num)
    .addEventListener("click", () => alert(msg + num), type);
}
bubble  = (num) => addClickListener("bubble ", num, false);
capture = (num) => addClickListener("capture ", num, true);

// first capture then bubble
capture(1);
capture(2);
bubble(2);
bubble(1);

// try reverse order
bubble(3);
bubble(4);
capture(4);
capture(3);
_x000D_
#div1, #div2, #div3, #div4 {
  border: solid 1px;
  padding: 3px;
  margin: 3px;
}
_x000D_
<div id="div1">
  div 1
  <div id="div2">
    div 2
  </div>
</div>
<div id="div3">
  div 3
  <div id="div4">
    div 4
  </div>
</div>
_x000D_
_x000D_
_x000D_

Does a valid XML file require an XML declaration?

In XML 1.0, the XML Declaration is optional. See section 2.8 of the XML 1.0 Recommendation, where it says it "should" be used -- which means it is recommended, but not mandatory. In XML 1.1, however, the declaration is mandatory. See section 2.8 of the XML 1.1 Recommendation, where it says "MUST" be used. It even goes on to state that if the declaration is absent, that automatically implies the document is an XML 1.0 document.

Note that in an XML Declaration the encoding and standalone are both optional. Only the version is mandatory. Also, these are not attributes, so if they are present they must be in that order: version, followed by any encoding, followed by any standalone.

<?xml version="1.0"?>
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" standalone="yes"?>
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>

If you don't specify the encoding in this way, XML parsers try to guess what encoding is being used. The XML 1.0 Recommendation describes one possible way character encoding can be autodetected. In practice, this is not much of a problem if the input is encoded as UTF-8, UTF-16 or US-ASCII. Autodetection doesn't work when it encounters 8-bit encodings that use characters outside the US-ASCII range (e.g. ISO 8859-1) -- avoid creating these if you can.

The standalone indicates whether the XML document can be correctly processed without the DTD or not. People rarely use it. These days, it is a bad to design an XML format that is missing information without its DTD.

Update:

A "prolog error/invalid utf-8 encoding" error indicates that the actual data the parser found inside the file did not match the encoding that the XML declaration says it is. Or in some cases the data inside the file did not match the autodetected encoding.

Since your file contains a byte-order-mark (BOM) it should be in UTF-16 encoding. I suspect that your declaration says <?xml version="1.0" encoding="UTF-8"?> which is obviously incorrect when the file has been changed into UTF-16 by NotePad. The simple solution is to remove the encoding and simply say <?xml version="1.0"?>. You could also edit it to say encoding="UTF-16" but that would be wrong for the original file (which wasn't in UTF-16) or if the file somehow gets changed back to UTF-8 or some other encoding.

Don't bother trying to remove the BOM -- that's not the cause of the problem. Using NotePad or WordPad to edit XML is the real problem!

Java: Simplest way to get last word in a string

If other whitespace characters are possible, then you'd want:

testString.split("\\s+");

Check if space is in a string

You can try this, and if it will find any space it will return the position where the first space is.

if mystring.find(' ') != -1:
    print True
else:
    print False

Split string in Lua?

Simply sitting on a delimiter

local str = 'one,two'
local regxEverythingExceptComma = '([^,]+)'
for x in string.gmatch(str, regxEverythingExceptComma) do
    print(x)
end

When to use Spring Security`s antMatcher()?

Basically http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

milliseconds to days

int days = (int) (milliseconds / 86 400 000 )

Difference between Pragma and Cache-Control headers?

Stop using (HTTP 1.0) Replaced with (HTTP 1.1 since 1999)
Expires: [date] Cache-Control: max-age=[seconds]
Pragma: no-cache Cache-Control: no-cache

If it's after 1999, and you're still using Expires or Pragma, you're doing it wrong.

I'm looking at you Stackoverflow:

200 OK
Pragma: no-cache
Content-Type: application/json
X-Frame-Options: SAMEORIGIN
X-Request-Guid: a3433194-4a03-4206-91ea-6a40f9bfd824
Strict-Transport-Security: max-age=15552000
Content-Length: 54
Accept-Ranges: bytes
Date: Tue, 03 Apr 2018 19:03:12 GMT
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: cache-yyz8333-YYZ
X-Cache: MISS
X-Cache-Hits: 0
X-Timer: S1522782193.766958,VS0,VE30
Vary: Fastly-SSL
X-DNS-Prefetch-Control: off
Cache-Control: private

tl;dr: Pragma is a legacy of HTTP/1.0 and hasn't been needed since Internet Explorer 5, or Netscape 4.7. Unless you expect some of your users to be using IE5: it's safe to stop using it.


  • Expires: [date] (deprecated - HTTP 1.0)
  • Pragma: no-cache (deprecated - HTTP 1.0)
  • Cache-Control: max-age=[seconds]
  • Cache-Control: no-cache (must re-validate the cached copy every time)

And the conditional requests:

  • Etag (entity tag) based conditional requests
    • Server: Etag: W/“1d2e7–1648e509289”
    • Client: If-None-Match: W/“1d2e7–1648e509289”
    • Server: 304 Not Modified
  • Modified date based conditional requests
    • Server: last-modified: Thu, 09 May 2019 19:15:47 GMT
    • Client: If-Modified-Since: Fri, 13 Jul 2018 10:49:23 GMT
    • Server: 304 Not Modified

last-modified: Thu, 09 May 2019 19:15:47 GMT

Check if string matches pattern

One-liner: re.match(r"pattern", string) # No need to compile

import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
...     print('Yes')
... 
Yes

You can evalute it as bool if needed

>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True

Domain Account keeping locking out with correct password every few minutes

You need to make sure that the clocks on all your servers are correct. Kerberos errors are normally caused by your server clock being out of sync with your domain.

UPDATE

Failure code 0x12 very specifically means "Clients credentials have been revoked", which means that this error has happened once the account has been disabled, expired, or locked out.

It would be useful to try and find the previous error messages if you think that the account was active - i.e. this error message may not be the root cause, you will have different errors preceding this error, which cause the account to get locked.

Ideally, to get a full answer, you will need to reactivate the account and keep an eye on the logs for an error occurring before the 0x12 error messages.

How Exactly Does @param Work - Java

@param won't affect the number. It's just for making javadocs.

More on javadoc: http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Many people set their cookie path to /. That will cause every favicon request to send a copy of the sites cookies, at least in chrome. Addressing your favicon to your cookieless domain should correct this.

<link rel="icon" href="https://cookieless.MySite.com/favicon.ico" type="image/x-icon" />

Depending on how much traffic you get, this may be the most practical reason for adding the link.

Info on setting up a cookieless domain:

http://www.ravelrumba.com/blog/static-cookieless-domain/

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

If you're using Windows 10, do this:

  1. Go to Start

  2. Start typing 'This PC'

  3. Right-click This PC, choose Properties

  4. On the left side of the window that pops up, click on Advanced System Settings

  5. Click on the Advanced tab

  6. Click on the Environmental Variables button at the bottom

  7. Down in the System Variables section, double-click Path

  8. Click the New button in the top right corner

  9. Add this path: C:\Program Files\Git\bin\ then click the enter key

  10. Add another path: C:\Program Files\Git\cmd

  11. Close & re-open the console if it's already open.

I stepped you through the long way so you gain exposure to the different Windows/menus. Good luck.

Mongoose and multiple database in single node.js project

A bit optimized(for me atleast) solution. write this to a file db.js and require this to wherever required and call it with a function call and you are good to go.

   const MongoClient = require('mongodb').MongoClient;
    async function getConnections(url,db){
        return new Promise((resolve,reject)=>{
            MongoClient.connect(url, { useUnifiedTopology: true },function(err, client) {
                if(err) { console.error(err) 
                    resolve(false);
                }
                else{
                    resolve(client.db(db));
                }
            })
        });
    }

    module.exports = async function(){
        let dbs      = [];
        dbs['db1']     = await getConnections('mongodb://localhost:27017/','db1');
        dbs['db2']     = await getConnections('mongodb://localhost:27017/','db2');
        return dbs;
    };

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

How to get file name when user select a file via <input type="file" />?

You can get the file name, but you cannot get the full client file-system path.

Try to access to the value attribute of your file input on the change event.

Most browsers will give you only the file name, but there are exceptions like IE8 which will give you a fake path like: "C:\fakepath\myfile.ext" and older versions (IE <= 6) which actually will give you the full client file-system path (due its lack of security).

document.getElementById('fileInput').onchange = function () {
  alert('Selected file: ' + this.value);
};

How to debug .htaccess RewriteRule not working

Perhaps a more logical method would be to create a file (e.g. test.html), add some content and then try to set it as the index page:

DirectoryIndex test.html

For the most part, the .htaccess rule will override the Apache configuration where working at the directory/file level

How is a non-breaking space represented in a JavaScript string?

Remember that .text() strips out markup, thus I don't believe you're going to find &nbsp; in a non-markup result.

Made in to an answer....

var p = $('<p>').html('&nbsp;');
if (p.text() == String.fromCharCode(160) && p.text() == '\xA0')
    alert('Character 160');

Shows an alert, as the ASCII equivalent of the markup is returned instead.

How to check command line parameter in ".bat" file?

Actually, all the other answers have flaws. The most reliable way is:

IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

Detailed Explanation:

Using "%1"=="-b" will flat out crash if passing argument with spaces and quotes. This is the least reliable method.

IF "%1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat "a b"

b""=="-b" was unexpected at this time.

Using [%1]==[-b] is better because it will not crash with spaces and quotes, but it will not match if the argument is surrounded by quotes.

IF [%1]==[-b] (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat "-b"

(does not match, and jumps to UNKNOWN instead of SPECIFIC)

Using "%~1"=="-b" is the most reliable. %~1 will strip off surrounding quotes if they exist. So it works with and without quotes, and also with no args.

IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat
C:\> run.bat -b
C:\> run.bat "-b"
C:\> run.bat "a b"

(all of the above tests work correctly)

What is the difference between for and foreach?

The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface. The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

Insert line at middle of file with Python?

This is a way of doing the trick.

f = open("path_to_file", "r")
contents = f.readlines()
f.close()

contents.insert(index, value)

f = open("path_to_file", "w")
contents = "".join(contents)
f.write(contents)
f.close()

"index" and "value" are the line and value of your choice, lines starting from 0.

Insert PHP code In WordPress Page and Post

You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.

The easiest solution for this is creating a shortcode. Then you can use something like this

function input_func( $atts ) {
    extract( shortcode_atts( array(
        'type' => 'text',
        'name' => '',
    ), $atts ) );

    return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );

See the Shortcode_API.

How do I sort a table in Excel if it has cell references in it?

I'm pretty sure this can be solved with the indirect() function. Here's a simplified spreadsheet:

            A         B                       C                         D    ...
       +------------------------------------------------------+- - - - - - - - -
     1 |CITY     |Q1-Q3 SALES|ANNUALIZED SALES:(Q1+Q2+Q3)*1.33|
       +======================================================+- - - - - - - - -
     2 |Tampa    | $23,453.00|                      $31,192.49|
       +------------------------------------------------------+
     3 |Chicago  | $33,251.00|                      $44,223.83|
       +------------------------------------------------------+
     4 |Portland | $14,423.00|                      $19,182.59|
       +------------------------------------------------------+
    ...|   ...   |    ...    |              ...               |

Normally the formula in cell C2 would be =B2*1.33, which works fine until you do a complex sort. To make it robust to sorting, build your own cell reference using the row number of that cell like this: =indirect("B"&row())*1.33.

Hope that works in your situation. It fixed a similar problem I was having.

Environment Specific application.properties file in Spring Boot application

My Point , IN this arent way asking developer to create all environment related in single go, resulting in risk of exposing Production Configuration to end developer

as per 12-Factor, shouldnt be enviornment specific reside in Enviornment only .

How do we do for CI CD

  • Build Spring one time and promote to aother environment, in that case, if we have spring jar has all environment, it iwll security risk, having all environment variable in GIT

Splitting on first occurrence

df.columnname[1].split('.', 1)

This will split data with the first occurrence of '.' in the string or data frame column value.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

Here is an effective solution from didi to solve this problem, Since this bug is very common and difficult to find the cause, It looks more like a system problem, Why can't we ignore it directly?Of course we can ignore it, Here is the sample code:

final Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = 
        Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if (t.getName().equals("FinalizerWatchdogDaemon") && e instanceof TimeoutException) {
        } else {
            defaultUncaughtExceptionHandler.uncaughtException(t, e);
        }
    }
});

By setting a special default uncaught exception handler, application can change the way in which uncaught exceptions are handled for those threads that would already accept whatever default behavior the system provided. When an uncaught TimeoutException is thrown from a thread named FinalizerWatchdogDaemon, this special handler will block the handler chain, the system handler will not be called, so crash will be avoided.

Through practice, no other bad effects were found. The GC system is still working, timeouts are alleviated as CPU usage decreases.

For more details see: https://mp.weixin.qq.com/s/uFcFYO2GtWWiblotem2bGg

How to make an autocomplete address field with google maps api?

I really doubt it--google maps API is great for geocoding known addresses, but it generally return data that is suitable for autocomplete-style operations. Nevermind the challenge of not hitting the API in such a way as to eat up your geocoding query limit very quickly.

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

Does Go have "if x in" construct similar to Python?

This is quote from the book "Programming in Go: Creating Applications for the 21st Century":

Using a simple linear search like this is the only option for unsorted data and is fine for small slices (up to hundreds of items). But for larger slices—especially if we are performing searches repeatedly—the linear search is very inefficient, on average requiring half the items to be compared each time.

Go provides a sort.Search() method which uses the binary search algorithm: This requires the comparison of only log2(n) items (where n is the number of items) each time. To put this in perspective, a linear search of 1000000 items requires 500000 comparisons on average, with a worst case of 1000000 comparisons; a binary search needs at most 20 comparisons, even in the worst case.

files := []string{"Test.conf", "util.go", "Makefile", "misc.go", "main.go"}
target := "Makefile"
sort.Strings(files)
i := sort.Search(len(files),
    func(i int) bool { return files[i] >= target })
if i < len(files) && files[i] == target {
    fmt.Printf("found \"%s\" at files[%d]\n", files[i], i)
}

https://play.golang.org/p/UIndYQ8FeW

How to delete an element from an array in C#

Removing from an array itself is not simple, as you then have to deal with resizing. This is one of the great advantages of using something like a List<int> instead. It provides Remove/RemoveAt in 2.0, and lots of LINQ extensions for 3.0.

If you can, refactor to use a List<> or similar.

Use Robocopy to copy only changed files?

Looks like /e option is what you need, it'll skip same files/directories.

robocopy c:\data c:\backup /e

If you run the command twice, you'll see the second round is much faster since it skips a lot of things.

Python: Find a substring in a string and returning the index of the substring

Adding onto @demented hedgehog answer on using find()

In terms of efficiency

It may be worth first checking to see if s1 is in s2 before calling find().
This can be more efficient if you know that most of the times s1 won't be a substring of s2

Since the in operator is very efficient

 s1 in s2

It can be more efficient to convert:

index = s2.find(s1)

to

index = -1
if s1 in s2:
   index = s2.find(s1)

This is useful for when find() is going to be returning -1 a lot.

I found it substantially faster since find() was being called many times in my algorithm, so I thought it was worth mentioning

Printing a char with printf

This is supposed to print the ASCII value of the character, as %d is the escape sequence for an integer. So the value given as argument of printf is taken as integer when printed.

char ch = 'a';
printf("%d", ch);

Same holds for printf("%d", '\0');, where the NULL character is interpreted as the 0 integer.

Finally, sizeof('\n') is 4 because in C, this notation for characters stands for the corresponding ASCII integer. So '\n' is the same as 10 as an integer.

It all depends on the interpretation you give to the bytes.

Set timeout for webClient.DownloadFile()

Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:

using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
     if (stream != null)
     {
          stream.ReadTimeout = Timeout.Infinite;
          using (var reader = new StreamReader(stream, Encoding.UTF8, false))
          {
               string line;
               while ((line = reader.ReadLine()) != null)
               {
                    if (line != String.Empty)
                    {
                        Console.WriteLine("Count {0}", count++);
                    }
                    Console.WriteLine(line);
               }
          }
     }
}

Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.

Swift - how to make custom header for UITableView?

This worked for me - Swift 3

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
        return headerCell
    }

How to export data from Spark SQL to CSV

The answer above with spark-csv is correct but there is an issue - the library creates several files based on the data frame partitioning. And this is not what we usually need. So, you can combine all partitions to one:

df.coalesce(1).
    write.
    format("com.databricks.spark.csv").
    option("header", "true").
    save("myfile.csv")

and rename the output of the lib (name "part-00000") to a desire filename.

This blog post provides more details: https://fullstackml.com/2015/12/21/how-to-export-data-frame-from-apache-spark/

How best to determine if an argument is not sent to the JavaScript function

There are several different ways to check if an argument was passed to a function. In addition to the two you mentioned in your (original) question - checking arguments.length or using the || operator to provide default values - one can also explicitly check the arguments for undefined via argument2 === undefined or typeof argument2 === 'undefined' if one is paranoid (see comments).

Using the || operator has become standard practice - all the cool kids do it - but be careful: The default value will be triggered if the argument evaluates to false, which means it might actually be undefined, null, false, 0, '' (or anything else for which Boolean(...) returns false).

So the question is when to use which check, as they all yield slightly different results.

Checking arguments.length exhibits the 'most correct' behaviour, but it might not be feasible if there's more than one optional argument.

The test for undefined is next 'best' - it only 'fails' if the function is explicitly called with an undefined value, which in all likelyhood should be treated the same way as omitting the argument.

The use of the || operator might trigger usage of the default value even if a valid argument is provided. On the other hand, its behaviour might actually be desired.

To summarize: Only use it if you know what you're doing!

In my opinion, using || is also the way to go if there's more than one optional argument and one doesn't want to pass an object literal as a workaround for named parameters.

Another nice way to provide default values using arguments.length is possible by falling through the labels of a switch statement:

function test(requiredArg, optionalArg1, optionalArg2, optionalArg3) {
    switch(arguments.length) {
        case 1: optionalArg1 = 'default1';
        case 2: optionalArg2 = 'default2';
        case 3: optionalArg3 = 'default3';
        case 4: break;
        default: throw new Error('illegal argument count')
    }
    // do stuff
}

This has the downside that the programmer's intention is not (visually) obvious and uses 'magic numbers'; it is therefore possibly error prone.

Subset a dataframe by multiple factor levels

Here's another:

data[data$Code == "A" | data$Code == "B", ]

It's also worth mentioning that the subsetting factor doesn't have to be part of the data frame if it matches the data frame rows in length and order. In this case we made our data frame from this factor anyway. So,

data[Code == "A" | Code == "B", ]

also works, which is one of the really useful things about R.

SQL LIKE condition to check for integer?

If you want to search as string, you can cast to text like this:

SELECT * FROM books WHERE price::TEXT LIKE '123%'

How to get the current working directory using python 3?

Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded. Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link

Listing all the folders subfolders and files in a directory using php

I'm really fond of SPL Library, they offer iterator's, including RecursiveDirectoryIterator.

How do I make an HTML button not reload the page

there is no need to js or jquery. to stop page reloading just specify the button type as 'button'. if you dont specify the button type, browser will set it to 'reset' or 'submit' witch cause to page reload.

 <button type='button'>submit</button> 

How do I make a text input non-editable?

<input type="text" value="3" class="field left" readonly>

You could see in https://www.w3schools.com/tags/att_input_readonly.asp

The method to set "readonly":

$("input").attr("readonly", true)

to cancel "readonly"(work in jQuery):

$("input").attr("readonly", false)

Renaming the current file in Vim

sav person.haml_spec.rb | call delete(expand('#'))

JQuery addclass to selected div, remove class if another div is selected

In this mode you can find all element which has class active and remove it

try this

$(document).ready(function() {
        $(this.attr('id')).click(function () {
           $(document).find('.active').removeClass('active');
           var DivId = $(this).attr('id');
           alert(DivId);
           $(this).addClass('active');
        });
  });

Get Substring between two characters using javascript

A small function I made that can grab the string between, and can (optionally) skip a number of matched words to grab a specific index.

Also, setting start to false will use the beginning of the string, and setting end to false will use the end of the string.

set pos1 to the position of the start text you want to use, 1 will use the first occurrence of start

pos2 does the same thing as pos1, but for end, and 1 will use the first occurrence of end only after start, occurrences of end before start are ignored.

function getStringBetween(str, start=false, end=false, pos1=1, pos2=1){
  var newPos1 = 0;
  var newPos2 = str.length;

  if(start){
    var loops = pos1;
    var i = 0;
    while(loops > 0){
      if(i > str.length){
        break;
      }else if(str[i] == start[0]){
        var found = 0;
        for(var p = 0; p < start.length; p++){
          if(str[i+p] == start[p]){
            found++;
          }
        }
        if(found >= start.length){
          newPos1 = i + start.length;
          loops--;
        }
      }
      i++;
    }
  }

  if(end){
    var loops = pos2;
    var i = newPos1;
    while(loops > 0){
      if(i > str.length){
        break;
      }else if(str[i] == end[0]){
        var found = 0;
        for(var p = 0; p < end.length; p++){
          if(str[i+p] == end[p]){
            found++;
          }
        }
        if(found >= end.length){
          newPos2 = i;
          loops--;
        }
      }
      i++;
    }
  }

  var result = '';
  for(var i = newPos1; i < newPos2; i++){
    result += str[i];
  }
  return result;
}

Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.