Programs & Examples On #Multitrigger

Set object property using reflection

You can try this out when you want to mass-assign properties of an Object from another Object using Property names:

public static void Assign(this object destination, object source)
    {
        if (destination is IEnumerable && source is IEnumerable)
        {
            var dest_enumerator = (destination as IEnumerable).GetEnumerator();
            var src_enumerator = (source as IEnumerable).GetEnumerator();
            while (dest_enumerator.MoveNext() && src_enumerator.MoveNext())
                dest_enumerator.Current.Assign(src_enumerator.Current);
        }
        else
        {
            var destProperties = destination.GetType().GetProperties();
            foreach (var sourceProperty in source.GetType().GetProperties())
            {
                foreach (var destProperty in destProperties)
                {
                    if (destProperty.Name == sourceProperty.Name && destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
                    {
                        destProperty.SetValue(destination,     sourceProperty.GetValue(source, new object[] { }), new object[] { });
                        break;
            }
        }
    }
}

How do I create a ListView with rounded corners in Android?

Here is one way of doing it (Thanks to Android Documentation though!):

Add the following into a file (say customshape.xml) and then place it in (res/drawable/customshape.xml)

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle"> 
     <gradient 
         android:startColor="#SomeGradientBeginColor"
         android:endColor="#SomeGradientEndColor" 
         android:angle="270"/> 

    <corners 
         android:bottomRightRadius="7dp" 
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp" 
         android:topRightRadius="7dp"/> 
</shape> 

Once you are done with creating this file, just set the background in one of the following ways:

Through Code: listView.setBackgroundResource(R.drawable.customshape);

Through XML, just add the following attribute to the container (ex: LinearLayout or to any fields):

android:background="@drawable/customshape"

Hope someone finds it useful...

How to display a date as iso 8601 format with PHP

Here is the good function for pre PHP 5: I added GMT difference at the end, it's not hardcoded.

function iso8601($time=false) {
    if ($time === false) $time = time();
    $date = date('Y-m-d\TH:i:sO', $time);
    return (substr($date, 0, strlen($date)-2).':'.substr($date, -2));
}

How to overcome "'aclocal-1.15' is missing on your system" warning?

2017 - High Sierra

It is really hard to get autoconf 1.15 working on Mac. We hired an expert to get it working. Everything worked beautifully.

Later I happened to upgrade a Mac to High Sierra.

The Docker pipeline stopped working!

Even though autoconf 1.15 is working fine on the Mac.

How to fix,

Short answer, I simply trashed the local repo, and checked out the repo again.

This suggestion is noted in the mix on this QA page and elsewhere.

It then worked fine!

It likely has something to do with the aclocal.m4 and similar files. (But who knows really). I endlessly massaged those files ... but nothing.

For some unknown reason if you just scratch your repo and get the repo again: everything works!

I tried for hours every combo of touching/deleting etc etc the files in question, but no. Just check out the repo from scratch!

MySQL Insert with While Loop

drop procedure if exists doWhile;
DELIMITER //  
CREATE PROCEDURE doWhile()   
BEGIN
DECLARE i INT DEFAULT 2376921001; 
WHILE (i <= 237692200) DO
    INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
    SET i = i+1;
END WHILE;
END;
//  

CALL doWhile(); 

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

System.String (with capital S) is already nullable, you do not need to declare it as such.

(string? myStr) is wrong.

Where is the kibana error log? Is there a kibana error log?

It seems that you need to pass a flag "-l, --log-file"

https://github.com/elastic/kibana/issues/3407

Usage: kibana [options]

Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.

Options:

    -h, --help                 output usage information
    -V, --version              output the version number
    -e, --elasticsearch <uri>  Elasticsearch instance
    -c, --config <path>        Path to the config file
    -p, --port <port>          The port to bind to
    -q, --quiet                Turns off logging
    -H, --host <host>          The host to bind to
    -l, --log-file <path>      The file to log to
    --plugins <path>           Path to scan for plugins

If you use the init script to run as a service, maybe you will need to customize it.

Java: Check if command line arguments are null

@jjnguy's answer is correct in most circumstances. You won't ever see a null String in the argument array (or a null array) if main is called by running the application is run from the command line in the normal way.

However, if some other part of the application calls a main method, it is conceivable that it might pass a null argument or null argument array.

However(2), this is clearly a highly unusual use-case, and it is an egregious violation of the implied contract for a main entry-point method. Therefore, I don't think you should bother checking for null argument values in main. In the unlikely event that they do occur, it is acceptable for the calling code to get a NullPointerException. After all, it is a bug in the caller to violate the contract.

Angular 2 change event on every keypress

The secret event that keeps angular ngModel synchronous is the event call input. Hence the best answer to your question should be:

<input type="text" [(ngModel)]="mymodel" (input)="valuechange($event)" />
{{mymodel}}

Java, How to add library files in netbeans?

In Netbeans 8.2

1. Dowload the binaries from the web source. The Apache Commos are in: [http://commons.apache.org/components.html][1] In this case, you must select the "Logging" in the Components menu and follow the link to downloads in the Releases part. Direct URL: [http://commons.apache.org/proper/commons-logging/download_logging.cgi][2] For me, the correct download was the file: commons-logging-1.2-bin.zip from the Binaries.

2. Unzip downloaded content. Now, you can see several jar files inside the directory created from the zip file.

3. Add the library to the project. Right click in the project, select Properties and click in Libraries (in the left side). Click the button "Add Jar/Folder". Go to the previously unzipped contents and select the properly jar file. Clic in "Open" and click in"Ok". The library has been loaded!

how to access iFrame parent page using jquery?

There are multiple ways to do these.

I) Get main parent directly.

for exa. i want to replace my child page to iframe then

var link = '<%=Page.ResolveUrl("~/Home/SubscribeReport")%>';
top.location.replace(link);

here top.location gets parent directly.

II) get parent one by one,

var element = $('.iframe:visible', window.parent.document);

here if you have more then one iframe, then specify active or visible one.

you also can do like these for getting further parents,

var masterParent = element.parent().parent().parent()

III) get parent by Identifier.

var myWindow = window.top.$("#Identifier")

VB.NET - Click Submit Button on Webbrowser page

You could try giving an ID to the form, in order to get ahold of it, and then call form.submit() from a Javascript call.

When do I need to use AtomicBoolean in Java?

The AtomicBoolean class gives you a boolean value that you can update atomically. Use it when you have multiple threads accessing a boolean variable.

The java.util.concurrent.atomic package overview gives you a good high-level description of what the classes in this package do and when to use them. I'd also recommend the book Java Concurrency in Practice by Brian Goetz.

c++ compile error: ISO C++ forbids comparison between pointer and integer

You must remember to use single quotes for char constants. So use

if (answer == 'y') return true;

Rather than

if (answer == "y") return true;

I tested this and it works

Sound effects in JavaScript / HTML5

You can always try AudioContext it has limited support but it's a part of the web audio api working draft. It might be worth it if you are planing to release something in the future. And if you are only programing for chrome and Firefox you're golden.

Destroy or remove a view in Backbone.js

I think this should work

destroyView : function () {
    this.$el.remove();
}

Android - Start service on boot

Following should work. I have verified. May be your problem is somewhere else.

Receiver:

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
            Log.d("TAG", "MyReceiver");
            Intent serviceIntent = new Intent(context, Test1Service.class);
            context.startService(serviceIntent);
        }
    }
}

Service:

public class Test1Service extends Service {
    /** Called when the activity is first created. */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "Service created.");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "Service started.");
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d("TAG", "Service started.");
    }
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0"
      android:installLocation="internalOnly">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
    
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.BATTERY_STATS" 
    />
<!--        <activity android:name=".MyActivity">
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER"></category> 
            </intent-filter>
       </activity> -->
        <service android:name=".Test1Service" 
                  android:label="@string/app_name"
                  >
        </service>
        <receiver android:name=".MyReceiver">  
            <intent-filter>  
                <action android:name="android.intent.action.BOOT_COMPLETED" /> 
            </intent-filter>  
        </receiver> 
    </application>
</manifest>

mysqldump exports only one table

Quoting this link: http://steveswanson.wordpress.com/2009/04/21/exporting-and-importing-an-individual-mysql-table/

  • Exporting the Table

To export the table run the following command from the command line:

mysqldump -p --user=username dbname tableName > tableName.sql

This will export the tableName to the file tableName.sql.

  • Importing the Table

To import the table run the following command from the command line:

mysql -u username -p -D dbname < tableName.sql

The path to the tableName.sql needs to be prepended with the absolute path to that file. At this point the table will be imported into the DB.

Adding Text to DataGridView Row Header

Yes. First, hook into the column added event:

this.dataGridView1.ColumnAdded += new DataGridViewColumnEventHandler(dataGridView1_ColumnAdded);

Then, in your event handler, just append the text you want to:

private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
    e.Column.HeaderText += additionalHeaderText;
}

Search for executable files using find command

This worked for me & thought of sharing...

find ./ -type f -name "*" -not -name "*.o" -exec sh -c '
    case "$(head -n 1 "$1")" in
      ?ELF*) exit 0;;
      MZ*) exit 0;;
      #!*/ocamlrun*)exit0;;
    esac
exit 1
' sh {} \; -print

Get webpage contents with Python?

If you ask me. try this one

import urllib2
resp = urllib2.urlopen('http://hiscore.runescape.com/index_lite.ws?player=zezima')

and read the normal way ie

page = resp.read()

Good luck though

Where value in column containing comma delimited values

WHERE
      MyColumn LIKE '%,' + @search + ',%' --middle
      OR
      MyColumn LIKE @search + ',%' --start
      OR
      MyColumn LIKE '%,' + @search --end
      OR 
      MyColumn =  @search --single (good point by Cheran S in comment)

Loop through each row of a range in Excel

Just stumbled upon this and thought I would suggest my solution. I typically like to use the built in functionality of assigning a range to an multi-dim array (I guess it's also the JS Programmer in me).

I frequently write code like this:

Sub arrayBuilder()

myarray = Range("A1:D4")

'unlike most VBA Arrays, this array doesn't need to be declared and will be automatically dimensioned

For i = 1 To UBound(myarray)

    For j = 1 To UBound(myarray, 2)

    Debug.Print (myarray(i, j))

    Next j

Next i

End Sub

Assigning ranges to variables is a very powerful way to manipulate data in VBA.

addID in jQuery?

I've used something like this before which addresses @scunliffes concern. It finds all instances of items with a class of (in this case .button), and assigns an ID and appends its index to the id name:

_x000D_
_x000D_
$(".button").attr('id', function (index) {_x000D_
 return "button-" + index;_x000D_
});
_x000D_
_x000D_
_x000D_

So let's say you have 3 items with the class name of .button on a page. The result would be adding a unique ID to all of them (in addition to their class of "button").

In this case, #button-0, #button-1, #button-2, respectively. This can come in very handy. Simply replace ".button" in the first line with whatever class you want to target, and replace "button" in the return statement with whatever you'd like your unique ID to be. Hope this helps!

How to use Class<T> in Java?

Using the generified version of class Class allows you, among other things, to write things like

Class<? extends Collection> someCollectionClass = someMethod();

and then you can be sure that the Class object you receive extends Collection, and an instance of this class will be (at least) a Collection.

How to set an "Accept:" header on Spring RestTemplate request?

Here is a simple answer. Hope it helps someone.

import org.springframework.boot.devtools.remote.client.HttpHeaderInterceptor;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;


public String post(SomeRequest someRequest) {
    // create a list the headers 
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
    interceptors.add(new HttpHeaderInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
    interceptors.add(new HttpHeaderInterceptor("ContentType", MediaType.APPLICATION_JSON_VALUE));
    interceptors.add(new HttpHeaderInterceptor("username", "user123"));
    interceptors.add(new HttpHeaderInterceptor("customHeader1", "c1"));
    interceptors.add(new HttpHeaderInterceptor("customHeader2", "c2"));
    // initialize RestTemplate
    RestTemplate restTemplate = new RestTemplate();
    // set header interceptors here
    restTemplate.setInterceptors(interceptors);
    // post the request. The response should be JSON string
    String response = restTemplate.postForObject(Url, someRequest, String.class);
    return response;
}

Running Java Program from Command Line Linux

If your Main class is in a package called FileManagement, then try:

java -cp . FileManagement.Main

in the parent folder of the FileManagement folder.

If your Main class is not in a package (the default package) then cd to the FileManagement folder and try:

java -cp . Main

More info about the CLASSPATH and how the JRE find classes:

jQuery append() vs appendChild()

appendChild is a pure javascript method where as append is a jQuery method.

Permission denied at hdfs

For Hadoop 3.x, if you try to create a file on HDFS when unauthenticated (e.g. user=dr.who) you will get this error.

It is not recommended for systems that need to be secure, however if you'd like to disable file permissions entirely in Hadoop 3 the hdfs-site.xml setting has changed to:

<property>
  <name>dfs.permissions.enabled</name>
  <value>false</value>
</property>

https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/hdfs-default.xml

jquery .html() vs .append()

You can get the second method to achieve the same effect by:

var mySecondDiv = $('<div></div>');
$(mySecondDiv).find('div').attr('id', 'mySecondDiv');
$('#myDiv').append(mySecondDiv);

Luca mentioned that html() just inserts hte HTML which results in faster performance.

In some occassions though, you would opt for the second option, consider:

// Clumsy string concat, error prone
$('#myDiv').html("<div style='width:'" + myWidth + "'px'>Lorem ipsum</div>");

// Isn't this a lot cleaner? (though longer)
var newDiv = $('<div></div>');
$(newDiv).find('div').css('width', myWidth);
$('#myDiv').append(newDiv);

REST API error code 500 handling

The real question is why does it generate a 500 error. If it is related to any input parameters, then I would argue that it should be handled internally and returned as a 400 series error. Generally a 400, 404 or 406 would be appropriate to reflect bad input since the general convention is that a RESTful resource is uniquely identified by the URL and a URL that cannot generate a valid response is a bad request (400) or similar.

If the error is caused by anything other than the inputs explicitly or implicitly supplied by the request, then I would say a 500 error is likely appropriate. So a failed database connection or other unpredictable error is accurately represented by a 500 series error.

PHP: date function to get month of the current date

$unixtime = strtotime($test);
echo date('m', $unixtime); //month
echo date('d', $unixtime); 
echo date('y', $unixtime );

What is tempuri.org?

Unfortunately the tempuri.org URL now just redirects to Bing.

You can see what it used to render via archive.org:

https://web.archive.org/web/20090304024056/http://tempuri.org/

To quote:

Each XML Web Service needs a unique namespace in order for client applications to distinguish it from other services on the Web. By default, ASP.Net Web Services use http://tempuri.org/ for this purpose. While this suitable for XML Web Services under development, published services should use a unique, permanent namespace.

Your XML Web Service should be identified by a namespace that you control. For example, you can use your company's Internet domain name as part of the namespace. Although many namespaces look like URLs, they need not point to actual resources on the Web.

For XML Web Services creating[sic] using ASP.NET, the default namespace can be changed using the WebService attribute's Namespace property. The WebService attribute is applied to the class that contains the XML Web Service methods. Below is a code example that sets the namespace to "http://microsoft.com/webservices/":

C#

[WebService(Namespace="http://microsoft.com/webservices/")]
public class MyWebService {
   // implementation
}

Visual Basic.NET

<WebService(Namespace:="http://microsoft.com/webservices/")> Public Class MyWebService
    ' implementation
End Class

Visual J#.NET

/**@attribute WebService(Namespace="http://microsoft.com/webservices/")*/
public class MyWebService {
    // implementation
}

It's also worth reading section 'A 1.3 Generating URIs' at:

http://www.w3.org/TR/wsdl#_Toc492291092

angular 2 how to return data from subscribe

I have used this way lots time ...

_x000D_
_x000D_
@Component({_x000D_
   selector: "data",_x000D_
   template: "<h1>{{ getData() }}</h1>"_x000D_
})_x000D_
_x000D_
export class DataComponent{_x000D_
    this.http.get(path).subscribe({_x000D_
       DataComponent.setSubscribeData(res);_x000D_
    })_x000D_
}_x000D_
_x000D_
_x000D_
static subscribeData:any;_x000D_
static setSubscribeData(data):any{_x000D_
    DataComponent.subscribeData=data;_x000D_
    return data;_x000D_
}
_x000D_
_x000D_
_x000D_

use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...

Laravel whereIn OR whereIn

Yes, orWhereIn is a method that you can use.

I'm fairly sure it should give you the result you're looking for, however, if it doesn't you could simply use implode to create a string and then explode it (this is a guess at your array structure):

$values = implode(',', array_map(function($value)
{
    return trim($value, ',');
}, $filters));

$query->whereIn('products.value', explode(',' $values));

Call JavaScript function from C#

You can call javascript functions from c# using Jering.Javascript.NodeJS, an open-source library by my organization:

string javascriptModule = @"
module.exports = (callback, x, y) => {  // Module must export a function that takes a callback as its first parameter
    var result = x + y; // Your javascript logic
    callback(null /* If an error occurred, provide an error object or message */, result); // Call the callback when you're done.
}";

// Invoke javascript
int result = await StaticNodeJSService.InvokeFromStringAsync<int>(javascriptModule, args: new object[] { 3, 5 });

// result == 8
Assert.Equal(8, result);

The library supports invoking directly from .js files as well. Say you have file C:/My/Directory/exampleModule.js containing:

module.exports = (callback, message) => callback(null, message);

You can invoke the exported function:

string result = await StaticNodeJSService.InvokeFromFileAsync<string>("C:/My/Directory/exampleModule.js", args: new[] { "test" });

// result == "test"
Assert.Equal("test", result);

Given a starting and ending indices, how can I copy part of a string in C?

Use strncpy

e.g.

strncpy(dest, src + beginIndex, endIndex - beginIndex);

This assumes you've

  1. Validated that dest is large enough.
  2. endIndex is greater than beginIndex
  3. beginIndex is less than strlen(src)
  4. endIndex is less than strlen(src)

React.js: onChange event for contentEditable

I suggest using a mutationObserver to do this. It gives you a lot more control over what is going on. It also gives you more details on how the browse interprets all the keystrokes

Here in TypeScript

import * as React from 'react';

export default class Editor extends React.Component {
    private _root: HTMLDivElement; // Ref to the editable div
    private _mutationObserver: MutationObserver; // Modifications observer
    private _innerTextBuffer: string; // Stores the last printed value

    public componentDidMount() {
        this._root.contentEditable = "true";
        this._mutationObserver = new MutationObserver(this.onContentChange);
        this._mutationObserver.observe(this._root, {
            childList: true, // To check for new lines
            subtree: true, // To check for nested elements
            characterData: true // To check for text modifications
        });
    }

    public render() {
        return (
            <div ref={this.onRootRef}>
                Modify the text here ...
            </div>
        );
    }

    private onContentChange: MutationCallback = (mutations: MutationRecord[]) => {
        mutations.forEach(() => {
            // Get the text from the editable div
            // (Use innerHTML to get the HTML)
            const {innerText} = this._root; 

            // Content changed will be triggered several times for one key stroke
            if (!this._innerTextBuffer || this._innerTextBuffer !== innerText) {
                console.log(innerText); // Call this.setState or this.props.onChange here
                this._innerTextBuffer = innerText;
            }
        });
    }

    private onRootRef = (elt: HTMLDivElement) => {
        this._root = elt;
    }
}

How do I calculate tables size in Oracle

First off, I would generally caution that gathering table statistics in order to do space analysis is a potentially dangerous thing to do. Gathering statistics may change query plans, particularly if the DBA has configured a statistics gathering job that uses non-default parameters that your call is not using, and will cause Oracle to re-parse queries that utilize the table in question which can be a performance hit. If the DBA has intentionally left some tables without statistics (common if your OPTIMIZER_MODE is CHOOSE), gathering statistics can cause Oracle to stop using the rule-based optimizer and start using the cost-based optimizer for a set of queries which can be a major performance headache if it is done unexpectedly in production. If your statistics are accurate, you can query USER_TABLES (or ALL_TABLES or DBA_TABLES) directly without calling GATHER_TABLE_STATS. If your statistics are not accurate, there is probably a reason for that and you don't want to disturb the status quo.

Second, the closest equivalent to the SQL Server sp_spaceused procedure is likely Oracle's DBMS_SPACE package. Tom Kyte has a nice show_space procedure that provides a simple interface to this package and prints out information similar to what sp_spaceused prints out.

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

How can I auto hide alert box after it showing it?

You can't close an alert box with Javascript.

You could, however, use a window instead:

var w = window.open('','','width=100,height=100')
w.document.write('Message')
w.focus()
setTimeout(function() {w.close();}, 5000)

How can I get the behavior of GNU's readlink -f on a Mac?

Here is a portable shell function that should work in ANY Bourne comparable shell. It will resolve the relative path punctuation ".. or ." and dereference symbolic links.

If for some reason you do not have a realpath(1) command, or readlink(1) this can be aliased.

which realpath || alias realpath='real_path'

Enjoy:

real_path () {
  OIFS=$IFS
  IFS='/'
  for I in $1
  do
    # Resolve relative path punctuation.
    if [ "$I" = "." ] || [ -z "$I" ]
      then continue
    elif [ "$I" = ".." ]
      then FOO="${FOO%%/${FOO##*/}}"
           continue
      else FOO="${FOO}/${I}"
    fi

    ## Resolve symbolic links
    if [ -h "$FOO" ]
    then
    IFS=$OIFS
    set `ls -l "$FOO"`
    while shift ;
    do
      if [ "$1" = "->" ]
        then FOO=$2
             shift $#
             break
      fi
    done
    IFS='/'
    fi
  done
  IFS=$OIFS
  echo "$FOO"
}

also, just in case anybody is interested here is how to implement basename and dirname in 100% pure shell code:

## http://www.opengroup.org/onlinepubs/000095399/functions/dirname.html
# the dir name excludes the least portion behind the last slash.
dir_name () {
  echo "${1%/*}"
}

## http://www.opengroup.org/onlinepubs/000095399/functions/basename.html
# the base name excludes the greatest portion in front of the last slash.
base_name () {
  echo "${1##*/}"
}

You can find updated version of this shell code at my google site: http://sites.google.com/site/jdisnard/realpath

EDIT: This code is licensed under the terms of the 2-clause (freeBSD style) license. A copy of the license may be found by following the above hyperlink to my site.

Regex Match all characters between two strings

This:

This is (.*?) sentence

works in javascript.

Unique random string generation

I am surprised why there is not a CrytpoGraphic solution in place. GUID is unique but not cryptographically safe. See this Dotnet Fiddle.

var bytes = new byte[40]; // byte size
using (var crypto = new RNGCryptoServiceProvider())
  crypto.GetBytes(bytes);

var base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

In case you want to Prepend with a Guid:

var result = Guid.NewGuid().ToString("N") + base64;
Console.WriteLine(result);

A cleaner alphanumeric string:

result = Regex.Replace(result,"[^A-Za-z0-9]","");
Console.WriteLine(result);

ADB Driver and Windows 8.1

The most complete answer I have found is here: http://blog.kikicode.com/2013/10/installing-android-adb-driver-in.html

I'm copying the complete answer below.


Installing Android ADB driver in Windows 8.1 64-bit when all else fails

For some reason I just couldn't get my machine to recognize Xperia J in Windows 8.1 64-bit. Even after installing latest Sony PC Companion (2.10.174). Device Manager kept showing yellow exclamation mark to an 'Android'.

Here's the solution, but I don't promise it will work on your device!

1. Find out your device's VID and PID

Open Device Manager, right-click that Android with yellow exclamation mark and click Properties. Go to Details tab. In Property, select Hardware Ids. Right-click the value and click Copy. Paste the value somewhere.

2. Download Android USB Driver

Run Android SDK Manager. Expand Extras, tick Google USB Driver, click Install packages. After installation, look for the driver location by hovering mouse over Google USB Driver. The location will appear in the tooltip.

3. Modify android_winusb.inf

Go to the usb driver location, for example in the above picture it is c:\Android\android-studio\sdk\extras\google\usb_driver Make a backup copy of android_winusb.inf Open android_winusb.inf with a text editor. Notepad is fine but Notepad++ is better, it will syntax highlight the inf file! Look for [Google.NTx86], and insert a line with your device's hardware ID that you copied above, for example

[Google.NTx86]

; ... other existing lines

;SONY Sony Xperia J
%CompositeAdbInterface% = USB_Install, USB\VID_0FCE&PID_6188&MI_01

Look for [Google.NTamd86], and insert the same lines, for example:

[Google.NTamd64]

; ... other existing lines

;SONY Sony Xperia J
%CompositeAdbInterface% = USB_Install, USB\VID_0FCE&PID_6188&MI_01

Save the file.

4. Disable driver signing

Run Command Prompt as an administrator Paste and run the following commands:

bcdedit -set loadoptions DISABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING ON

Restart Windows.

5. Install driver

Open Device Manager, right-click that Android with yellow exclamation mark and click Update Driver Software. Click Browse my computer for driver software. Enter or browse to the folder containing android_winusb.inf, eg: C:\Android\android-studio\sdk\extras\google\usb_driver Click Next. The driver will install. Run adb devices to confirm your device is working fine.

6. Re-enable driver signing

Run Command Prompt as an administrator Paste and run the following commands:

bcdedit -set loadoptions ENABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING OFF

Restart Windows. Run adb devices to reconfirm!

How do I prevent the padding property from changing width or height in CSS?

Put a div in your newdiv with width: auto and margin-left: 20px

Remove the padding from newdiv.

The W3 Box model page has good info.

how to get the last part of a string before a certain character?

You are looking for str.rsplit(), with a limit:

print x.rsplit('-', 1)[0]

.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.

Another option is to use str.rpartition(), which will only ever split just once:

print x.rpartition('-')[0]

For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().

Demo:

>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'

and the same with str.rpartition()

>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'

Best way to check for "empty or null value"

The expression stringexpression = '' yields:

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

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

(stringexpression = '') IS NOT FALSE

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

(stringexpression <> '') IS NOT TRUE

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

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

coalesce(stringexpression, '') = ''

But the expressions at the top are faster.

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

stringexpression <> ''

About char(n)

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

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

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

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

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

Demo

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

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

Result:

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

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

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

Result:

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

Test for "null or empty string" with text:

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

Result:

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

db<>fiddle here
Old sqlfiddle

Related:

How to check the presence of php and apache on ubuntu server through ssh

Another way to find out if a program is installed is by using the which command. It will show the path of the program you're searching for. For example if when your searching for apache you can use the following command:

$ which apache2ctl
/usr/sbin/apache2ctl

And if you searching for PHP try this:

$ which php
/usr/bin/php

If the which command doesn't give any result it means the software is not installed (or is not in the current $PATH):

$ which php
$

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

For an Ant project:

Make sure, you have servlet-api.jar in the lib folder.

For a Maven project:

Make sure, you have the dependency added in POM.xml.

<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <scope>provided</scope>
</dependency>

Another way to do it is: Update the project facets to pick up the right server.

Check this box in this location:

Project ? Properties ? Target Runtimes ? Apache Tomcat (any server)

Is there a constraint that restricts my generic method to numeric types?

If you are using .NET 4.0 and later then you can just use dynamic as method argument and check in runtime that the passed dynamic argument type is numeric/integer type.

If the type of the passed dynamic is not numeric/integer type then throw exception.

An example short code that implements the idea is something like:

using System;
public class InvalidArgumentException : Exception
{
    public InvalidArgumentException(string message) : base(message) {}
}
public class InvalidArgumentTypeException : InvalidArgumentException
{
    public InvalidArgumentTypeException(string message) : base(message) {}
}
public class ArgumentTypeNotIntegerException : InvalidArgumentTypeException
{
    public ArgumentTypeNotIntegerException(string message) : base(message) {}
}
public static class Program
{
    private static bool IntegerFunction(dynamic n)
    {
        if (n.GetType() != typeof(Int16) &&
            n.GetType() != typeof(Int32) &&
            n.GetType() != typeof(Int64) &&
            n.GetType() != typeof(UInt16) &&
            n.GetType() != typeof(UInt32) &&
            n.GetType() != typeof(UInt64))
            throw new ArgumentTypeNotIntegerException("argument type is not integer type");
        //code that implements IntegerFunction goes here
    }
    private static void Main()
    {
         Console.WriteLine("{0}",IntegerFunction(0)); //Compiles, no run time error and first line of output buffer is either "True" or "False" depends on the code that implements "Program.IntegerFunction" static method.
         Console.WriteLine("{0}",IntegerFunction("string")); //Also compiles but it is run time error and exception of type "ArgumentTypeNotIntegerException" is thrown here.
         Console.WriteLine("This is the last Console.WriteLine output"); //Never reached and executed due the run time error and the exception thrown on the second line of Program.Main static method.
    }

Of course that this solution works in run time only but never in compile time.

If you want a solution that always works in compile time and never in run time then you will have to wrap the dynamic with a public struct/class whose overloaded public constructors accept arguments of the desired types only and give the struct/class appropriate name.

It makes sense that the wrapped dynamic is always private member of the class/struct and it is the only member of the struct/class and the name of the only member of the struct/class is "value".

You will also have to define and implement public methods and/or operators that work with the desired types for the private dynamic member of the class/struct if necessary.

It also makes sense that the struct/class has special/unique constructor that accepts dynamic as argument that initializes it's only private dynamic member called "value" but the modifier of this constructor is private of course.

Once the class/struct is ready define the argument's type of IntegerFunction to be that class/struct that has been defined.

An example long code that implements the idea is something like:

using System;
public struct Integer
{
    private dynamic value;
    private Integer(dynamic n) { this.value = n; }
    public Integer(Int16 n) { this.value = n; }
    public Integer(Int32 n) { this.value = n; }
    public Integer(Int64 n) { this.value = n; }
    public Integer(UInt16 n) { this.value = n; }
    public Integer(UInt32 n) { this.value = n; }
    public Integer(UInt64 n) { this.value = n; }
    public Integer(Integer n) { this.value = n.value; }
    public static implicit operator Int16(Integer n) { return n.value; }
    public static implicit operator Int32(Integer n) { return n.value; }
    public static implicit operator Int64(Integer n) { return n.value; }
    public static implicit operator UInt16(Integer n) { return n.value; }
    public static implicit operator UInt32(Integer n) { return n.value; }
    public static implicit operator UInt64(Integer n) { return n.value; }
    public static Integer operator +(Integer x, Int16 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, Int32 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, Int64 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt16 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt32 y) { return new Integer(x.value + y); }
    public static Integer operator +(Integer x, UInt64 y) { return new Integer(x.value + y); }
    public static Integer operator -(Integer x, Int16 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, Int32 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, Int64 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt16 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt32 y) { return new Integer(x.value - y); }
    public static Integer operator -(Integer x, UInt64 y) { return new Integer(x.value - y); }
    public static Integer operator *(Integer x, Int16 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, Int32 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, Int64 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt16 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt32 y) { return new Integer(x.value * y); }
    public static Integer operator *(Integer x, UInt64 y) { return new Integer(x.value * y); }
    public static Integer operator /(Integer x, Int16 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, Int32 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, Int64 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt16 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt32 y) { return new Integer(x.value / y); }
    public static Integer operator /(Integer x, UInt64 y) { return new Integer(x.value / y); }
    public static Integer operator %(Integer x, Int16 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, Int32 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, Int64 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt16 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt32 y) { return new Integer(x.value % y); }
    public static Integer operator %(Integer x, UInt64 y) { return new Integer(x.value % y); }
    public static Integer operator +(Integer x, Integer y) { return new Integer(x.value + y.value); }
    public static Integer operator -(Integer x, Integer y) { return new Integer(x.value - y.value); }
    public static Integer operator *(Integer x, Integer y) { return new Integer(x.value * y.value); }
    public static Integer operator /(Integer x, Integer y) { return new Integer(x.value / y.value); }
    public static Integer operator %(Integer x, Integer y) { return new Integer(x.value % y.value); }
    public static bool operator ==(Integer x, Int16 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int16 y) { return x.value != y; }
    public static bool operator ==(Integer x, Int32 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int32 y) { return x.value != y; }
    public static bool operator ==(Integer x, Int64 y) { return x.value == y; }
    public static bool operator !=(Integer x, Int64 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt16 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt16 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt32 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt32 y) { return x.value != y; }
    public static bool operator ==(Integer x, UInt64 y) { return x.value == y; }
    public static bool operator !=(Integer x, UInt64 y) { return x.value != y; }
    public static bool operator ==(Integer x, Integer y) { return x.value == y.value; }
    public static bool operator !=(Integer x, Integer y) { return x.value != y.value; }
    public override bool Equals(object obj) { return this == (Integer)obj; }
    public override int GetHashCode() { return this.value.GetHashCode(); }
    public override string ToString() { return this.value.ToString(); }
    public static bool operator >(Integer x, Int16 y) { return x.value > y; }
    public static bool operator <(Integer x, Int16 y) { return x.value < y; }
    public static bool operator >(Integer x, Int32 y) { return x.value > y; }
    public static bool operator <(Integer x, Int32 y) { return x.value < y; }
    public static bool operator >(Integer x, Int64 y) { return x.value > y; }
    public static bool operator <(Integer x, Int64 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt16 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt16 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt32 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt32 y) { return x.value < y; }
    public static bool operator >(Integer x, UInt64 y) { return x.value > y; }
    public static bool operator <(Integer x, UInt64 y) { return x.value < y; }
    public static bool operator >(Integer x, Integer y) { return x.value > y.value; }
    public static bool operator <(Integer x, Integer y) { return x.value < y.value; }
    public static bool operator >=(Integer x, Int16 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int16 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Int32 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int32 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Int64 y) { return x.value >= y; }
    public static bool operator <=(Integer x, Int64 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt16 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt16 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt32 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt32 y) { return x.value <= y; }
    public static bool operator >=(Integer x, UInt64 y) { return x.value >= y; }
    public static bool operator <=(Integer x, UInt64 y) { return x.value <= y; }
    public static bool operator >=(Integer x, Integer y) { return x.value >= y.value; }
    public static bool operator <=(Integer x, Integer y) { return x.value <= y.value; }
    public static Integer operator +(Int16 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(Int32 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(Int64 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt16 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt32 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator +(UInt64 x, Integer y) { return new Integer(x + y.value); }
    public static Integer operator -(Int16 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(Int32 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(Int64 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt16 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt32 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator -(UInt64 x, Integer y) { return new Integer(x - y.value); }
    public static Integer operator *(Int16 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(Int32 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(Int64 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt16 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt32 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator *(UInt64 x, Integer y) { return new Integer(x * y.value); }
    public static Integer operator /(Int16 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(Int32 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(Int64 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt16 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt32 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator /(UInt64 x, Integer y) { return new Integer(x / y.value); }
    public static Integer operator %(Int16 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(Int32 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(Int64 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt16 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt32 x, Integer y) { return new Integer(x % y.value); }
    public static Integer operator %(UInt64 x, Integer y) { return new Integer(x % y.value); }
    public static bool operator ==(Int16 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int16 x, Integer y) { return x != y.value; }
    public static bool operator ==(Int32 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int32 x, Integer y) { return x != y.value; }
    public static bool operator ==(Int64 x, Integer y) { return x == y.value; }
    public static bool operator !=(Int64 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt16 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt16 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt32 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt32 x, Integer y) { return x != y.value; }
    public static bool operator ==(UInt64 x, Integer y) { return x == y.value; }
    public static bool operator !=(UInt64 x, Integer y) { return x != y.value; }
    public static bool operator >(Int16 x, Integer y) { return x > y.value; }
    public static bool operator <(Int16 x, Integer y) { return x < y.value; }
    public static bool operator >(Int32 x, Integer y) { return x > y.value; }
    public static bool operator <(Int32 x, Integer y) { return x < y.value; }
    public static bool operator >(Int64 x, Integer y) { return x > y.value; }
    public static bool operator <(Int64 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt16 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt16 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt32 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt32 x, Integer y) { return x < y.value; }
    public static bool operator >(UInt64 x, Integer y) { return x > y.value; }
    public static bool operator <(UInt64 x, Integer y) { return x < y.value; }
    public static bool operator >=(Int16 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int16 x, Integer y) { return x <= y.value; }
    public static bool operator >=(Int32 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int32 x, Integer y) { return x <= y.value; }
    public static bool operator >=(Int64 x, Integer y) { return x >= y.value; }
    public static bool operator <=(Int64 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt16 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt16 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt32 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt32 x, Integer y) { return x <= y.value; }
    public static bool operator >=(UInt64 x, Integer y) { return x >= y.value; }
    public static bool operator <=(UInt64 x, Integer y) { return x <= y.value; }
}
public static class Program
{
    private static bool IntegerFunction(Integer n)
    {
        //code that implements IntegerFunction goes here
        //note that there is NO code that checks the type of n in rum time, because it is NOT needed anymore 
    }
    private static void Main()
    {
        Console.WriteLine("{0}",IntegerFunction(0)); //compile error: there is no overloaded METHOD for objects of type "int" and no implicit conversion from any object, including "int", to "Integer" is known.
        Console.WriteLine("{0}",IntegerFunction(new Integer(0))); //both compiles and no run time error
        Console.WriteLine("{0}",IntegerFunction("string")); //compile error: there is no overloaded METHOD for objects of type "string" and no implicit conversion from any object, including "string", to "Integer" is known.
        Console.WriteLine("{0}",IntegerFunction(new Integer("string"))); //compile error: there is no overloaded CONSTRUCTOR for objects of type "string"
    }
}

Note that in order to use dynamic in your code you must Add Reference to Microsoft.CSharp

If the version of the .NET framework is below/under/lesser than 4.0 and dynamic is undefined in that version then you will have to use object instead and do casting to the integer type, which is trouble, so I recommend that you use at least .NET 4.0 or newer if you can so you can use dynamic instead of object.

How to display the first few characters of a string in Python?

If you want first 2 letters and last 2 letters of a string then you can use the following code: name = "India" name[0:2]="In" names[-2:]="ia"

Closing a file after File.Create

The function returns a FileStream object. So you could use it's return value to open your StreamWriter or close it using the proper method of the object:

File.Create(myPath).Close();

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

You need to see if the Type of your instance is equal to the Type of the class. To get the type of the instance you use the GetType() method:

 u.GetType().Equals(t);

or

 u.GetType.Equals(typeof(User));

should do it. Obviously you could use '==' to do your comparison if you prefer.

How to rotate x-axis tick labels in Pandas barplot

For bar graphs, you can include the angle which you finally want the ticks to have.

Here I am using rot=0 to make them parallel to the x axis.

series.plot.bar(rot=0)
plt.show()
plt.close()

Can a div have multiple classes (Twitter Bootstrap)

Yes, div can take as many classes as you need. Use space to separate one from another.

 <div class="active dropdown-toggle custom-class">Example of multiple classses</div>

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

If nothing happens even if you added all the annotation needed, try to add this dependency to your pom.xml, I just faced the same problem and resolved it by adding this one here:

<dependency>
   <groupId>commons-configuration</groupId>
   <artifactId>commons-configuration</artifactId>
   <version>1.9</version>
</dependency>

Printing with sed or awk a line following a matching pattern

This might work for you (GNU sed):

sed -n ':a;/regexp/{n;h;p;x;ba}' file

Use seds grep-like option -n and if the current line contains the required regexp replace the current line with the next, copy that line to the hold space (HS), print the line, swap the pattern space (PS) for the HS and repeat.

How to compare strings in Bash

a="abc"
b="def"

# Equality Comparison
if [ "$a" == "$b" ]; then
    echo "Strings match"
else
    echo "Strings don't match"
fi

# Lexicographic (greater than, less than) comparison.
if [ "$a" \< "$b" ]; then
    echo "$a is lexicographically smaller then $b"
elif [ "$a" \> "$b" ]; then
    echo "$b is lexicographically smaller than $a"
else
    echo "Strings are equal"
fi

Notes:

  1. Spaces between if and [ and ] are important
  2. > and < are redirection operators so escape it with \> and \< respectively for strings.

Execute a stored procedure in another stored procedure in SQL server

If you only want to perform some specific operations by your second SP and do not require values back from the SP then simply do:

Exec secondSPName  @anyparams

Else, if you need values returned by your second SP inside your first one, then create a temporary table variable with equal numbers of columns and with same definition of column return by second SP. Then you can get these values in first SP as:

Insert into @tep_table
Exec secondSPName @anyparams

Update:

To pass parameter to second sp, do this:

Declare @id ID_Column_datatype 
Set @id=(Select id from table_1 Where yourconditions)

Exec secondSPName @id

Update 2:

Suppose your second sp returns Id and Name where type of id is int and name is of varchar(64) type.

now, if you want to select these values in first sp then create a temporary table variable and insert values into it:

Declare @tep_table table
(
  Id int,
  Name varchar(64)
)
Insert into @tep_table
Exec secondSP

Select * From @tep_table

This will return you the values returned by second SP.

Hope, this clear all your doubts.

How to check if another instance of my shell script is running

This is compact and universal

# exit if another instance of this script is running
for pid in $(pidof -x `basename $0`); do
   [ $pid != $$ ] && { exit 1; }
done

How to check if an element does NOT have a specific class?

There are more complex scenarios where this doesn't work. What if you want to select an element with class A that doesn't contain elements with class B. You end up needing something more like:

If parent element does not contain certain child element; jQuery

Python element-wise tuple operations like sum

In case someone need to average a list of tuples:

import operator 
from functools import reduce
tuple(reduce(lambda x, y: tuple(map(operator.add, x, y)),list_of_tuples))

macro run-time error '9': subscript out of range

When you get the error message, you have the option to click on "Debug": this will lead you to the line where the error occurred. The Dark Canuck seems to be right, and I guess the error occurs on the line:

Sheets("Sheet1").protect Password:="btfd"

because most probably the "Sheet1" does not exist. However, if you say "It works fine, but when I save the file I get the message: run-time error '9': subscription out of range" it makes me think the error occurs on the second line:

ActiveWorkbook.Save

Could you please check this by pressing the Debug button first? And most important, as Gordon Bell says, why are you using a macro to protect a workbook?

Adding a new array element to a JSON object

JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON

var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"

label or @html.Label ASP.net MVC 4

In the case of your label snippet, it doesn't really matter. I would go for the simpler syntax (plain HTML).

Most helper methods also don't allow you to surround another element. This can be a consideration when choosing to use/not use one.

Strongly-Typed Equivalents

However, it's worth noting that what you use the @Html.[Element]For<T>() methods that you gain important features. Note the "For" at the end of the method name.

Example:

@Html.TextBoxFor( o => o.FirstName )

This will handle ID/Name creation based on object hierarchy (which is critical for model binding). It will also add unobtrusive validation attributes. These methods take an Expression as an argument which refers to a property within the model. The metadata of this property is obtained by the MVC framework, and as such it "knows" more about the property than its string-argument counterpart.

It also allows you to deal with UI code in a strongly-typed fashion. Visual Studio will highlight syntax errors, whereas it cannot do so with a string. Views can also be optionally compiled along with the solution, allowing for additional compile-time checks.

Other Considerations

Occasionally a HTML helper method will also perform additional tasks which are useful, such as Html.Checkbox and Html.CheckboxFor which also create a hidden field to go along with the checkbox. Another example are the URL-related methods (such as for a hyperlink) which are route-aware.

<!-- bad -->
<a href="/foo/bar/123">my link</a>

<!-- good -->
@Html.ActionLink( "my link", "foo", "bar", new{ id=123 } )

<!-- also fine (perhaps you want to wrap something with the anchor) -->
<a href="@Url.Action( "foo", "bar", new{ id=123 } )"><span>my link</span></a>

There is a slight performance benefit to using plain HTML versus code which must be executed whenever the view is rendered, although this should not be the deciding factor.

How can I open a Shell inside a Vim Window?

I guess this is a fairly old question, but now in 2017. We have neovim, which is a fork of vim which adds terminal support.

So invoking :term would open a terminal window. The beauty of this solution as opposed to using tmux (a terminal multiplexer) is that you'll have the same window bindings as your vim setup. neovim is compatible with vim, so you can basically copy and paste your .vimrc and it will just work.

More advantages are you can switch to normal mode on the opened terminal and you can do basic copy and editing. It is also pretty useful for git commits too I guess, since everything in your buffer you can use in auto-complete.

I'll update this answer since vim is also planning to release terminal support, probably in vim 8.1. You can follow the progress here: https://groups.google.com/forum/#!topic/vim_dev/Q9gUWGCeTXM

Once it's released, I do believe this is a more superior setup than using tmux.

What is the function of the push / pop instructions used on registers in x86 assembly?

Pushing and popping registers are behind the scenes equivalent to this:

push reg   <= same as =>      sub  $8,%rsp        # subtract 8 from rsp
                              mov  reg,(%rsp)     # store, using rsp as the address

pop  reg    <= same as=>      mov  (%rsp),reg     # load, using rsp as the address
                              add  $8,%rsp        # add 8 to the rsp

Note this is x86-64 At&t syntax.

Used as a pair, this lets you save a register on the stack and restore it later. There are other uses, too.

View array in Visual Studio debugger?

If you have a large array and only want to see a subsection of the array you can type this into the watch window;

ptr+100,10

to show a list of the 10 elements starting at ptr[100]. Beware that the displayed array subscripts will start at [0], so you will have to remember that ptr[0] is really ptr[100] and ptr[1] is ptr[101] etc.

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

How to output MySQL query results in CSV format?

From http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/

SELECT order_id,product_name,qty
FROM orders
WHERE foo = 'bar'
INTO OUTFILE '/var/lib/mysql-files/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

Using this command columns names will not be exported.

Also note that /var/lib/mysql-files/orders.csv will be on the server that is running MySQL. The user that the MySQL process is running under must have permissions to write to the directory chosen, or the command will fail.

If you want to write output to your local machine from a remote server (especially a hosted or virtualize machine such as Heroku or Amazon RDS), this solution is not suitable.

Access index of the parent ng-repeat from child ng-repeat

My example code was correct and the issue was something else in my actual code. Still, I know it was difficult to find examples of this so I'm answering it in case someone else is looking.

<div ng-repeat="f in foos">
  <div>
    <div ng-repeat="b in foos.bars">
      <a ng-click="addSomething($parent.$index)">Add Something</a>
    </div>
  </div>
</div>

Can I use Homebrew on Ubuntu?

You can just follow instructions from the Homebrew on Linux docs, but I think it is better to understand what the instructions are trying to achieve.

Understanding the installation steps can save some time


Step 1: Choose location

First of all, it is important to understand that linuxbrew will be installed on the /home directory and not inside /home/your-user (the ~ directory).
(See the reason for that at the end of answer).
Keep this in mind when you run the other steps below.

Step 2: Add linuxbrew binaries to /home :

The installation script will do it for us:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Step 3: Check that /linuxbrew was added to the relevant location

This can be done by simply navigating to /home.
Notice that the docs are showing it as a one-liner by adding test -d <linuxbrew location> before each command.

(Read more about the test command in here).

Step 4: Export relevant environment variables to terminal

We need to add linuxbrew to PATH and add some more environment variables to the current terminal.

We can just add the following exports to terminal (wait don't do it..):

export PATH="/home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin${PATH+:$PATH}";

export HOMEBREW_PREFIX="/home/linuxbrew/.linuxbrew";
export HOMEBREW_CELLAR="/home/linuxbrew/.linuxbrew/Cellar";
export HOMEBREW_REPOSITORY="/home/linuxbrew/.linuxbrew/Homebrew";
export MANPATH="/home/linuxbrew/.linuxbrew/share/man${MANPATH+:$MANPATH}:";
export INFOPATH="/home/linuxbrew/.linuxbrew/share/info:${INFOPATH:-}";

Or simply run (If your linuxbrew folder is on other location then /home - change the path):

eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)

(*) Because brew command is not yet identified by the current terminal (this is what we're solving right now) we'll have to specify the full path to the brew binary: /home/linuxbrew/.linuxbrew/bin/brew shellenv

Test this step by:

1 ) Run brew from current terminal to see if it identifies the command.

2 ) Run printenv and check if all environment variables were exported and that you see /home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin on PATH.

Step 5: Ensure step 4 is running on each terminal

We need to add step 4 to ~/.profile (in case of Debian/Ubuntu):

echo "eval \$($(brew --prefix)/bin/brew shellenv)" >> ~/.profile

For CentOS/Fedora/Red Hat - replace ~/.profile with ~/.bash_profile.

Step 6: Ensure that ~/.profile or ~/.bash_profile are being executed when new terminal is opened

If you executed step 5 and failed to run brew from new terminal - add a test command like echo "Hi!" to ~/.profile or ~/.bash_profile.
If you don't see Hi! when you open a new terminal - go to the terminal preferences and ensure that the attribute of 'run command as login shell' is set.
Read more in here.


Why the installation script installs Homebrew to /home/linuxbrew/.linuxbrew - from here:

The installation script installs Homebrew to /home/linuxbrew/.linuxbrew using sudo if possible and in your home directory at ~/.linuxbrew otherwise. Homebrew does not use sudo after installation.
Using /home/linuxbrew/.linuxbrew allows the use of more binary packages (bottles) than installing in your personal home directory.

The prefix /home/linuxbrew/.linuxbrew was chosen so that users without admin access can ask an admin to create a linuxbrew role account and still benefit from precompiled binaries.

If you do not yourself have admin privileges, consider asking your admin staff to create a linuxbrew role account for you with home directory /home/linuxbrew.

File tree view in Notepad++

Tree like structure in Notepad++ without plugin

Download Notepad++ 6.8.8 & then follow step below :

Notepad++ -> View-> Project-> choose Panel 1 OR Panel 2 OR Panel 3 ->

It will create a sub part Wokspace on the left side -> Right click on Workspace & click Add Project -> Again right click on Project which is created recently -> And click on Add Files From Directory.

This is it. Enjoy

Is Python faster and lighter than C++?

It's the same problem with managed and easy to use programming language as always - they are slow (and sometimes memory-eating).

These are languages to do control rather than processing. If I would have to write application to transform images and had to use Python too all the processing could be written in C++ and connected to Python via bindings while interface and process control would be definetely Python.

What is the difference between Task.Run() and Task.Factory.StartNew()

According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:

I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :) StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.

Here are the actual reasons:

  1. Does not understand async delegates. This is actually the same as point 1 in the reasons why you would want to use StartNew. The problem is that when you pass an async delegate to StartNew, it’s natural to assume that the returned task represents that delegate. However, since StartNew does not understand async delegates, what that task actually represents is just the beginning of that delegate. This is one of the first pitfalls that coders encounter when using StartNew in async code.
  2. Confusing default scheduler. OK, trick question time: in the code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);

private static void A() { }

Well, you know it’s a trick question, eh? If you answered “a thread pool thread”, I’m sorry, but that’s not correct. “A” will run on whatever TaskScheduler is currently executing!

So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.

In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew() but the animation displayed properly when I switched to Task.Run().

For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html

Working with huge files in VIM

this is old but, use nano, vim or gvim

Nginx not running with no error message

First, always sudo nginx -t to verify your config files are good.

I ran into the same problem. The reason I had the issue was twofold. First, I had accidentally copied a log file into my site-enabled folder. I deleted the log file and made sure that all the files in sites-enabled were proper nginx site configs. I also noticed two of my virtual hosts were listening for the same domain. So I made sure that each of my virtual hosts had unique domain names.

sudo service nginx restart

Then it worked.

How to count the number of rows in excel with data?

I prefer using the CurrentRegion property, which is equivalent to Ctrl-*, which expands the current range to its largest continuous range with data. You start with a cell, or range, which you know will contain data, then expand it. The UsedRange Property sometimes returns huge areas, just because someone did some formatting at the bottom of the sheet.

Dim Liste As Worksheet    
Set Liste = wb.Worksheets("B Leistungen (Liste)")     
Dim longlastrow As Long
longlastrow = Liste.Range(Liste.Cells(4, 1), Liste.Cells(6, 3)).CurrentRegion.Rows.Count

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

The ngRoute module is no longer part of the core angular.js file. If you are continuing to use $routeProvider then you will now need to include angular-route.js in your HTML:

<script src="angular.js">
<script src="angular-route.js">

API Reference

You also have to add ngRoute as a dependency for your application:

var app = angular.module('MyApp', ['ngRoute', ...]);

If instead you are planning on using angular-ui-router or the like then just remove the $routeProvider dependency from your module .config() and substitute it with the relevant provider of choice (e.g. $stateProvider). You would then use the ui.router dependency:

var app = angular.module('MyApp', ['ui.router', ...]);

Breaking out of nested loops

You can also refactor your code to use a generator. But this may not be a solution for all types of nested loops.

How can I debug a .BAT script?

I don't know of anyway to step through the execution of a .bat file but you can use echo and pause to help with debugging.

ECHO
Will echo a message in the batch file. Such as ECHO Hello World will print Hello World on the screen when executed. However, without @ECHO OFF at the beginning of the batch file you'll also get "ECHO Hello World" and "Hello World." Finally, if you'd just like to create a blank line, type ECHO. adding the period at the end creates an empty line.

PAUSE
Prompt the user to press any key to continue.

Source: Batch File Help

@workmad3: answer has more good tips for working with the echo command.

Another helpful resource... DDB: DOS Batch File Tips

List<T> OrderBy Alphabetical Order

private void SortGridGenerico< T >(
          ref List< T > lista       
    , SortDirection sort
    , string propriedadeAOrdenar)
{

    if (!string.IsNullOrEmpty(propriedadeAOrdenar)
    && lista != null
    && lista.Count > 0)
    {

        Type t = lista[0].GetType();

        if (sort == SortDirection.Ascending)
        {

            lista = lista.OrderBy(
                a => t.InvokeMember(
                    propriedadeAOrdenar
                    , System.Reflection.BindingFlags.GetProperty
                    , null
                    , a
                    , null
                )
            ).ToList();
        }
        else
        {
            lista = lista.OrderByDescending(
                a => t.InvokeMember(
                    propriedadeAOrdenar
                    , System.Reflection.BindingFlags.GetProperty
                    , null
                    , a
                    , null
                )
            ).ToList();
        }
    }
}

How to make a flat list out of list of lists?

np.hstack(listoflist).tolist()

How to split a dataframe string column into two columns?

You can use str.split by whitespace (default separator) and parameter expand=True for DataFrame with assign to new columns:

df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA', 
                           '01001 Autauga County, AL', '01003 Baldwin County, AL', 
                           '01005 Barbour County, AL']})
print (df)
                        row
0       00000 UNITED STATES
1             01000 ALABAMA
2  01001 Autauga County, AL
3  01003 Baldwin County, AL
4  01005 Barbour County, AL



df[['a','b']] = df['row'].str.split(n=1, expand=True)
print (df)
                        row      a                   b
0       00000 UNITED STATES  00000       UNITED STATES
1             01000 ALABAMA  01000             ALABAMA
2  01001 Autauga County, AL  01001  Autauga County, AL
3  01003 Baldwin County, AL  01003  Baldwin County, AL
4  01005 Barbour County, AL  01005  Barbour County, AL

Modification if need remove original column with DataFrame.pop

df[['a','b']] = df.pop('row').str.split(n=1, expand=True)
print (df)
       a                   b
0  00000       UNITED STATES
1  01000             ALABAMA
2  01001  Autauga County, AL
3  01003  Baldwin County, AL
4  01005  Barbour County, AL

What is same like:

df[['a','b']] = df['row'].str.split(n=1, expand=True)
df = df.drop('row', axis=1)
print (df)

       a                   b
0  00000       UNITED STATES
1  01000             ALABAMA
2  01001  Autauga County, AL
3  01003  Baldwin County, AL
4  01005  Barbour County, AL

If get error:

#remove n=1 for split by all whitespaces
df[['a','b']] = df['row'].str.split(expand=True)

ValueError: Columns must be same length as key

You can check and it return 4 column DataFrame, not only 2:

print (df['row'].str.split(expand=True))
       0        1        2     3
0  00000   UNITED   STATES  None
1  01000  ALABAMA     None  None
2  01001  Autauga  County,    AL
3  01003  Baldwin  County,    AL
4  01005  Barbour  County,    AL

Then solution is append new DataFrame by join:

df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA', 
                           '01001 Autauga County, AL', '01003 Baldwin County, AL', 
                           '01005 Barbour County, AL'],
                    'a':range(5)})
print (df)
   a                       row
0  0       00000 UNITED STATES
1  1             01000 ALABAMA
2  2  01001 Autauga County, AL
3  3  01003 Baldwin County, AL
4  4  01005 Barbour County, AL

df = df.join(df['row'].str.split(expand=True))
print (df)

   a                       row      0        1        2     3
0  0       00000 UNITED STATES  00000   UNITED   STATES  None
1  1             01000 ALABAMA  01000  ALABAMA     None  None
2  2  01001 Autauga County, AL  01001  Autauga  County,    AL
3  3  01003 Baldwin County, AL  01003  Baldwin  County,    AL
4  4  01005 Barbour County, AL  01005  Barbour  County,    AL

With remove original column (if there are also another columns):

df = df.join(df.pop('row').str.split(expand=True))
print (df)
   a      0        1        2     3
0  0  00000   UNITED   STATES  None
1  1  01000  ALABAMA     None  None
2  2  01001  Autauga  County,    AL
3  3  01003  Baldwin  County,    AL
4  4  01005  Barbour  County,    AL   

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

this also works:

a=pd.DataFrame({'A':a.groupby('A')['B'].max().index,'B':a.groupby('A')       ['B'].max().values})

How to throw an exception in C?

If you write code with Happy path design pattern (i.e. for embedded device) you may simulate exception error processing (aka deffering or finally emulation) with operator "goto".

int process(int port)
{
    int rc;
    int fd1;
    int fd2;

    fd1 = open("/dev/...", ...);
    if (fd1 == -1) {
      rc = -1;
      goto out;
    }

    fd2 = open("/dev/...", ...);
    if (fd2 == -1) {
      rc = -1;
      goto out;
    }

    // Do some with fd1 and fd2 for example write(f2, read(fd1))

    rc = 0;

   out:

    //if (rc != 0) {
        (void)close(fd1);
        (void)close(fd2);
    //}

    return rc;
}

It does not actually exception handler but it take you a way to handle error at fucntion exit.

P.S. You should be careful use goto only from same or more deep scopes and never jump variable declaration.

isPrime Function for Python Language

Of many prime number tests floating around the Internet, consider the following Python function:

def is_prime(n):
  if n == 2 or n == 3: return True
  if n < 2 or n%2 == 0: return False
  if n < 9: return True
  if n%3 == 0: return False
  r = int(n**0.5)
  # since all primes > 3 are of the form 6n ± 1
  # start with f=5 (which is prime)
  # and test f, f+2 for being prime
  # then loop by 6. 
  f = 5
  while f <= r:
    print('\t',f)
    if n % f == 0: return False
    if n % (f+2) == 0: return False
    f += 6
  return True    

Since all primes > 3 are of the form 6n ± 1, once we eliminate that n is:

  1. not 2 or 3 (which are prime) and
  2. not even (with n%2) and
  3. not divisible by 3 (with n%3) then we can test every 6th n ± 1.

Consider the prime number 5003:

print is_prime(5003)

Prints:

 5
 11
 17
 23
 29
 35
 41
 47
 53
 59
 65
True

The line r = int(n**0.5) evaluates to 70 (the square root of 5003 is 70.7318881411 and int() truncates this value)

Consider the next odd number (since all even numbers other than 2 are not prime) of 5005, same thing prints:

 5
False

The limit is the square root since x*y == y*x The function only has to go 1 loop to find that 5005 is divisible by 5 and therefore not prime. Since 5 X 1001 == 1001 X 5 (and both are 5005), we do not need to go all the way to 1001 in the loop to know what we know at 5!


Now, let's look at the algorithm you have:

def isPrime(n):
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False

    return True

There are two issues:

  1. It does not test if n is less than 2, and there are no primes less than 2;
  2. It tests every number between 2 and n**0.5 including all even and all odd numbers. Since every number greater than 2 that is divisible by 2 is not prime, we can speed it up a little by only testing odd numbers greater than 2.

So:

def isPrime2(n):
    if n==2 or n==3: return True
    if n%2==0 or n<2: return False
    for i in range(3, int(n**0.5)+1, 2):   # only odd numbers
        if n%i==0:
            return False    

    return True

OK -- that speeds it up by about 30% (I benchmarked it...)

The algorithm I used is_prime is about 2x times faster still, since only every 6th integer is looping through the loop. (Once again, I benchmarked it.)


Side note: x**0.5 is the square root:

>>> import math
>>> math.sqrt(100)==100**0.5
True

Side note 2: primality testing is an interesting problem in computer science.

Search all tables, all columns for a specific value SQL Server

I've just updated my blog post to correct the error in the script that you were having Jeff, you can see the updated script here: Search all fields in SQL Server Database

As requested, here's the script in case you want it but I'd recommend reviewing the blog post as I do update it from time to time

DECLARE @SearchStr nvarchar(100)
SET @SearchStr = '## YOUR STRING HERE ##'
 
 
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Updated and tested by Tim Gaunt
-- http://www.thesitedoctor.co.uk
-- http://blogs.thesitedoctor.co.uk/tim/2010/02/19/Search+Every+Table+And+Field+In+A+SQL+Server+Database+Updated.aspx
-- Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010
-- Date modified: 03rd March 2011 19:00 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
 
SET NOCOUNT ON
 
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
 
WHILE @TableName IS NOT NULL
 
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
 
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
         
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )
 
        IF @ColumnName IS NOT NULL
         
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END   
END
 
SELECT ColumnName, ColumnValue FROM #Results
 
DROP TABLE #Results

Need to list all triggers in SQL Server database with table name and table's schema

this may help.

SELECT DISTINCT o.[name] AS [Table]
FROM    [sysobjects] o
JOIN    [sysobjects] tr
    ON  o.[id] = tr.[parent_obj]
WHERE   tr.[type] = 'tr'
ORDER BY [Table]

Get a list of tables and all their triggers.

SELECT DISTINCT o.[name] AS [Table], tr.[name] AS [Trigger]
FROM    [sysobjects] o
JOIN    [sysobjects] tr
    ON  o.[id] = tr.[parent_obj]
WHERE   tr.[type] = 'tr'
ORDER BY [Table], [Trigger]

In which case do you use the JPA @JoinTable annotation?

It lets you handle Many to Many relationship. Example:

Table 1: post

post has following columns
____________________
|  ID     |  DATE   |
|_________|_________|
|         |         |
|_________|_________|

Table 2: user

user has the following columns:

____________________
|     ID  |NAME     |
|_________|_________|
|         |         |
|_________|_________|

Join Table lets you create a mapping using:

@JoinTable(
  name="USER_POST",
  joinColumns=@JoinColumn(name="USER_ID", referencedColumnName="ID"),
  inverseJoinColumns=@JoinColumn(name="POST_ID", referencedColumnName="ID"))

will create a table:

____________________
|  USER_ID| POST_ID |
|_________|_________|
|         |         |
|_________|_________|

Validating IPv4 addresses with regexp

''' This code works for me, and is as simple as that.

Here I have taken the value of ip and I am trying to match it with regex.

ip="25.255.45.67"    

op=re.match('(\d+).(\d+).(\d+).(\d+)',ip)

if ((int(op.group(1))<=255) and (int(op.group(2))<=255) and int(op.group(3))<=255) and (int(op.group(4))<=255)):

print("valid ip")

else:

print("Not valid")

Above condition checks if the value exceeds 255 for all the 4 octets then it is not a valid. But before applying the condition we have to convert them into integer since the value is in a string.

group(0) prints the matched output, Whereas group(1) prints the first matched value and here it is "25" and so on. '''

Store mysql query output into a shell variable

myvariable=$(mysql database -u $user -p$password | SELECT A, B, C FROM table_a)

without the blank space after -p. Its trivial, but without don't work.

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

This happened to me after I ran a script with cProfile a la python3 -m cProfile script.py even though xlrd was already installed and had never thrown this error before. it persisted even under python3 script.py. (Granted, I agree this wasn't what happened to OP, given the obvious import error)

However, for cases like mine, the following fixed the issue, despite being told "requirement already met" in every case.

pip install --upgrade pandas
pip install --upgrade xlrd

Pretty confounding stuff; not sure if cProfile was the cause or just a coincidence

The following should work, assuming your pip install operated on python2.

python3 -m pip install xlrd

C# How to change font of a label

You can't change a Font once it's created - so you need to create a new one:

  mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

Which Protocols are used for PING?

Internet Control Message Protocol

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

ICMP is built on top of a bunch of other protocols, so in that sense your TA is correct. However, ping itself is ICMP.

@synthesize vs @dynamic, what are the differences?

Take a look at this article; under the heading "Methods provided at runtime":

Some accessors are created dynamically at runtime, such as certain ones used in CoreData's NSManagedObject class. If you want to declare and use properties for these cases, but want to avoid warnings about methods missing at compile time, you can use the @dynamic directive instead of @synthesize.

...

Using the @dynamic directive essentially tells the compiler "don't worry about it, a method is on the way."

The @synthesize directive, on the other hand, generates the accessor methods for you at compile time (although as noted in the "Mixing Synthesized and Custom Accessors" section it is flexible and does not generate methods for you if either are implemented).

What's the best way to parse command line arguments?

Pretty much everybody is using getopt

Here is the example code for the doc :

import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError:
        # print help information and exit:
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        if o in ("-o", "--output"):
            output = a

So in a word, here is how it works.

You've got two types of options. Those who are receiving arguments, and those who are just like switches.

sys.argv is pretty much your char** argv in C. Like in C you skip the first element which is the name of your program and parse only the arguments : sys.argv[1:]

Getopt.getopt will parse it according to the rule you give in argument.

"ho:v" here describes the short arguments : -ONELETTER. The : means that -o accepts one argument.

Finally ["help", "output="] describes long arguments ( --MORETHANONELETTER ). The = after output once again means that output accepts one arguments.

The result is a list of couple (option,argument)

If an option doesn't accept any argument (like --help here) the arg part is an empty string. You then usually want to loop on this list and test the option name as in the example.

I hope this helped you.

Top 1 with a left join

Because the TOP 1 from the ordered sub-query does not have profile_id = 'u162231993' Remove where u.id = 'u162231993' and see results then.

Run the sub-query separately to understand what's going on.

Send request to curl with post data sourced from a file

Most of answers are perfect here, but when I landed here for my particular problem, I have to upload binary file (XLSX spread sheet) using POST method, I see one thing missing, i.e. usually its not just file you load, you may have more form data elements, like comment to file or tags to file etc as was my case. Hence, I would like to add it here as it was my use case, so that it could help others.

curl -POST -F comment=mycomment -F file_type=XLSX -F file_data=@/your/path/to/file.XLSX http://yourhost.example.com/api/example_url

Gradle DSL method not found: 'runProguard'

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

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

enter image description here

How to install wkhtmltopdf on a linux based (shared hosting) web server

Place the wkhtmltopdf executable on the server and chmod it +x.

Create an executable shell script wrap.sh containing:

#!/bin/sh
export HOME="$PWD"
export LD_LIBRARY_PATH="$PWD/lib/"
exec $@ 2>/dev/null
#exec $@ 2>&1 # debug mode

Download needed shared objects for that architecture and place them an a folder named "lib":

  • lib/libfontconfig.so.1
  • lib/libfontconfig.so.1.3.0
  • lib/libfreetype.so.6
  • lib/libfreetype.so.6.3.18
  • lib/libX11.so.6 lib/libX11.so.6.2.0
  • lib/libXau.so.6 lib/libXau.so.6.0.0
  • lib/libxcb.so.1 lib/libxcb.so.1.0.0
  • lib/libxcb-xlib.so.0
  • lib/libxcb-xlib.so.0.0.0
  • lib/libXdmcp.so.6
  • lib/libXdmcp.so.6.0.0
  • lib/libXext.so.6 lib/libXext.so.6.4.0

(some of them are symlinks)

… and you're ready to go:

./wrap.sh ./wkhtmltopdf-amd64 --page-size A4 --disable-internal-links --disable-external-links "http://www.example.site/" out.pdf

If you experience font problems like squares for all the characters, define TrueType fonts explicitly:

@font-face {
  font-family:Trebuchet MS;
  font-style:normal;
  font-weight:normal;
  src:url("http://www.yourserver.tld/fonts/Trebuchet_MS.ttf");
  format(TrueType);
}

CSS3 Box Shadow on Top, Left, and Right Only

It's better if you just cover the bottom part with another div and you will get consistent drop shadow across the board.

#servicesContainer {
  /*your css*/
  position: relative;
}

and it's fixed! like magic!

Get the index of a certain value in an array in PHP

array_search is the way to do it.

array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed

From the docs:

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;

You could loop over the array manually and find the index but why do it when there's a function for that. This function always returns a key and it will work well with associative and normal arrays.

Oracle - How to create a readonly user

create user ro_role identified by ro_role;
grant create session, select any table, select any dictionary to ro_role;

Oracle Add 1 hour in SQL

The calculation is simple

if you want to add 1 hour in the date .

every day have 24 hour , you can add .

select sysdate + 1/24 from dual; 

if you want 1 day to add

select sysdate + 24/24 from dual; 

or 

select sysdate + 1 from dual; 

same as for 2, 3 , 4 day

For static date you have the answer below.

No submodule mapping found in .gitmodule for a path that's not a submodule

Following rajibchowdhury's answer (upvoted), use git rm command which is advised is for removing the special entry in the index indicating a submodule (a 'folder' with a special mode 160000).

If that special entry path isn't referenced in the .gitmodule (like 'Classes/Support/Three20' in the original question), then you need to remove it, in order to avoid the "No submodule mapping found in .gitmodules for path" error message.

You can check all the entries in the index which are referencing submodules:

git ls-files --stage | grep 160000

Previous answer (November 2010)

It is possible that you haven't declared your initial submodule correctly (i.e. without any tail '/' at the end, as described in my old answer, even though your .gitmodule has paths which looks ok in it).

This thread mentions:

do you get the same error when running 'git submodule init' from a fresh clone?
If so, you have something wrong.

If you have no submodules, delete .gitmodules, and any references to submodules in .git/config, and ensure the Pikimal dir does not have a .git dir in it.
If that fixes the problem, check in and do the same on your cruise working copy.

Obviously, don't delete your main .gitmodules file, but look after other extra .gitmodules files in your working tree.


Still in the topic of "incorrect submodule initialization", Jefromi mentions submodules which actually are gitlinks.

See How to track untracked content? in order to convert such a directory to a real submodule.

React - Component Full Screen (with height 100%)

I managed this with a css class in my app.css

.fill-window {
    height: 100%;
    position: absolute;
    left: 0;
    width: 100%;
    overflow: hidden;
}

Apply it to your root element in your render() method

render() {
   return ( <div className="fill-window">{content}</div> );
}

Or inline

render() {
   return (
      <div style={{ height: '100%', position: 'absolute', left: '0px', width: '100%', overflow: 'hidden'}}>
          {content}
      </div>
   );
}

Programmatically shut down Spring Boot application

Closing a SpringApplication basically means closing the underlying ApplicationContext. The SpringApplication#run(String...) method gives you that ApplicationContext as a ConfigurableApplicationContext. You can then close() it yourself.

For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to shut down...
        ctx.close();
    }
}

Alternatively, you can use the static SpringApplication.exit(ApplicationContext, ExitCodeGenerator...) helper method to do it for you. For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to stop...
        int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
            @Override
            public int getExitCode() {
                // no errors
                return 0;
            }
        });

        // or shortened to
        // int exitCode = SpringApplication.exit(ctx, () -> 0);

        System.exit(exitCode);
    }
}

Java: using switch statement with enum under subclass

This is how I am using it. And it is working fantastically -

public enum Button {
        REPORT_ISSUES(0),
        CANCEL_ORDER(1),
        RETURN_ORDER(2);

        private int value;

        Button(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }

And the switch-case as shown below

@Override
public void onClick(MyOrderDetailDelgate.Button button, int position) {
    switch (button) {
        case REPORT_ISSUES: {
            break;
        }
        case CANCEL_ORDER: {
            break;
        }
        case RETURN_ORDER: {
            break;
        }
    }
}

How to set the color of "placeholder" text?

Try this

_x000D_
_x000D_
input::-webkit-input-placeholder { /* WebKit browsers */_x000D_
    color:    #f51;_x000D_
}_x000D_
input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */_x000D_
    color:    #f51;_x000D_
}_x000D_
input::-moz-placeholder { /* Mozilla Firefox 19+ */_x000D_
    color:    #f51;_x000D_
}_x000D_
input:-ms-input-placeholder { /* Internet Explorer 10+ */_x000D_
    color:    #f51;_x000D_
}
_x000D_
<input type="text" placeholder="Value" />
_x000D_
_x000D_
_x000D_

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

Sometimes things might be simpler. I came here with the exact issue and tried all the suggestions. But later found that the problem was just the local file path was different and I was on a different folder. :-)

eg -

~/myproject/mygitrepo/app/$ git diff app/TestFile.txt

should have been

~/myproject/mygitrepo/app/$ git diff TestFile.txt

installation app blocked by play protect

I am adding this answer for others who are still seeking a solution to this problem if you don't want to upload your app on playstore then temporarily there is a workaround for this problem.

Google is providing safety device verification api which you need to call only once in your application and after that your application will not be blocked by play protect:

Here are there the links:

https://developer.android.com/training/safetynet/attestation#verify-attestation-response

Link for sample code project:

https://github.com/googlesamples/android-play-safetynet

Calculate distance between 2 GPS coordinates

PHP version:

(Remove all deg2rad() if your coordinates are already in radians.)

$R = 6371; // km
$dLat = deg2rad($lat2-$lat1);
$dLon = deg2rad($lon2-$lon1);
$lat1 = deg2rad($lat1);
$lat2 = deg2rad($lat2);

$a = sin($dLat/2) * sin($dLat/2) +
     sin($dLon/2) * sin($dLon/2) * cos($lat1) * cos($lat2); 

$c = 2 * atan2(sqrt($a), sqrt(1-$a)); 
$d = $R * $c;

How do I set up NSZombieEnabled in Xcode 4?

In Xcode 4.2

  • Project Name/Edit Scheme/Diagnostics/
  • Enable Zombie Objects check box
  • You're done

How to set background color of a button in Java GUI?

Simple:

btn.setBackground(Color.red);

To use RGB values:

btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));

break statement in "if else" - java

The issue is that you are trying to have multiple statements in an if without using {}. What you currently have is interpreted like:

if( choice==5 )
{
    System.out.println( ... );
}
break;
else
{
    //...
}

You really want:

if( choice==5 )
{
    System.out.println( ... );
    break;
}
else
{
    //...
}

Also, as Farce has stated, it would be better to use else if for all the conditions instead of if because if choice==1, it will still go through and check if choice==5, which would fail, and it will still go into your else block.

if( choice==1 )
    //...
else if( choice==2 )
    //...
else if( choice==3 )
    //...
else if( choice==4 )
    //...
else if( choice==5 )
{
    //...
}
else
    //...

A more elegant solution would be using a switch statement. However, break only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:

LOOP:
for(;;)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch( choice )
    {
        case 1:
            playGame();
            break;
        case 2:
            loadGame();
            break;
        case 2:
            options();
            break;
        case 4:
            credits();
            break;
        case 5:
            System.out.println("End of Game\n Thank you for playing with us!");
            break LOOP;
        default:
            System.out.println( ... );
    }
}

Instead of labeling the loop, you could also use a flag to tell the loop to stop.

bool finished = false;
while( !finished )
{
    switch( choice )
    {
        // ...
        case 5:
            System.out.println( ... )
            finished = true;
            break;
        // ...
    }
}

PHP create key => value pairs within a foreach

In PHP >= 5.3 it can be done like this:

$offerArray = array_map(function($value) {
    return $value[4];
}, $offer);

Ant is using wrong java version

You can use the target and source properties on the javac tag to set a target runtime. The example below will compile any source code to target version 1.4 on any compiler that supports version 1.4 or later.

<javac compiler="classic" taskname="javac" includeAntRuntime="no" fork=" deprecation="true" target="1.4" source="1.4" srcdir="${src}" destdir="${classes}">

Note: The 'srcdir' and 'destdir' are property values set else where in the build script, e.g. <property name="classes" value="c:/classes" />

Convert php array to Javascript

If you need a multidimensional PHP array to be printed directly into the html page source code, and in an indented human-readable Javascript Object Notation (aka JSON) fashion, use this nice function I found in http://php.net/manual/en/function.json-encode.php#102091 coded by somebody nicknamed "bohwaz".

<?php

function json_readable_encode($in, $indent = 0, $from_array = false)
{
    $_myself = __FUNCTION__;
    $_escape = function ($str)
    {
        return preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
    };

    $out = '';

    foreach ($in as $key=>$value)
    {
        $out .= str_repeat("\t", $indent + 1);
        $out .= "\"".$_escape((string)$key)."\": ";

        if (is_object($value) || is_array($value))
        {
            $out .= "\n";
            $out .= $_myself($value, $indent + 1);
        }
        elseif (is_bool($value))
        {
            $out .= $value ? 'true' : 'false';
        }
        elseif (is_null($value))
        {
            $out .= 'null';
        }
        elseif (is_string($value))
        {
            $out .= "\"" . $_escape($value) ."\"";
        }
        else
        {
            $out .= $value;
        }

        $out .= ",\n";
    }

    if (!empty($out))
    {
        $out = substr($out, 0, -2);
    }

    $out = str_repeat("\t", $indent) . "{\n" . $out;
    $out .= "\n" . str_repeat("\t", $indent) . "}";

    return $out;
}

?>       

How to keep onItemSelected from firing off on a newly instantiated Spinner?

No unwanted events from the layout phase if you defer adding the listener till the layout is finished:

spinner.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            // Ensure you call it only once works for JELLY_BEAN and later
            spinner.getViewTreeObserver().removeOnGlobalLayoutListener(this);

            // add the listener
            spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                    // check if pos has changed
                    // then do your work
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                }

            });

        }
    });

Java, Calculate the number of days between two dates

This function is good for me:

public static int getDaysCount(Date begin, Date end) {
    Calendar start = org.apache.commons.lang.time.DateUtils.toCalendar(begin);
    start.set(Calendar.MILLISECOND, 0);
    start.set(Calendar.SECOND, 0);
    start.set(Calendar.MINUTE, 0);
    start.set(Calendar.HOUR_OF_DAY, 0);

    Calendar finish = org.apache.commons.lang.time.DateUtils.toCalendar(end);
    finish.set(Calendar.MILLISECOND, 999);
    finish.set(Calendar.SECOND, 59);
    finish.set(Calendar.MINUTE, 59);
    finish.set(Calendar.HOUR_OF_DAY, 23);

    long delta = finish.getTimeInMillis() - start.getTimeInMillis();
    return (int) Math.ceil(delta / (1000.0 * 60 * 60 * 24));
}

Java ArrayList clear() function

If you in any doubt, have a look at JDK source code

ArrayList.clear() source code:

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

You will see that size is set to 0 so you start from 0 position.

Please note that when adding elements to ArrayList, the backend array is extended (i.e. array data is copied to bigger array if needed) in order to be able to add new items. When performing ArrayList.clear() you only remove references to array elements and sets size to 0, however, capacity stays as it was.

Setting the selected value on a Django forms.ChoiceField

Both Tom and Burton's answers work for me eventually, but I had a little trouble figuring out how to apply them to a ModelChoiceField.

The only trick to it is that the choices are stored as tuples of (<model's ID>, <model's unicode repr>), so if you want to set the initial model selection, you pass the model's ID as the initial value, not the object itself or it's name or anything else. Then it's as simple as:

form = EmployeeForm(initial={'manager': manager_employee_id})

Alternatively the initial argument can be ignored in place of an extra line with:

form.fields['manager'].initial = manager_employee_id

Bash if statement with multiple conditions throws an error

You can get some inspiration by reading an entrypoint.sh script written by the contributors from MySQL that checks whether the specified variables were set.

As the script shows, you can pipe them with -a, e.g.:

if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
    ...
fi

Get current date in milliseconds

Casting the NSTimeInterval directly to a long overflowed for me, so instead I had to cast to a long long.

long long milliseconds = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);

The result is a 13 digit timestamp as in Unix.

How to do date/time comparison

Recent protocols prefer usage of RFC3339 per golang time package documentation.

In general RFC1123Z should be used instead of RFC1123 for servers that insist on that format, and RFC3339 should be preferred for new protocols. RFC822, RFC822Z, RFC1123, and RFC1123Z are useful for formatting; when used with time.Parse they do not accept all the time formats permitted by the RFCs.

cutOffTime, _ := time.Parse(time.RFC3339, "2017-08-30T13:35:00Z")
// POSTDATE is a date time field in DB (datastore)
query := datastore.NewQuery("db").Filter("POSTDATE >=", cutOffTime).

Error 1022 - Can't write; duplicate key in table

I also encountered that problem.Check if database name already exist in Mysql,and rename the old one.

AngularJS resource promise

If you want to use asynchronous method you need to use callback function by $promise, here is example:

var Regions = $resource('mocks/regions.json');

$scope.regions = Regions.query();
$scope.regions.$promise.then(function (result) {
    $scope.regions = result;
});

Postgresql Select rows where column = array

For dynamic SQL use:

'IN(' ||array_to_string(some_array, ',')||')'

Example

DO LANGUAGE PLPGSQL $$

DECLARE
    some_array bigint[];
    sql_statement text;

BEGIN

    SELECT array[1, 2] INTO some_array;
    RAISE NOTICE '%', some_array;

    sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
    RAISE NOTICE '%', sql_statement;

END;

$$;

Result: NOTICE: {1,2} NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)

Best algorithm for detecting cycles in a directed graph

If you can't add a "visited" property to the nodes, use a set (or map) and just add all visited nodes to the set unless they are already in the set. Use a unique key or the address of the objects as the "key".

This also gives you the information about the "root" node of the cyclic dependency which will come in handy when a user has to fix the problem.

Another solution is to try to find the next dependency to execute. For this, you must have some stack where you can remember where you are now and what you need to do next. Check if a dependency is already on this stack before you execute it. If it is, you've found a cycle.

While this might seem to have a complexity of O(N*M) you must remember that the stack has a very limited depth (so N is small) and that M becomes smaller with each dependency that you can check off as "executed" plus you can stop the search when you found a leaf (so you never have to check every node -> M will be small, too).

In MetaMake, I created the graph as a list of lists and then deleted every node as I executed them which naturally cut down the search volume. I never actually had to run an independent check, it all happened automatically during normal execution.

If you need a "test only" mode, just add a "dry-run" flag which disables the execution of the actual jobs.

Catching FULL exception message

I found it!

Simply print out $Error[0] for the last error message.

Throwing exceptions in a PHP Try Catch block

Throw needs an object instantiated by \Exception. Just the $e catched can play the trick.

throw $e

Convert string to number and add one

a nice way from http://try.jquery.com/levels/4/challenges/16 :

adding a + before the string without using parseInt and parseFloat and radix and errors i faced for missing radix parameter

sample

var number= +$('#inputForm').val();

Styles.Render in MVC4

Set this to False on your web.config

<compilation debug="false" targetFramework="4.6.1" />

How do I output the results of a HiveQL query to CSV?

You can use INSERTDIRECTORY …, as in this example:

INSERT OVERWRITE LOCAL DIRECTORY '/tmp/ca_employees'
SELECT name, salary, address
FROM employees
WHERE se.state = 'CA';

OVERWRITE and LOCAL have the same interpretations as before and paths are interpreted following the usual rules. One or more files will be written to /tmp/ca_employees, depending on the number of reducers invoked.

Broken references in Virtualenvs

What fixed it for me was just uninstalling python3 and pipenv then reinstalling them.

brew uninstall pipenv
brew uninstall python3
brew install python3 
brew install pipenv

How can I emulate a get request exactly like a web browser?

Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at http://docs.php.net/function.curl-setopt.
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.

edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.

$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

I think the answer for your question is here

To have Chrome send Access-Control-Allow-Origin in the header, just alias your localhost in your /etc/hosts file to some other domain, like:

127.0.0.1 localhost yourdomain.com

An URL to a Windows shared folder

File protocol URIs are like this

file://[HOST]/[PATH]

that's why you often see file URLs like this (3 slashes) file:///c:\path...

So if the host is server01, you want

file://server01/folder/path....

This is according to the wikipedia page on file:// protocols and checks out with .NET's Uri.IsWellFormedUriString method.

How do I set default value of select box in angularjs

You can simple use ng-init like this

<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>

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

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

On the documentation:

http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat

It says:

(...) if you know the matrix element type, e.g. it is float, then you can use at<>() method

That is, you can use:

Mat M(100, 100, CV_64F);
cout << M.at<double>(0,0);

Maybe it is easier to use the Mat_ class. It is a template wrapper for Mat. Mat_ has the operator() overloaded in order to access the elements.

CSS selector for a checked radio button's label

I know this is an old question, but if you would like to have the <input> be a child of <label> instead of having them separate, here is a pure CSS way that you could accomplish it:

:checked + span { font-weight: bold; }

Then just wrap the text with a <span>:

<label>
   <input type="radio" name="test" />
   <span>Radio number one</span>
</label>

See it on JSFiddle.

Filter Extensions in HTML form upload

You can do it using javascript. Grab the value of the form field in your submit function, parse out the extension.

You can start with something like this:

<form name="someform"enctype="multipart/form-data" action="uploader.php" method="POST">
<input type=file name="file1" />
<input type=button onclick="val()" value="xxxx" />
</form>
<script>
function val() {
    alert(document.someform.file1.value)
}
</script>

I agree with alexmac - do it server-side as well.

Best way to implement multi-language/globalization in large .NET project

+1 Database

Forms in your app can even re-translate themselves on the fly if corrections are made to the database.

We used a system where all the controls were mapped in an XML file (one per form) to language resource IDs, but all the IDs were in the database.

Basically, instead of having each control hold the ID (implementing an interface, or using the tag property in VB6), we used the fact that in .NET, the control tree was easily discoverable through reflection. A process when the form loaded would build the XML file if it was missing. The XML file would map the controls to their resource IDs, so this simply needed to be filled in and mapped to the database. This meant that there was no need to change the compiled binary if something was not tagged, or if it needed to be split to another ID (some words in English which might be used as both nouns and verbs might need to translate to two different words in the dictionary and not be re-used, but you might not discover this during initial assignment of IDs). But the fact is that the whole translation process becomes completely independent of your binary (every form has to inherit from a base form which knows how to translate itself and all its controls).

The only ones where the app gets more involved is when a phase with insertion points is used.

The database translation software was your basic CRUD maintenance screen with various workflow options to facilitate going through the missing translations, etc.

Setting selected option in laravel form

            @foreach ($categories as $category)
             <option value="{{$category->id}}" 
               @foreach ($posts->postRelateToCategory as $Postcategory)
                 @if ($Postcategory->id == $category->id)
                 {{'selected="selected"'}}
                 @endif 
               @endforeach >
              {{ $category->category_name }} </option>               
            @endforeach    

JS map return object

Use .map without return in simple way. Also start using let and const instead of var because let and const is more recommended

_x000D_
_x000D_
const rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
const launchOptimistic = rockets.map(elem => (_x000D_
  {_x000D_
    country: elem.country,_x000D_
    launches: elem.launches+10_x000D_
  } _x000D_
));_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
_x000D_
_x000D_

Using import fs from 'fs'

ES6 modules support in Node.js is fairly recent; even in the bleeding-edge versions, it is still experimental. With Node.js 10, you can start Node.js with the --experimental-modules flag, and it will likely work.

To import on older Node.js versions - or standard Node.js 10 - use CommonJS syntax:

const fs = require('fs');

Putting an if-elif-else statement on one line?

if i > 100:
    x = 2
elif i < 100:
    x = 1
else:
    x = 0

If you want to use the above-mentioned code in one line, you can use the following:

x = 2 if i > 100 else 1 if i < 100 else 0

On doing so, x will be assigned 2 if i > 100, 1 if i < 100 and 0 if i = 100

How do I get this javascript to run every second?

Use setInterval:

$(function(){
setInterval(oneSecondFunction, 1000);
});

function oneSecondFunction() {
// stuff you want to do every second
}

Here's an article on the difference between setTimeout and setInterval. Both will provide the functionality you need, they just require different implementations.

How does Subquery in select statement work in oracle

In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.

Git error: "Please make sure you have the correct access rights and the repository exists"

Like other answers, use https instead of ssh was the solution.

I post an answer to give a concrete example of a possible solution. I solved this issue with bitbucket when I changed remote url to HTTPS with this command line:

git remote set-url origin <bitbucket_URL>

After that, I could push the content to the repository with this command:

git push -u origin --all

And then I could also use Sourcetree

How can one check to see if a remote file exists using PHP?

function remote_file_exists($url){
   return(bool)preg_match('~HTTP/1\.\d\s+200\s+OK~', @current(get_headers($url)));
}  
$ff = "http://www.emeditor.com/pub/emed32_11.0.5.exe";
    if(remote_file_exists($ff)){
        echo "file exist!";
    }
    else{
        echo "file not exist!!!";
    }

Response Content type as CSV

I have found that the problem with IE is that it sniffs the return data and makes up its own mind about what content-type it thinks it has been sent. There are a number of side effect that this causes, such as always openning a saveAs dialog for text files because you are using compression of data trasnferes. The solution is (in php code)......

header('X-Content-Type-Options: nosniff');

How to change UIPickerView height

In iOS 4.2 & 4.3 the following works:

UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.frame = CGRectMake(0, 0, 320, 180);
[self addSubview:datePicker];

The following does not work:

UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
[self addSubview:datePicker];

I have an app that is in the app store with a 3 line date picker. I thought the height change may have been prevented because you see the text under the date picker's border, but this happens to the normal 216 height date picker too.

Which is the bug? Your guess is as good as mine.

Also there are 3 valid heights for UIDatePicker (and UIPickerView) 162.0, 180.0, and 216.0. If you set a UIPickerView height to anything else you will see the following in the console when debugging on an iOS device.

2011-09-14 10:06:56.180 DebugHarness[1717:707] -[UIPickerView setFrame:]: invalid height value 300.0 pinned to 216.0

Entry point for Java applications: main(), init(), or run()?

The main() method is the entry point for a Java application. run() is typically used for new threads or tasks.

Where have you been writing a run() method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?

How to check if the given string is palindrome?

public static boolean isPalindrome( String str ) {
    int count = str.length() ;
    int i, j = count - 1 ;
    for ( i = 0 ; i < count ; i++ ) {
        if ( str.charAt(i) != str.charAt(j) ) return false ;
        if ( i == j ) return true ;
        j-- ;
    }
    return true ;
}

IntelliJ does not show project folders

I have a better solution that worked for me and it might work for you. No need to delete the whole .idea folder as this way you lose the whole project. It is possible that you just accidentally excluded all folders in project settings. I also found that project folders disappeared. I was trying to find out how to disable indexing, so I was looking at Project Settings -> Modules and I clicked on Excluded to see if I could add the whole project there to ignore it for indexing. It didn't do anything and I couldn't drag and drop the folder under Excluded. What I didn't realize is that simply clicking "Excluded", IntelliJ automatically moves the folder to Excluded and all folders disappeared in Project Explorer. "Excluded" button changes background to gray, which means exclusion is active. This is a very poor user interface because it is hardly noticeable and clicking this button has a far-reaching impact on your project.

Fix:

  1. Open Project Settings -> Modules
  2. If Excluded is highlighted, click on it
  3. Click Apply or Close

Result: Folders in your project show up again

Really bad bad bad UI design! Source and Excluded buttons look like tabs when they work in fact as "Checkboxes"!

Be careful, just clicking Sources or Excluded seems like an innocent selection of tab without any visible effect, yet it has far-reaching consequences, basically adding or removing files from the build process.

Make div 100% Width of Browser Window

.myDiv {
    background-color: red;
    width: 100%;
    min-height: 100vh;
    max-height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    margin: 0 auto;
}

Basically, we're fixing the div's position regardless of it's parent, and then position it using margin: 0 auto; and settings its position at the top left corner.

How to get the list of properties of a class?

I am also facing this kind of requirement.

From this discussion I got another Idea,

Obj.GetType().GetProperties()[0].Name

This is also showing the property name.

Obj.GetType().GetProperties().Count();

this showing number of properties.

Thanks to all. This is nice discussion.

$(this).attr("id") not working

Because of the way the function is called (i.e. as a simple call to a function variable), this is the global object (for which window is an alias in browsers). Use the obj parameter instead.

Also, creating a jQuery object and the using its attr() method for obtaining an element ID is inefficient and unnecessary. Just use the element's id property, which works in all browsers.

function showHideOther(obj){ 
    var sel = obj.options[obj.selectedIndex].value;
    var ID = obj.id;

    if (sel == 'other') { 
        $(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
    } else {
        $(obj).css({'display' : 'none'});
    }
}

How to generate random number with the specific length in python

Does 0 count as a possible first digit? If so, then you need random.randint(0,10**n-1). If not, random.randint(10**(n-1),10**n-1). And if zero is never allowed, then you'll have to explicitly reject numbers with a zero in them, or draw n random.randint(1,9) numbers.

Aside: it is interesting that randint(a,b) uses somewhat non-pythonic "indexing" to get a random number a <= n <= b. One might have expected it to work like range, and produce a random number a <= n < b. (Note the closed upper interval.)

Given the responses in the comments about randrange, note that these can be replaced with the cleaner random.randrange(0,10**n), random.randrange(10**(n-1),10**n) and random.randrange(1,10).

Optimal number of threads per core

4000 threads at one time is pretty high.

The answer is yes and no. If you are doing a lot of blocking I/O in each thread, then yes, you could show significant speedups doing up to probably 3 or 4 threads per logical core.

If you are not doing a lot of blocking things however, then the extra overhead with threading will just make it slower. So use a profiler and see where the bottlenecks are in each possibly parallel piece. If you are doing heavy computations, then more than 1 thread per CPU won't help. If you are doing a lot of memory transfer, it won't help either. If you are doing a lot of I/O though such as for disk access or internet access, then yes multiple threads will help up to a certain extent, or at the least make the application more responsive.

Convert Json String to C# Object List

Please make sure that all properties are both the getter and setter. In case, any property is getter only, it will cause the reverting the List to original data as the JSON string is typed.

Please refer to the following code snippet for the same: Model:

 public class Person
{
    public int ID { get; set; }
    // following 2 lines are cause of error
    //public string Name { get { return string.Format("{0} {1}", First, Last); } }
    //public string Country { get { return Countries[CountryID]; } }
    public int CountryID { get; set; }
    public bool Active { get; set; }
    public string First { get; set; }
    public string Last { get; set; }
    public DateTime Hired { get; set; }
}
public class ModelObj
    {
        public string Str { get; set; }
        public List<Person> Persons { get; set; }
    }

Controller:

 [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        var data = new ModelObj();
        data.Str = (string)collection.GetValue("Str").ConvertTo(typeof(string));
        var personsString = (string)collection.GetValue("Persons").ConvertTo(typeof(string));
        using (var textReader = new StringReader(personsString))
        {
            using (var reader = new JsonTextReader(textReader))
            {
                data.Persons = new JsonSerializer().Deserialize(reader, typeof(List<Person>)) as List<Person>; 
            }
        }

        return View(data);
    }

How can I extract substrings from a string in Perl?

You could use a regular expression such as the following:

/([-a-z0-9]+)\s*\((.*?)\)\s*(\*)?/

So for example:

$s = "abc-456-hu5t10 (High priority) *";
$s =~ /([-a-z0-9]+)\s*\((.*?)\)\s*(\*)?/;
print "$1\n$2\n$3\n";

prints

abc-456-hu5t10
High priority
*

Referring to the null object in Python

Per Truth value testing, 'None' directly tests as FALSE, so the simplest expression will suffice:

if not foo:

Best solution to protect PHP code without encryption

The only way to really protect your php-applications from other, is to not share the source code. If you post you code somewhere online, or send it to you customers by some medium, other people than you have access to the code.

You could add an unique watermark to every single copy of your code. That way you can trace leaks back to a singe customer. (But will that help you, since the code already are outside of your control?)

Most code I see comes with a licence and maybe a warranty. A line at the top of the script telling people not to alter the script, will maybe be enought. Self; when I find non-open source code, I won't use it in my projects. Maybe I'm a bit dupe, but I expect ppl not to use my none-OSS code!

MySQL compare now() (only date, not time) with a datetime field

Compare date only instead of date + time (NOW) with:

CURDATE()

How to write a simple Html.DropDownListFor()?

Avoid of lot of fat fingering by starting with a Dictionary in the Model

namespace EzPL8.Models
{
    public class MyEggs
    {
        public Dictionary<int, string> Egg { get; set; }

        public MyEggs()
        {
            Egg = new Dictionary<int, string>()
            {
                { 0, "No Preference"},
                { 1, "I hate eggs"},
                { 2, "Over Easy"},
                { 3, "Sunny Side Up"},
                { 4, "Scrambled"},
                { 5, "Hard Boiled"},
                { 6, "Eggs Benedict"}
            };

    }


    }

In the View convert it to a list for display

@Html.DropDownListFor(m => m.Egg.Keys,
                         new SelectList(
                             Model.Egg, 
                             "Key", 
                             "Value"))

How can query string parameters be forwarded through a proxy_pass with nginx?

To redirect Without Query String add below lines in Server block under listen port line:

if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/;
}

With Query String:

if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/?$query_string;
}

How to get value by key from JObject?

This should help -

var json = "{'@STARTDATE': '2016-02-17 00:00:00.000',  '@ENDDATE': '2016-02-18 23:59:00.000' }";
var fdate = JObject.Parse(json)["@STARTDATE"];

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

Apparently YouTube constantly polls for Google Cast scripts even if the extension isn't installed.

From one commenter:

... it appears that Chrome attempts to get cast_sender.js on pages that have YouTube content. I'm guessing when Chrome sees media that it can stream it attempts to access the Chromecast extension. When the extension isn't present, the error is thrown.

Read more

The only solution I've come across is to install the Google Cast extension, whether you need it or not. You may then hide the toolbar button.

For more information and updates, see this SO question. Here's the official issue.

ImportError: No module named _ssl

If you built Python from source, this is just a matter of dependencies: since you miss OpenSSL lib installed, python silently fails installing the _ssl module. You can see it in the final report of the make command:

Python build finished, but the necessary bits to build these modules were not found:
_bsddb             _sqlite3           _ssl
_tkinter           bsddb185           dbm
dl                 gdbm               imageop
sunaudiodev
To find the necessary bits, look in setup.py in detect_modules() for the module's name.

Installing OpenSSL lib in any of the standard lib paths (/usr/lib, /usr/local/lib...) should do the trick. Anyway this is how I did :-)

Node.js: for each … in not working

for those used to php:

//add this function
function foreach(arr, func){
  for(var i in arr){
    func(i, arr[i]);
  }
}

usage:

foreach(myArray, function(i, v){
  //run code here
});

similar to php version:

foreach(myArray as i=>v){
  //run code here
}

How to get the name of the current Windows user in JavaScript

I think is not possible to do that. It would be a huge security risk if a browser access to that kind of personal information

How to parse XML and count instances of a particular node attribute?

Here a very simple but effective code using cElementTree.

try:
    import cElementTree as ET
except ImportError:
  try:
    # Python 2.5 need to import a different module
    import xml.etree.cElementTree as ET
  except ImportError:
    exit_err("Failed to import cElementTree from any known place")      

def find_in_tree(tree, node):
    found = tree.find(node)
    if found == None:
        print "No %s in file" % node
        found = []
    return found  

# Parse a xml file (specify the path)
def_file = "xml_file_name.xml"
try:
    dom = ET.parse(open(def_file, "r"))
    root = dom.getroot()
except:
    exit_err("Unable to open and parse input definition file: " + def_file)

# Parse to find the child nodes list of node 'myNode'
fwdefs = find_in_tree(root,"myNode")

This is from "python xml parse".

Is it possible to add dynamically named properties to JavaScript object?

ES6 for the win!

const b = 'b';
const c = 'c';

const data = {
    a: true,
    [b]: true, // dynamic property
    [`interpolated-${c}`]: true, // dynamic property + interpolation
    [`${b}-${c}`]: true
}

If you log data you get this:

{
  a: true,
  b: true,
  interpolated-c: true,
  b-c: true
}

This makes use of the new Computed Property syntax and Template Literals.

Is there a way to create multiline comments in Python?

Among other answers, I find the easiest way is to use the IDE comment functions which use the Python comment support of #.

I am using Anaconda Spyder and it has:

  • Ctrl + 1 - Comment/uncomment
  • Ctrl + 4 - Comment a block of code
  • Ctrl + 5 - Uncomment a block of code

It would comment/uncomment a single/multi line/s of code with #.

I find it the easiest.

For example, a block comment:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================

How can I convert the "arguments" object to an array in JavaScript?

Here's a clean and concise solution:

_x000D_
_x000D_
function argsToArray() {_x000D_
  return Object.values(arguments);_x000D_
}_x000D_
_x000D_
// example usage_x000D_
console.log(_x000D_
  argsToArray(1, 2, 3, 4, 5)_x000D_
  .map(arg => arg*11)_x000D_
);
_x000D_
_x000D_
_x000D_

Object.values( ) will return the values of an object as an array, and since arguments is an object, it will essentially convert arguments into an array, thus providing you with all of an array's helper functions such as map, forEach, filter, etc.

How to substitute shell variables in complex text files

In reference to answer 2, when discussing envsubst, you asked:

How can I make it work with the variables that are declared in my .sh script?

The answer is you simply need to export your variables before calling envsubst.

You can also limit the variable strings you want to replace in the input using the envsubst SHELL_FORMAT argument (avoiding the unintended replacement of a string in the input with a common shell variable value - e.g. $HOME).

For instance:

export VAR1='somevalue' VAR2='someothervalue'
MYVARS='$VAR1:$VAR2'

envsubst "$MYVARS" <source.txt >destination.txt

Will replace all instances of $VAR1 and $VAR2 (and only VAR1 and VAR2) in source.txt with 'somevalue' and 'someothervalue' respectively.

PHP: Count a stdClass object

There is nothing wrong with count() here, "trends" is the only key that is being counted in this case, you can try doing:

count($obj->trends);

Or:

count($obj->trends['2009-08-21 11:05']);

Or maybe even doing:

count($obj, COUNT_RECURSIVE);

Regex: ignore case sensitivity

As I discovered from this similar post (ignorecase in AWK), on old versions of awk (such as on vanilla Mac OS X), you may need to use 'tolower($0) ~ /pattern/'.

IGNORECASE or (?i) or /pattern/i will either generate an error or return true for every line.

How to send json data in the Http request using NSURLRequest

Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):

NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
  [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

NSString *jsonRequest = [jsonDict JSONRepresentation];

NSLog(@"jsonRequest is %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
 receivedData = [[NSMutableData data] retain];
}

The receivedData is then handled by:

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];

This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made. Hope that helps.

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

My problem was that I had the wrong MS Sync FrameWork version (1.0) in my project References. After update to the version 2.1, the error was gone and life is good again.

Using Mockito to test abstract classes

If you just need to test some of the concrete methods without touching any of the abstracts, you can use CALLS_REAL_METHODS (see Morten's answer), but if the concrete method under test calls some of the abstracts, or unimplemented interface methods, this won't work -- Mockito will complain "Cannot call real method on java interface."

(Yes, it's a lousy design, but some frameworks, e.g. Tapestry 4, kind of force it on you.)

The workaround is to reverse this approach -- use the ordinary mock behavior (i.e., everything's mocked/stubbed) and use doCallRealMethod() to explicitly call out the concrete method under test. E.g.

public abstract class MyClass {
    @SomeDependencyInjectionOrSomething
    public abstract MyDependency getDependency();

    public void myMethod() {
        MyDependency dep = getDependency();
        dep.doSomething();
    }
}

public class MyClassTest {
    @Test
    public void myMethodDoesSomethingWithDependency() {
        MyDependency theDependency = mock(MyDependency.class);

        MyClass myInstance = mock(MyClass.class);

        // can't do this with CALLS_REAL_METHODS
        when(myInstance.getDependency()).thenReturn(theDependency);

        doCallRealMethod().when(myInstance).myMethod();
        myInstance.myMethod();

        verify(theDependency, times(1)).doSomething();
    }
}

Updated to add:

For non-void methods, you'll need to use thenCallRealMethod() instead, e.g.:

when(myInstance.myNonVoidMethod(someArgument)).thenCallRealMethod();

Otherwise Mockito will complain "Unfinished stubbing detected."

NSURLErrorDomain error codes description

I received the error Domain=NSURLErrorDomain Code=-1011 when using Parse, and providing the wrong clientKey. As soon as I corrected that, it began working.

how to change namespace of entire project?

In asp.net is more to do, to get completely running under another namespace.

  • Copy your source folder and rename it to your new project name.
  • Open it and Replace all by Ctrl + H and be sure to include all Replace everything
  • Press F2 on your Projectname and rename it to your new project name
  • go to your project properties and adjust it, coz everything has gone and you need to make a new Debug Profile Profile to Create
  • All dependencies have now an exclamation mark - restart visual studio
  • Clean your solution and Run it and it should work :)

File size exceeds configured limit (2560000), code insight features not available

For the 64-bit 2020 version

I tried in vain to find the current location of this file for version 2020. When navigating to Help > Edit Custom Properties a new (empty) file is created at appData/Roaming/JetBrains/IntelliJIdea2020.1/idea.properties. There is no /bin directory as some tutorials suggest. However, neither adding the block from the accepted answer to this file nor adding the same file to /bin resulted in an update to my configuration.

I finally discovered that a reference to the same property exists in appData/Roaming/JetBrains/IntelliJIdea2020.1/idea64.exe.vmoptions. It looks like this:

-Didea.max.intellisense.filesize=3470

I changed it to this, which should be adequate for my needs:

-Didea.max.intellisense.filesize=9999

This strikes me as a bug in this version where the behavior of the menu item doesn't reflect what's needed, but it may also be the case that my particular setup is somehow different than stock. I do have PyCharm and the JDK installed.

What is the point of the diamond operator (<>) in Java 7?

All said in the other responses are valid but the use cases are not completely valid IMHO. If one checks out Guava and especially the collections related stuff, the same has been done with static methods. E.g. Lists.newArrayList() which allows you to write

List<String> names = Lists.newArrayList();

or with static import

import static com.google.common.collect.Lists.*;
...
List<String> names = newArrayList();
List<String> names = newArrayList("one", "two", "three");

Guava has other very powerful features like this and I actually can't think of much uses for the <>.

It would have been more useful if they went for making the diamond operator behavior the default, that is, the type is inferenced from the left side of the expression or if the type of the left side was inferenced from the right side. The latter is what happens in Scala.

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I had the same error. My issue was using the wrong parameter name when binding.

Notice :tokenHash in the query, but :token_hash when binding. Fixing one or the other resolves the error in this instance.

// Prepare DB connection
$sql = 'INSERT INTO rememberedlogins (token_hash,user_id,expires_at)
        VALUES (:tokenHash,:user_id,:expires_at)';
$db = static::getDB();
$stmt = $db->prepare($sql);

// Bind values
$stmt->bindValue(':token_hash',$hashed_token,PDO::PARAM_STR);

How to do a logical OR operation for integer comparison in shell scripting?

And in Bash

 line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
 vpid=`ps -ef|  grep wowzaDataSync | grep -v grep  | awk '{print $2}'`
 echo "-------->"${line1}
    if [ -z $line1 ] && [ ! -z $vpid ]
    then
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Process Is Working Fine"
    else
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Prcess Hanging Due To Exception With PID :"${pid}
   fi

OR in Bash

line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
vpid=`ps -ef|  grep wowzaDataSync | grep -v grep  | awk '{print $2}'`
echo "-------->"${line1}
   if [ -z $line1 ] || [ ! -z $vpid ]
    then
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Process Is Working Fine"
    else
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Prcess Hanging Due To Exception With PID :"${pid}
  fi

Iterating over a 2 dimensional python list

zip will transpose the list, after that you can concatenate the outputs.

In [3]: zip(*[ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ])
Out[3]: [('0,0', '1,0', '2,0'), ('0,1', '1,1', '2,1')]

Codeigniter - no input file specified

Godaddy hosting it seems fixed on .htaccess, myself it is working

RewriteRule ^(.*)$ index.php/$1 [L]

to

RewriteRule ^(.*)$ index.php?/$1 [QSA,L]

How to disable Compatibility View in IE

All you need is to force disable C.M. in IE - Just paste This code (in IE9 and under c.m. will be disabled):

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

Source: http://twigstechtips.blogspot.com/2010/03/css-ie8-meta-tag-to-disable.html