Programs & Examples On #Hook form alter

hook_form_alter() is the hook implemented by Drupal modules to alter the forms implemented by other modules.

Remove redundant paths from $PATH variable

There are no standard tools to "edit" the value of $PATH (i.e. "add folder only when it doesn't already exists" or "remove this folder").

To check what the path would be when you login next time, use telnet localhost (or telnet 127.0.0.1). It will then ask for your username and password.

This gives you a new login shell (i.e. a completely new one that doesn't inherit anything from the current environment).

You can check the value of the $PATH there and edit your rc files until it is correct. This is also useful to see whether you could login again at all after making a change to an important file.

How to force a SQL Server 2008 database to go Offline

Go offline

USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

Go online

USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO

Iterating through directories with Python

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

If you still get errors when running the above, please provide the error message.


Updated for Python3

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(os.path.join(subdir, file))

Compare a string using sh shell

eq is used to compare integers use equal '=' instead , example:

if [ 'AAA' = 'ABC' ];
then 
    echo "the same" 
else 
    echo "not the same"
fi

good luck

Prevent WebView from displaying "web page not available"

I suppose that if you insist on doing this, you could just check if the resource is there before calling the loadURL function. Just simply override the functions and do the check before calling the super()

REMARK (maybe off-topic): In http, there is a method called HEAD which is described as follow:

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response

This method might be handy. Anyway how ever you implement it ... check this code:

import java.util.Map;

import android.content.Context;
import android.webkit.WebView;

public class WebViewPreLoad extends WebView{

public WebViewPreLoad(Context context) {
super(context);
}
public void loadUrl(String str){
if(//Check if exists)
super.loadUrl(str);
else
//handle error
}
public void loadUrl(String url, Map<String,String> extraHeaders){
if(//Check if exists)
super.loadUrl(url, extraHeaders);
else
//handle error
}
}

You could try this check using

if(url.openConnection().getContentLength() > 0)

How Exactly Does @param Work - Java

It is basically a comment. As we know, a number of people working on the same project must have knowledge about the code changes. We are making some notes in the program about the parameters.

How can I get a precise time, for example in milliseconds in Objective-C?

#define CTTimeStart() NSDate * __date = [NSDate date]
#define CTTimeEnd(MSG) NSLog(MSG " %g",[__date timeIntervalSinceNow]*-1)

Usage:

CTTimeStart();
...
CTTimeEnd(@"that was a long time:");

Output:

2013-08-23 15:34:39.558 App-Dev[21229:907] that was a long time: .0023

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

I recently started receiving this error inside of my internal NLog failures log, with Visual Studio 2013. The solution has been using NLog v2.0.0 for several years. Within the last month, our main log stopped working. To fix this I updated NLog to the newest version (v3.1.0) via Nuget. The security exception is now gone and ALL of the log messages are appearing again.

Additionally, I later found another Security exception and was able to fix it by following the instructions on this post in another thread.

Create a unique number with javascript time

This creates an almost guaranteed unique 32 character key client side, if you want just numbers change the "chars" var.

var d = new Date().valueOf();
var n = d.toString();
var result = '';
var length = 32;
var p = 0;
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

for (var i = length; i > 0; --i){
    result += ((i & 1) && n.charAt(p) ? '<b>' + n.charAt(p) + '</b>' : chars[Math.floor(Math.random() * chars.length)]);
    if(i & 1) p++;
};

https://jsfiddle.net/j0evrdf1/1/

Currency format for display

You can use string.Format("{0:c}", value).

See also here:

How to directly initialize a HashMap (in a literal way)?

JAVA 8

In plain java 8 you also have the possibility of using Streams/Collectors to do the job.

Map<String, String> myMap = Stream.of(
         new SimpleEntry<>("key1", "value1"),
         new SimpleEntry<>("key2", "value2"),
         new SimpleEntry<>("key3", "value3"))
        .collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue));

This has the advantage of not creating an Anonymous class.

Note that the imports are:

import static java.util.stream.Collectors.toMap;
import java.util.AbstractMap.SimpleEntry;

Of course, as noted in other answers, in java 9 onwards you have simpler ways of doing the same.

PHP - Getting the index of a element from a array

function Index($index) {
    $Count = count($YOUR_ARRAY);
    if ($index <= $Count) {
        $Keys = array_keys($YOUR_ARRAY);
        $Value = array_values($YOUR_ARRAY);
        return $Keys[$index] . ' = ' . $Value[$index];
    } else {
        return "Out of the ring";
    }
}

echo 'Index : ' . Index(0);

Replace the ( $YOUR_ARRAY )

How do I make a Docker container start automatically on system boot?

To start a container and set it to restart automatically on system reboot use

docker run -d --restart unless-stopped ecstatic_ritchie

Where ecstatic_ritchie is an example name specifying the container in interest. Use docker ps -a to list all container names.

To make particular running containers start automatically on system reboot

docker update --restart unless-stopped ecstatic_ritchie

To make all running containers start automatically on system reboot

docker update --restart unless-stopped $(docker ps -q)

See more on Docker homepage

How to show only next line after the matched one?

perl one-liner alert

just for fun... print only one line after match

perl -lne '$next = ($.+1) if /match/; $. == $next && print' data.txt

even more fun... print the next ten lines after match

perl -lne 'push @nexts, (($.+1)..($.+10)) if /match/; $. ~~ @nexts && print' data.txt

kinda cheating though since there's actually two commands

Inline onclick JavaScript variable

Yes, JavaScript variables will exist in the scope they are created.

var bannerID = 55;

<input id="EditBanner" type="button" 
  value="Edit Image" onclick="EditBanner(bannerID);"/>


function EditBanner(id) {
   //Do something with id
}

If you use event handlers and jQuery it is simple also

$("#EditBanner").click(function() {
   EditBanner(bannerID);
});

What is __init__.py for?

The __init__.py file makes Python treat directories containing it as modules.

Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.

How to open a website when a Button is clicked in Android application?

You can wrap the buttons in anchors that href to the appropriate website.

<a href="http://www.stackoverflow.com">
  <input type="button" value="Button" />
</a>
<a href="http://www.stackoverflow.com">
  <input type="button" value="Button" />
</a>
<a href="http://www.stackoverflow.com">
  <input type="button" value="Button" />
</a>

When the user clicks the button (input) they are directed to the destination specified in the href property of the anchor.

Edit: Oops, I didn't read "Eclipse" in the question title. My mistake.

Put Excel-VBA code in module or sheet?

I would suggest separating your code based on the functionality and purpose specific to each sheet or module. In this manner, you would only put code relative to a sheet's UI inside the sheet's module and only put code related to modules in respective modules. Also, use separate modules to encapsulate code that is shared or reused among several different sheets.

For example, let's say you multiple sheets that are responsible for displaying data from a database in a special way. What kinds of functionality do we have in this situation? We have functionality related to each specific sheet, tasks related to getting data from the database, and tasks related to populating a sheet with data. In this case, I might start with a module for the data access, a module for populating a sheet with data, and within each sheet I'd have code for accessing code in those modules.

It might be laid out like this.

Module: DataAccess:

Function GetData(strTableName As String, strCondition1 As String) As Recordset
    'Code Related to getting data from the database'
End Function

Module: PopulateSheet:

Sub PopulateASheet(wsSheet As Worksheet, rs As Recordset)
    'Code to populate a worksheet '
End Function

Sheet: Sheet1 Code:

Sub GetDataAndPopulate()
    'Sample Code'
     Dim rs As New Recordset
     Dim ws As Worksheet
     Dim strParam As String
     Set ws = ActiveSheet
     strParam = ws.Range("A1").Value

     Set rs = GetData("Orders",strParam)

     PopulateASheet ws, rs
End Sub

Sub Button1_Click()
    Call GetDataAndPopulate
End Sub

How can I check a C# variable is an empty string "" or null?

if (string.IsNullOrEmpty(myString)) {
   //
}

extract month from date in python

Alternate solution

Create a column that will store the month:

data['month'] = data['date'].dt.month

Create a column that will store the year:

data['year'] = data['date'].dt.year

How to directly move camera to current location in Google Maps Android API v2?

make sure you have these permissions:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Then make some activity and register a LocationListener

package com.example.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

public class LocationActivity extends SherlockFragmentActivity implements LocationListener     {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map);
    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER        
}

@Override
public void onLocationChanged(Location location) {
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
    map.animateCamera(cameraUpdate);
    locationManager.removeUpdates(this);
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }

@Override
public void onProviderEnabled(String provider) { }

@Override
public void onProviderDisabled(String provider) { }
}

map.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>

rawQuery(query, selectionArgs)

For completeness and correct resource management:

        ICursor cursor = null;
        try
        {

            cursor = db.RawQuery("SELECT * FROM " + RECORDS_TABLE + " WHERE " + RECORD_ID + "=?", new String[] { id + "" });

            if (cursor.Count > 0)
            {
                cursor.MoveToFirst();
            }
            return GetRecordFromCursor(cursor); // Copy cursor props to custom obj
        }
        finally // IMPORTANT !!! Ensure cursor is not left hanging around ...
        {
            if(cursor != null)
                cursor.Close();
        }

C split a char array into different variables

This is how I do it.

void SplitBufferToArray(char *buffer, char * delim, char ** Output) {

    int partcount = 0;
    Output[partcount++] = buffer;

    char* ptr = buffer;
    while (ptr != 0) { //check if the string is over
        ptr = strstr(ptr, delim);
        if (ptr != NULL) {
            *ptr = 0;
            Output[partcount++] = ptr + strlen(delim);
            ptr = ptr + strlen(delim);
        }

    }
    Output[partcount++] = NULL;
}

Get Value of Row in Datatable c#

for (int i=0; i<dt_pattern.Rows.Count; i++)
{
    DataRow dr = dt_pattern.Rows[i];
}

In the loop, you can now reference row i+1 (assuming there is an i+1)

Populating a ComboBox using C#

but do you not just get your combo box name and then items.add("")?

For instance

Language.Items.Add("Italian");
Language.Items.Add("English");
Language.Items.Add("Spanish");

Hope this helped :D

Postgresql -bash: psql: command not found

If you are using the Postgres Mac app (by Heroku) and Bundler, you can add the pg_config directly inside the app, to your bundle.

bundle config build.pg --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config

...then run bundle again.

Note: check the version first using the following.

ls /Applications/Postgres.app/Contents/Versions/

How to reload the datatable(jquery) data?

To reload the table data from Ajax data source, use the following function:

dataTable.ajax.reload()

Where dataTable is the variable used to create the table.

var dataTable = $('#your_table_id').DataTable({
     ajax: "URL"
});

See ajax.reload() for more information.

Should I return EXIT_SUCCESS or 0 from main()?

What you return from a program is just a convention.

No, I can't think of any circumstances where "EXIT_SUCCESS" wouldn't be "0".

Personally, I'd recommend "0".

IMHO...

jQuery changing font family and font size

Full working solution :

HTML:

<form id="myform">
    <button>erase</button>
    <select id="fs"> 
        <option value="Arial">Arial</option>
        <option value="Verdana ">Verdana </option>
        <option value="Impact ">Impact </option>
        <option value="Comic Sans MS">Comic Sans MS</option>
    </select>

    <select id="size">
        <option value="7">7</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
    </select>
</form>

<br/>

<textarea class="changeMe">Text into textarea</textarea>
<div id="container" class="changeMe">
    <div id="float">
        <p>
            Text into container
        </p>
    </div>
</div>

jQuery:

$("#fs").change(function() {
    //alert($(this).val());
    $('.changeMe').css("font-family", $(this).val());

});

$("#size").change(function() {
    $('.changeMe').css("font-size", $(this).val() + "px");
});

Fiddle here: http://jsfiddle.net/AaT9b/

Getting all file names from a folder using C#

http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles.aspx

The System.IO namespace has loads of methods to help you with file operations. The

Directory.GetFiles() 

method returns an array of strings which represent the files in the target directory.

changing kafka retention period during runtime

log.retention.hours is a property of a broker which is used as a default value when a topic is created. When you change configurations of currently running topic using kafka-topics.sh, you should specify a topic-level property.

A topic-level property for log retention time is retention.ms.

From Topic-level configuration in Kafka 0.8.1 documentation:

  • Property: retention.ms
  • Default: 7 days
  • Server Default Property: log.retention.minutes
  • Description: This configuration controls the maximum time we will retain a log before we will discard old log segments to free up space if we are using the "delete" retention policy. This represents an SLA on how soon consumers must read their data.

So the correct command depends on the version. Up to 0.8.2 (although docs still show its use up to 0.10.1) use kafka-topics.sh --alter and after 0.10.2 (or perhaps from 0.9.0 going forward) use kafka-configs.sh --alter

$ bin/kafka-topics.sh --zookeeper zk.yoursite.com --alter --topic as-access --config retention.ms=86400000
 

You can check whether the configuration is properly applied with the following command.

$ bin/kafka-topics.sh --describe --zookeeper zk.yoursite.com --topic as-access

Then you will see something like below.

Topic:as-access  PartitionCount:3  ReplicationFactor:3  Configs:retention.ms=86400000

On npm install: Unhandled rejection Error: EACCES: permission denied

This one works for me:

sudo chown -R $(whoami) ~/.npm

I did not use the -g because I am the only user. I used a MacBook Air.

Checking Value of Radio Button Group via JavaScript?

If you wrap your form elements in a form tag with a name attribute you can easily get the value using document.formName.radioGroupName.value.

<form name="myForm">
    <input type="radio" id="genderm" name="gender" value="male" />
    <label for="genderm">Male</label>
    <input type="radio" id="genderf" name="gender" value="female" />
    <label for="genderf">Female</label>
</form>

<script>
    var selected = document.forms.myForm.gender.value;
</script>

In Objective-C, how do I test the object type?

Simple, [yourobject class] it will return the class name of yourobject.

Android 8: Cleartext HTTP traffic not permitted

Put following into your resources/android/xml/network_security_config.xml :

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

This solves Failed to load resource: net::ERR_CLEARTEXT_NOT_PERMITTED problem on Android for Cordova / Ionic.

How do I remove javascript validation from my eclipse project?

In addition, if you are using Tern eclipse IDE or IBM Node.js Tools for Eclipse, you may need to disable JSHint and other libraries that you don't want.

To disable this, Project Properties > Tern > Modules > JSHint or any other library that you don't want. enter image description here

How to force garbage collector to run?

System.GC.Collect() forces garbage collector to run. This is not recommended but can be used if situations arise.

Confirmation before closing of tab/browser

Simply

function goodbye(e) {
        if(!e) e = window.event;
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

        //e.stopPropagation works in Firefox.
        if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
        }
    }
window.onbeforeunload=goodbye;

Regex to match string containing two names in any order

You can do:

\bjack\b.*\bjames\b|\bjames\b.*\bjack\b

What does this thread join code mean?

let's say our main thread starts the threads t1 and t2. Now, when t1.join() is called, the main thread suspends itself till thread t1 dies and then resumes itself. Similarly, when t2.join() executes, the main thread suspends itself again till the thread t2 dies and then resumes.

So, this is how it works.

Also, the while loop was not really needed here.

How to uncheck checkbox using jQuery Uniform library

Just do this:

$('#checkbox').prop('checked',true).uniform('refresh');

Why must wait() always be in synchronized block

A wait() only makes sense when there is also a notify(), so it's always about communication between threads, and that needs synchronization to work correctly. One could argue that this should be implicit, but that would not really help, for the following reason:

Semantically, you never just wait(). You need some condition to be satsified, and if it is not, you wait until it is. So what you really do is

if(!condition){
    wait();
}

But the condition is being set by a separate thread, so in order to have this work correctly you need synchronization.

A couple more things wrong with it, where just because your thread quit waiting doesn't mean the condition you are looking for is true:

  • You can get spurious wakeups (meaning that a thread can wake up from waiting without ever having received a notification), or

  • The condition can get set, but a third thread makes the condition false again by the time the waiting thread wakes up (and reacquires the monitor).

To deal with these cases what you really need is always some variation of this:

synchronized(lock){
    while(!condition){
        lock.wait();
    }
}

Better yet, don't mess with the synchronization primitives at all and work with the abstractions offered in the java.util.concurrent packages.

How to set caret(cursor) position in contenteditable element (div)?

_x000D_
_x000D_
function set_mouse() {_x000D_
  var as = document.getElementById("editable");_x000D_
  el = as.childNodes[1].childNodes[0]; //goal is to get ('we') id to write (object Text) because it work only in object text_x000D_
  var range = document.createRange();_x000D_
  var sel = window.getSelection();_x000D_
  range.setStart(el, 1);_x000D_
  range.collapse(true);_x000D_
  sel.removeAllRanges();_x000D_
  sel.addRange(range);_x000D_
_x000D_
  document.getElementById("we").innerHTML = el; // see out put of we id_x000D_
}
_x000D_
<div id="editable" contenteditable="true">dddddddddddddddddddddddddddd_x000D_
  <p>dd</p>psss_x000D_
  <p>dd</p>_x000D_
  <p>dd</p>_x000D_
  <p>text text text</p>_x000D_
</div>_x000D_
<p id='we'></p>_x000D_
<button onclick="set_mouse()">focus</button>
_x000D_
_x000D_
_x000D_

It is very hard set caret in proper position when you have advance element like (p) (span) etc. The goal is to get (object text):

<div id="editable" contenteditable="true">dddddddddddddddddddddddddddd<p>dd</p>psss<p>dd</p>
    <p>dd</p>
    <p>text text text</p>
</div>
<p id='we'></p>
<button onclick="set_mouse()">focus</button>
<script>

    function set_mouse() {
        var as = document.getElementById("editable");
        el = as.childNodes[1].childNodes[0];//goal is to get ('we') id to write (object Text) because it work only in object text
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(el, 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);

        document.getElementById("we").innerHTML = el;// see out put of we id
    }
</script>

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Try using ReadAsStringAsync() instead.

 var foo = resp.Content.ReadAsStringAsync().Result;

The reason why it ReadAsAsync<string>() doesn't work is because ReadAsAsync<> will try to use one of the default MediaTypeFormatter (i.e. JsonMediaTypeFormatter, XmlMediaTypeFormatter, ...) to read the content with content-type of text/plain. However, none of the default formatter can read the text/plain (they can only read application/json, application/xml, etc).

By using ReadAsStringAsync(), the content will be read as string regardless of the content-type.

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

How do I extract text that lies between parentheses (round brackets)?

A very simple way to do it is by using regular expressions:

Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value

As a response to the (very funny) comment, here's the same Regex with some explanation:

\(             # Escaped parenthesis, means "starts with a '(' character"
    (          # Parentheses in a regex mean "put (capture) the stuff 
               #     in between into the Groups array" 
       [^)]    # Any character that is not a ')' character
       *       # Zero or more occurrences of the aforementioned "non ')' char"
    )          # Close the capturing group
\)             # "Ends with a ')' character"

Unzip files (7-zip) via cmd command

Regarding Phil Street's post:

It may actually be installed in your 32-bit program folder instead of your default x64, if you're running 64-bit OS. Check to see where 7-zip is installed, and if it is in Program Files (x86) then try using this instead:

PATH=%PATH%;C:\Program Files (x86)\7-Zip

where is gacutil.exe?

gacutil comes with Visual Studio, not with VSTS. It is part of Windows SDK and can be download separately at http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en . This installation will have gacutil.exe included. But first check it here

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

you might have it installed.

As @devi mentioned

If you decide to grab gacutil files from existing installation, note that from .NET 4.0 is three files: gacutil.exe gacutil.exe.config and 1033/gacutlrc.dll

How to replace captured groups only?

Now that Javascript has lookbehind (as of ES2018), on newer environments, you can avoid groups entirely in situations like these. Rather, lookbehind for what comes before the group you were capturing, and lookahead for what comes after, and replace with just !NEW_ID!:

_x000D_
_x000D_
const str = 'name="some_text_0_some_text"';
console.log(
  str.replace(/(?<=name="\w+)\d+(?=\w+")/, '!NEW_ID!')
);
_x000D_
_x000D_
_x000D_

With this method, the full match is only the part that needs to be replaced.

  • (?<=name="\w+) - Lookbehind for name=", followed by word characters (luckily, lookbehinds do not have to be fixed width in Javascript!)
  • \d+ - Match one or more digits - the only part of the pattern not in a lookaround, the only part of the string that will be in the resulting match
  • (?=\w+") - Lookahead for word characters followed by " `

Keep in mind that lookbehind is pretty new. It works in modern versions of V8 (including Chrome, Opera, and Node), but not in most other environments, at least not yet. So while you can reliably use lookbehind in Node and in your own browser (if it runs on a modern version of V8), it's not yet sufficiently supported by random clients (like on a public website).

How to have the formatter wrap code with IntelliJ?

You can create a macro for Ctrl +Shift + S (for example) that do all this things:

Edit > Macros > Start Macro Recording (the recording will start). Click where you need.

For example:

Code > Reformat Code
Code > Auto-Indent Lines
Code > Optimize Imports
Code > Rearrange Code
File > Save All
... (all that you want)

Then, click on red button in bottom-right of the IDE to stop the Macro recording.

Set a macro name.

Go to File > Settings > Macros > YOUR MACRO NAME.

Right Click > Add Keyboard Shortcut, and type Ctrl + Shift + S.

IOCTL Linux device driver

An ioctl, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.

An alternative is the sysfs interface, where you set up a file under /sys/ and read/write that to get information from and to the driver. An example of how to set this up:

static ssize_t mydrvr_version_show(struct device *dev,
        struct device_attribute *attr, char *buf)
{
    return sprintf(buf, "%s\n", DRIVER_RELEASE);
}

static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);

And during driver setup:

device_create_file(dev, &dev_attr_version);

You would then have a file for your device in /sys/, for example, /sys/block/myblk/version for a block driver.

Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl or libnl3 libraries.

Appending HTML string to the DOM

Why is that not acceptable?

document.getElementById('test').innerHTML += str

would be the textbook way of doing it.

What is the proper way to check and uncheck a checkbox in HTML5?

You can refer to this page at w3schools but basically you could use any of:

<input checked>
<input checked="checked">
<input checked="">

Can anyone explain python's relative imports?

Checking it out in python3:

python -V
Python 3.6.5

Example1:

.
+-- parent.py
+-- start.py
+-- sub
    +-- relative.py

- start.py
import sub.relative

- parent.py
print('Hello from parent.py')

- sub/relative.py
from .. import parent

If we run it like this(just to make sure PYTHONPATH is empty):

PYTHONPATH='' python3 start.py

Output:

Traceback (most recent call last):
  File "start.py", line 1, in <module>
    import sub.relative
  File "/python-import-examples/so-example-v1/sub/relative.py", line 1, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/relative.py

- sub/relative.py
import parent

If we run it like this:

PYTHONPATH='' python3 start.py

Output:

Hello from parent.py

Example2:

.
+-- parent.py
+-- sub
    +-- relative.py
    +-- start.py

- parent.py
print('Hello from parent.py')

- sub/relative.py
print('Hello from relative.py')

- sub/start.py
import relative
from .. import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 2, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/start.py:

- sub/start.py
import relative
import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 3, in <module>
    import parent
ModuleNotFoundError: No module named 'parent'

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

Also it's better to use import from root folder, i.e.:

- sub/start.py
import sub.relative
import parent

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

How to get the day name from a selected date?

What about if we use String.Format here

_x000D_
_x000D_
DateTime today = DateTime.Today;_x000D_
String.Format("{0:dd-MM}, {1:dddd}", today, today) //In dd-MM format_x000D_
String.Format("{0:MM-dd}, {1:dddd}", today, today) //In MM-dd format
_x000D_
_x000D_
_x000D_

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

Here is what i observed when I used my own image sets in .jpg format. In the sample script available in Opencv doc, note that it has the undistort and crop the image lines as below:

# undistort
dst = cv2.undistort(img, mtx, dist, None, newcameramtx)

# crop the image
x,y,w,h = roi
dst = dst[y:y+h, x:x+w]
cv2.imwrite('calibresult.jpg',dst)

So, when we run the code for the first time, it executes the line cv2.imwrite('calibresult.jpg',dst) saving a image calibresult.jpg in the current directory. So, when I ran the code for the next time, along with my sample image sets that I used for calibrating the camera in jpg format, the code also tried to consider this newly added image calibresult.jpg due to which the error popped out

error: C:\builds\master_PackSlaveAddon-win64-vc12-static\opencv\modules\imgproc\src\color.cpp:7456: error: (-215) scn == 3 || scn == 4 in function cv::ipp_cvtColor

What I did was: I simply deleted that newly generated image after each run or alternatively changed the type of the image to say png or tiff type. That solved the problem. Check if you are inputting and writing calibresult of the same type. If so, just change the type.

Get element by id - Angular2

(<HTMLInputElement>document.getElementById('loginInput')).value = '123';

Angular cannot take HTML elements directly thereby you need to specify the element type by binding the above generic to it.

UPDATE::

This can also be done using ViewChild with #localvariable as shown here, as mentioned in here

<textarea  #someVar  id="tasknote"
                  name="tasknote"
                  [(ngModel)]="taskNote"
                  placeholder="{{ notePlaceholder }}"
                  style="background-color: pink"
                  (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} 

</textarea>

import {ElementRef,Renderer2} from '@angular/core';
@ViewChild('someVar') el:ElementRef;

constructor(private rd: Renderer2) {}

ngAfterViewInit() {
      console.log(this.rd); 
      this.el.nativeElement.focus();      //<<<=====same as oldest way
}

Gradle project refresh failed after Android Studio update

I tried everything, nothing worked.then I tried the following steps and it worked

  1. close Android studio

  2. go to "My Documents"

  3. delete the following folders a).android, b).androidstudio1.5, c).gradle

  4. start Android studio and enjoy...

It seems stupid but works...

How to change language of app when user selects language?

Those who getting the version issue try this code ..

public static void switchLocal(Context context, String lcode, Activity activity) {
        if (lcode.equalsIgnoreCase(""))
            return;
        Resources resources = context.getResources();
        Locale locale = new Locale(lcode);
        Locale.setDefault(locale);
        android.content.res.Configuration config = new 
        android.content.res.Configuration();
        config.locale = locale;
        resources.updateConfiguration(config, resources.getDisplayMetrics());
        //restart base activity 
        activity.finish();
        activity.startActivity(activity.getIntent());
    }

Android Linear Layout - How to Keep Element At Bottom Of View?

DO LIKE THIS

 <LinearLayout
android:id="@+id/LinearLayouts02"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom|end">

<TextView
    android:id="@+id/texts1"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:layout_weight="2"
    android:text="@string/forgotpass"
    android:padding="7dp"
    android:gravity="bottom|center_horizontal"
    android:paddingLeft="10dp"
    android:layout_marginBottom="30dp"
    android:bottomLeftRadius="10dp"
    android:bottomRightRadius="50dp"
    android:fontFamily="sans-serif-condensed"
    android:textColor="@color/colorAccent"
    android:textStyle="bold"
    android:textSize="16sp"
    android:topLeftRadius="10dp"
    android:topRightRadius="10dp"
   />

</LinearLayout>

Macro to Auto Fill Down to last adjacent cell

This example shows you how to fill column B based on the the volume of data in Column A. Adjust "A1" accordingly to your needs. It will fill in column B based on the formula in B1.

Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

How can I validate google reCAPTCHA v2 using javascript/jQuery?

Source Link

enter image description here

You can simply check on client side using grecaptcha.getResponse() method

          var rcres = grecaptcha.getResponse();
          if(rcres.length){
            grecaptcha.reset();
            showHideMsg("Form Submitted!","success");
          }else{
            showHideMsg("Please verify reCAPTCHA","error");
          }

Understanding "VOLUME" instruction in DockerFile

The official docker tutorial says:

A data volume is a specially-designated directory within one or more containers that bypasses the Union File System. Data volumes provide several useful features for persistent or shared data:

  • Volumes are initialized when a container is created. If the container’s base image contains data at the specified mount point,
    that existing data is copied into the new volume upon volume
    initialization. (Note that this does not apply when mounting a host
    directory.)

  • Data volumes can be shared and reused among containers.

  • Changes to a data volume are made directly.

  • Changes to a data volume will not be included when you update an image.

  • Data volumes persist even if the container itself is deleted.

In Dockerfile you can specify only the destination of a volume inside a container. e.g. /usr/src/app.

When you run a container, e.g. docker run --volume=/opt:/usr/src/app my_image, you may but do not have to specify its mounting point (/opt) on the host machine. If you do not specify --volume argument then the mount point will be chosen automatically, usually under /var/lib/docker/volumes/.

Must declare the scalar variable

If someone else comes across this question while no solution here made my sql file working, here's what my mistake was:

I have been exporting the contents of my database via the 'Generate Script' command of Microsofts' Server Management Studio and then doing some operations afterwards while inserting the generated data in another instance.

Due to the generated export, there have been a bunch of "GO" statements in the sql file.

What I didn't know was that variables declared at the top of a file aren't accessible as far as a GO statement is executed. Therefore I had to remove the GO statements in my sql file and the error "Must declare the scalar variable xy" was gone!

How to calculate the inverse of the normal cumulative distribution function in python?

# given random variable X (house price) with population muy = 60, sigma = 40
import scipy as sc
import scipy.stats as sct
sc.version.full_version # 0.15.1

#a. Find P(X<50)
sct.norm.cdf(x=50,loc=60,scale=40) # 0.4012936743170763

#b. Find P(X>=50)
sct.norm.sf(x=50,loc=60,scale=40) # 0.5987063256829237

#c. Find P(60<=X<=80)
sct.norm.cdf(x=80,loc=60,scale=40) - sct.norm.cdf(x=60,loc=60,scale=40)

#d. how much top most 5% expensive house cost at least? or find x where P(X>=x) = 0.05
sct.norm.isf(q=0.05,loc=60,scale=40)

#e. how much top most 5% cheapest house cost at least? or find x where P(X<=x) = 0.05
sct.norm.ppf(q=0.05,loc=60,scale=40)

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Fixed it with -no-pie option in linker stage:

g++-8 -L"/home/pedro/workspace/project/lib" -no-pie ...

How to convert empty spaces into null values, using SQL Server?

SQL Server ignores trailing whitespace when comparing strings, so ' ' = ''. Just use the following query for your update

UPDATE table
SET col1 = NULL
WHERE col1 = ''

NULL values in your table will stay NULL, and col1s with any number on space only characters will be changed to NULL.

If you want to do it during your copy from one table to another, use this:

INSERT INTO newtable ( col1, othercolumn )
SELECT
   NULLIF(col1, ''),
   othercolumn
FROM table

"On Exit" for a Console Application

This code works to catch the user closing the console window:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        handler = new ConsoleEventDelegate(ConsoleEventCallback);
        SetConsoleCtrlHandler(handler, true);
        Console.ReadLine();
    }

    static bool ConsoleEventCallback(int eventType) {
        if (eventType == 2) {
            Console.WriteLine("Console window closing, death imminent");
        }
        return false;
    }
    static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
    // Pinvoke
    private delegate bool ConsoleEventDelegate(int eventType);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

}

Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Android: Go back to previous activity

Besides all the mentioned answers, their is still an alternative way of doing this, lets say you have two classes , class A and class B.

Class A you have made some activities like checkbox select, printed out some data and intent to class B. Class B, you would like to pass multiple values to class A and maintain the previous state of class A, you can use, try this alternative method or download source code to demonstrate this

http://whats-online.info/science-and-tutorials/125/Android-maintain-the-previous-state-of-activity-on-intent/

or

http://developer.android.com/reference/android/content/Intent.html

How to create friendly URL in php?

There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.

One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].

You can easily extract the /path/to/your/page/here bit with the following bit of code:

$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));

From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)

JS jQuery - check if value is in array

You are comparing a jQuery object (jQuery('input:first')) to strings (the elements of the array).
Change the code in order to compare the input's value (wich is a string) to the array elements:

if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)

The inArray method returns -1 if the element wasn't found in the array, so as your bonus answer to how to determine if an element is not in an array, use this :

if(jQuery.inArray(el,arr) == -1){
    // the element is not in the array
};

jQuery make global variable

Your code looks fine except the possibility that if the variable declaration is inside a dom read handler then it will not be a global variable... it will be a closure variable

jQuery(function(){
    //here it is a closure variable
    var a_href;
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }
})

To make the variable global, one solution is to declare the variable in global scope

var a_href;
jQuery(function(){
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }
})

another is to set the variable as a property of the window object

window.a_href = $(this).attr('href')

Why console printing undefined

You are getting the output as undefined because even though the variable is declared, you have not initialized it with a value, the value of the variable is set only after the a element is clicked till that time the variable will have the value undefined. If you are not declaring the variable it will throw a ReferenceError

Synchronizing a local Git repository with a remote one

If you are talking about syncing a forked repo then you can follow these steps.

How to sync a fork repository from git

  1. check your current git branch

    git branch

  2. checkout to master if you are not on master

    git checkout master

  3. Fetch the upstream repository if you have correct access rights

    git fetch upstream

  4. If you are getting below error then run

    git remote add upstream [email protected]:upstream_clone_repo_url/xyz.git

    fatal: 'upstream/master' does not appear to be a git repository  
    fatal: Could not read from remote repository.
    Please make sure you have the correct access rights and the repository exists.
    
  5. Now run the below command.

    git fetch upstream

  6. Now if you are on master then merge the upstream/master into master branch

    git merge upstream/master

    That's it!!

    Crosscheck via git remote command, more specific git remote -v

    If I also have commit rights to the upstream repo, I can create a local upstream branch and do work that will go upstream there.

Google Map API v3 ~ Simply Close an infowindow?

infowindow.open(null,null);

will close opened infowindow. It will work same as

Key error when selecting columns in pandas dataframe after read_csv

The key error generally comes if the key doesn't match any of the dataframe column name 'exactly':

You could also try:

import csv
import pandas as pd
import re
    with open (filename, "r") as file:
        df = pd.read_csv(file, delimiter = ",")
        df.columns = ((df.columns.str).replace("^ ","")).str.replace(" $","")
        print(df.columns)

Soft Edges using CSS?

You can use CSS gradient - although there are not consistent across browsers so You would have to code it for every one

Like that: CSS3 Transparency + Gradient

Gradient should be more transparent on top or on top right corner (depending on capabilities)

String to Binary in C#

Here you go:

public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
    return encoding.GetBytes(str);
}

public static String ToBinary(Byte[] data)
{
    return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}

// Use any sort of encoding you like. 
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));

Finding an element in an array in Java

There is a contains method for lists, so you should be able to do:

Arrays.asList(yourArray).contains(yourObject);

Warning: this might not do what you (or I) expect, see Tom's comment below.

How can I open two pages from a single click without using JavaScript?

Without JavaScript, it's not possible to open two pages by clicking one link unless both pages are framed on the one page that opens from clicking the link. With JS it's trivial:

<p><a href="#" onclick="window.open('http://google.com');
    window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>

Do note that this will be blocked by popup blockers built into web browsers but you are usually notified of this.

Git merge errors

git commit -m "Merged master fixed conflict."

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

In Solution Explorer, please select files you want to copied to output directory and assign two properties: - Build action = Content - Copy to Output Directory = Copy Always

This will do the trick.

How can I use a for each loop on an array?

Element needs to be a variant, so you can't declare it as a string. Your function should accept a variant if it is a string though as long as you pass it ByVal.

Public Sub example()
    Dim sArray(4) As string
    Dim element As variant

    For Each element In sArray
        do_something (element)
    Next element
End Sub


Sub do_something(ByVal e As String)

End Sub

The other option is to convert the variant to a string before passing it.

  do_something CStr(element)

How to add a border just on the top side of a UIView

In case someone will ever need Xamarin version:

public static class UIUtils
{
    public static void AddBorder(this CALayer cALayer, UIRectEdge edge, UIColor color, float thickness)
    {

        var border = new CALayer();
        switch (edge) 
        {
            case UIRectEdge.Top:
                border.Frame = new CGRect(0, 0, cALayer.Frame.Width, height: thickness);
                break;
            case UIRectEdge.Bottom:
                border.Frame = new CGRect(0, cALayer.Frame.Height - thickness, width: cALayer.Frame.Width, height: thickness);
                break;
            case UIRectEdge.Left:
                border.Frame = new CGRect(0, 0, width: thickness, height: cALayer.Frame.Height);
                break;
            case UIRectEdge.Right:
                border.Frame = new CGRect(cALayer.Frame.Width - thickness, y: 0, width: thickness, height: cALayer.Frame.Height);
                break;
            default: break;
        }
        border.BackgroundColor = color.CGColor;
        cALayer.AddSublayer(border);
    }
}

Call a Class From another class

Simply create an instance of Class2 and call the desired method.

Suggested reading: http://docs.oracle.com/javase/tutorial/java/javaOO/

Javascript find json value

Making more general the @showdev answer.

var getObjectByValue = function (array, key, value) {
    return array.filter(function (object) {
        return object[key] === value;
    });
};

Example:

getObjectByValue(data, "code", "DZ" );

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

A lot of the answers given so far are pretty good, but you must clearly define what it is exactly that you want.

If you would like a alphabetical character followed by any number of non-white-space characters (note that it would also include numbers!) then you should use this:

^[A-Za-z]\S*$

If you would like to include only alpha-numeric characters and certain symbols, then use this:

^[A-Za-z][A-Za-z0-9!@#$%^&*]*$

Your original question looks like you are trying to include the space character as well, so you probably want something like this:

^[A-Za-z ][A-Za-z0-9!@#$%^&* ]*$

And that is my final answer!

I suggest taking some time to learn more about regular expressions. They are the greatest thing since sliced bread!

Try this syntax reference page (that site in general is very good).

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

With VSTS the url is, When you copy git clone url from vsts you always get

https://orgname@dev.azure.com/org/project/_git/repo

Replace orgname@ with your alternate username that you would have created in VSTS -> profile -> Security.

final git url -

https://alternateusername@dev.azure.com/org/project/_git/repo

Tomcat in Intellij Idea Community Edition

If you are using maven, you can use this command mvn tomcat:run, but first you add in your pom.xml this structure into build tag, just like this:

<build>
    <finalName>mvn-webapp-test</finalName>
      <plugins>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>${maven.compiler.plugin.version}</version>
              <configuration>
                  <source>1.6</source>
                  <target>1.6</target>
              </configuration>
          </plugin>
      </plugins>
  </build>

how to assign a block of html code to a javascript variable

we can use backticks (``) without any error.. eg: <div>"test"<div>

we can store large template(HTML) inside the backticks which was introduced in ES6 javascript standard

No need to escape any special characters

if no backticks.. we need to escape characters by appending backslash() eg:" \"test\""

Change NULL values in Datetime format to empty string

CASE and CAST should work:

CASE WHEN mycol IS NULL THEN '' ELSE CONVERT(varchar(50), mycol, 121) END

Response.Redirect to new window

Contruct your url via click event handler:

string strUrl = "/some/url/path" + myvar;

Then:

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + strUrl + "','_blank')", true);

Windows Task Scheduler doesn't start batch file task

I had the same problem and none of the solutions worked. When I checked the history I figured out the issue. I had this warning

Task Scheduler did not launch task "\TASK_NAME"  because instance "{34a206d4-7fce-3895-bfcd-2456f6ed6533}"  of the same task is already running.

In the settings tab there is a drop down option for "If the task is already running, then the following rule applies:" and the default is "Do not start a new instance". Change that to "Run a new instance in parallel" or "Stop the existing instance" based on what you actually need to be done.

I know it's an old thread and multiple solutions are good here, this is just what worked for me. Hope it helps.

How can you test if an object has a specific property?

Try this for a one liner that is strict safe.

[bool]$myobject.PSObject.Properties[$propertyName]

For example:

Set-StrictMode -Version latest;
$propertyName = 'Property1';
$myobject = [PSCustomObject]@{ Property0 = 'Value0' };

if ([bool]$myobject.PSObject.Properties[$propertyName]) {
    $value = $myobject.$propertyName;
}

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

I find that the "solution" of just increasing the timeouts obscures what's really going on here, which is either

  1. Your code and/or network calls are way too slow (should be sub 100 ms for a good user experience)
  2. The assertions (tests) are failing and something is swallowing the errors before Mocha is able to act on them.

You usually encounter #2 when Mocha doesn't receive assertion errors from a callback. This is caused by some other code swallowing the exception further up the stack. The right way of dealing with this is to fix the code and not swallow the error.

When external code swallows your errors

In case it's a library function that you are unable to modify, you need to catch the assertion error and pass it onto Mocha yourself. You do this by wrapping your assertion callback in a try/catch block and pass any exceptions to the done handler.

it('should not fail', function (done) { // Pass reference here!

  i_swallow_errors(function (err, result) {
    try { // boilerplate to be able to get the assert failures
      assert.ok(true);
      assert.equal(result, 'bar');
      done();
    } catch (error) {
      done(error);
    }
  });
});

This boilerplate can of course be extracted into some utility function to make the test a little more pleasing to the eye:

it('should not fail', function (done) { // Pass reference here!
    i_swallow_errors(handleError(done, function (err, result) {
        assert.equal(result, 'bar');
    }));
});

// reusable boilerplate to be able to get the assert failures
function handleError(done, fn) {
    try { 
        fn();
        done();
    } catch (error) {
        done(error);
    }
}

Speeding up network tests

Other than that I suggest you pick up the advice on starting to use test stubs for network calls to make tests pass without having to rely on a functioning network. Using Mocha, Chai and Sinon the tests might look something like this

describe('api tests normally involving network calls', function() {

    beforeEach: function () {
        this.xhr = sinon.useFakeXMLHttpRequest();
        var requests = this.requests = [];

        this.xhr.onCreate = function (xhr) {
            requests.push(xhr);
        };
    },

    afterEach: function () {
        this.xhr.restore();
    }


    it("should fetch comments from server", function () {
        var callback = sinon.spy();
        myLib.getCommentsFor("/some/article", callback);
        assertEquals(1, this.requests.length);

        this.requests[0].respond(200, { "Content-Type": "application/json" },
                                 '[{ "id": 12, "comment": "Hey there" }]');
        expect(callback.calledWith([{ id: 12, comment: "Hey there" }])).to.be.true;
    });

});

See Sinon's nise docs for more info.

How to get request url in a jQuery $.get/ajax request

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

So you would use

$.ajax('http://www.example.org', {
  dataType: 'xml',
  data: {'a':1,'b':2,'c':3},
  context: {
    url: 'http://www.example.org'
  }
}).done(function(xml) {alert(this.url});

get specific row from spark dataframe

This Works for me in PySpark

df.select("column").collect()[0][0]

Setting the filter to an OpenFileDialog to allow the typical image formats?

This is extreme, but I built a dynamic, database-driven filter using a 2 column database table named FILE_TYPES, with field names EXTENSION and DOCTYPE:

---------------------------------
| EXTENSION  |  DOCTYPE         |
---------------------------------
|   .doc     |  Document        |
|   .docx    |  Document        |
|   .pdf     |  Document        |
|   ...      |  ...             |
|   .bmp     |  Image           |
|   .jpg     |  Image           |
|   ...      |  ...             |
---------------------------------

Obviously I had many different types and extensions, but I'm simplifying it for this example. Here is my function:

    private static string GetUploadFilter()
    {
        // Desired format:
        // "Document files (*.doc, *.docx, *.pdf)|*.doc;*.docx;*.pdf|"
        // "Image files (*.bmp, *.jpg)|*.bmp;*.jpg|"

        string filter = String.Empty;
        string nameFilter = String.Empty;
        string extFilter = String.Empty;

        // Used to get extensions
        DataTable dt = new DataTable();
        dt = DataLayer.Get_DataTable("SELECT * FROM FILE_TYPES ORDER BY EXTENSION");

        // Used to cycle through doctype groupings ("Images", "Documents", etc.)
        DataTable dtDocTypes = new DataTable();
        dtDocTypes = DataLayer.Get_DataTable("SELECT DISTINCT DOCTYPE FROM FILE_TYPES ORDER BY DOCTYPE");

        // For each doctype grouping...
        foreach (DataRow drDocType in dtDocTypes.Rows)
        {
            nameFilter = drDocType["DOCTYPE"].ToString() + " files (";

            // ... add its associated extensions
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["DOCTYPE"].ToString() == drDocType["DOCTYPE"].ToString())
                {
                    nameFilter += "*" + dr["EXTENSION"].ToString() + ", ";
                    extFilter += "*" + dr["EXTENSION"].ToString() + ";";
                }                    
            }

            // Remove endings put in place in case there was another to add, and end them with pipe characters:
            nameFilter = nameFilter.TrimEnd(' ').TrimEnd(',');
            nameFilter += ")|";
            extFilter = extFilter.TrimEnd(';');
            extFilter += "|";

            // Add the name and its extensions to our main filter
            filter += nameFilter + extFilter;

            extFilter = ""; // clear it for next round; nameFilter will be reset to the next DOCTYPE on next pass
        }

        filter = filter.TrimEnd('|');
        return filter;
    }

    private void UploadFile(string fileType, object sender)
    {            
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        string filter = GetUploadFilter();
        dlg.Filter = filter;

        if (dlg.ShowDialog().Value == true)
        {
            string fileName = dlg.FileName;

            System.IO.FileStream fs = System.IO.File.OpenRead(fileName);
            byte[] array = new byte[fs.Length];

            // This will give you just the filename
            fileName = fileName.Split('\\')[fileName.Split('\\').Length - 1];
            ...

Should yield a filter that looks like this:

enter image description here

Make flex items take content width, not width of parent container

In addtion to align-self you can also consider auto margin which will do almost the same thing

_x000D_
_x000D_
.container {_x000D_
  background: red;_x000D_
  height: 200px;_x000D_
  flex-direction: column;_x000D_
  padding: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
a {_x000D_
  margin-right:auto;_x000D_
  padding: 10px 40px;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
  <a href="#">Test</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python vs Cpython

Even I had the same problem understanding how are CPython, JPython, IronPython, PyPy are different from each other.

So, I am willing to clear three things before I begin to explain:

  1. Python: It is a language, it only states/describes how to convey/express yourself to the interpreter (the program which accepts your python code).
  2. Implementation: It is all about how the interpreter was written, specifically, in what language and what it ends up doing.
  3. Bytecode: It is the code that is processed by a program, usually referred to as a virtual machine, rather than by the "real" computer machine, the hardware processor.

CPython is the implementation, which was written in C language. It ends up producing bytecode (stack-machine based instruction set) which is Python specific and then executes it. The reason to convert Python code to a bytecode is because it's easier to implement an interpreter if it looks like machine instructions. But, it isn't necessary to produce some bytecode prior to execution of the Python code (but CPython does produce).

If you want to look at CPython's bytecode then you can. Here's how you can:

>>> def f(x, y):                # line 1
...    print("Hello")           # line 2
...    if x:                    # line 3
...       y += x                # line 4
...    print(x, y)              # line 5
...    return x+y               # line 6
...                             # line 7
>>> import dis                  # line 8
>>> dis.dis(f)                  # line 9
  2           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('Hello')
              4 CALL_FUNCTION            1
              6 POP_TOP

  3           8 LOAD_FAST                0 (x)
             10 POP_JUMP_IF_FALSE       20

  4          12 LOAD_FAST                1 (y)
             14 LOAD_FAST                0 (x)
             16 INPLACE_ADD
             18 STORE_FAST               1 (y)

  5     >>   20 LOAD_GLOBAL              0 (print)
             22 LOAD_FAST                0 (x)
             24 LOAD_FAST                1 (y)
             26 CALL_FUNCTION            2
             28 POP_TOP

  6          30 LOAD_FAST                0 (x)
             32 LOAD_FAST                1 (y)
             34 BINARY_ADD
36 RETURN_VALUE

Now, let's have a look at the above code. Lines 1 to 6 are a function definition. In line 8, we import the 'dis' module which can be used to view the intermediate Python bytecode (or you can say, disassembler for Python bytecode) that is generated by CPython (interpreter).

NOTE: I got the link to this code from #python IRC channel: https://gist.github.com/nedbat/e89fa710db0edfb9057dc8d18d979f9c

And then, there is Jython, which is written in Java and ends up producing Java byte code. The Java byte code runs on Java Runtime Environment, which is an implementation of Java Virtual Machine (JVM). If this is confusing then I suspect that you have no clue how Java works. In layman terms, Java (the language, not the compiler) code is taken by the Java compiler and outputs a file (which is Java byte code) that can be run only using a JRE. This is done so that, once the Java code is compiled then it can be ported to other machines in Java byte code format, which can be only run by JRE. If this is still confusing then you may want to have a look at this web page.

Here, you may ask if the CPython's bytecode is portable like Jython, I suspect not. The bytecode produced in CPython implementation was specific to that interpreter for making it easy for further execution of code (I also suspect that, such intermediate bytecode production, just for the ease the of processing is done in many other interpreters).

So, in Jython, when you compile your Python code, you end up with Java byte code, which can be run on a JVM.

Similarly, IronPython (written in C# language) compiles down your Python code to Common Language Runtime (CLR), which is a similar technology as compared to JVM, developed by Microsoft.

selectOneMenu ajax events

The PrimeFaces ajax events sometimes are very poorly documented, so in most cases you must go to the source code and check yourself.

p:selectOneMenu supports change event:

<p:selectOneMenu ..>
    <p:ajax event="change" update="msgtext"
        listener="#{post.subjectSelectionChanged}" />
    <!--...-->
</p:selectOneMenu>

which triggers listener with AjaxBehaviorEvent as argument in signature:

public void subjectSelectionChanged(final AjaxBehaviorEvent event)  {...}

Pandas: how to change all the values of a column?

As @DSM points out, you can do this more directly using the vectorised string methods:

df['Date'].str[-4:].astype(int)

Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):

df['Date'].str.extract('(?P<year>\d{4})').astype(int)

An alternative slightly more flexible way, might be to use apply (or equivalently map) to do this:

df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
             #  converts the last 4 characters of the string to an integer

The lambda function, is taking the input from the Date and converting it to a year.
You could (and perhaps should) write this more verbosely as:

def convert_to_year(date_in_some_format):
    date_as_string = str(date_in_some_format)  # cast to string
    year_as_string = date_in_some_format[-4:] # last four characters
    return int(year_as_string)

df['Date'] = df['Date'].apply(convert_to_year)

Perhaps 'Year' is a better name for this column...

How do I undo a checkout in git?

You probably want git checkout master, or git checkout [branchname].

How can I produce an effect similar to the iOS 7 blur view?

I just wrote my little subclass of UIView that has ability to produce native iOS 7 blur on any custom view. It uses UIToolbar but in a safe way for changing it's frame, bounds, color and alpha with real-time animation.

Please let me know if you notice any problems.

https://github.com/ivoleko/ILTranslucentView

ILTranslucentView examples

Changing all files' extensions in a folder with one command on Windows

NOTE: not for Windows

Using ren-1.0 the correct form is:

"ren *.*" "#2.jpg"

From man ren

The replacement pattern is another filename with embedded wildcard indexes, each of which consists of the character # followed by a digit from 1 to 9. In the new name of a matching file, the wildcard indexes are replaced by the actual characters that matched the referenced wildcards in the original filename.

and

Note that the shell normally expands the wildcards * and ?, which in the case of ren is undesirable. Thus, in most cases it is necessary to enclose the search pattern in quotes.

Make element fixed on scroll

There are some problems implementing this which the original accepted answer does not answer:

  1. The onscroll event of the window is firing very often. This implies that you either have to use a very performant listener, or you have to delay the listener somehow. jQuery Creator John Resig states here how a delayed mechanism can be implemented, and the reasons why you should do it. In my opinion, given todays browsers and environments, a performant listener will do as well. Here is an implementation of the pattern suggested by John Resig
  2. The way position:fixed works in css, if you scroll down the page and move an element from position:static to position: fixed, the page will "jump" a little because the document "looses" the height of the element. You can get rid of that by adding the height to the scrollTop and replace the lost height in the document body with another object. You can also use that object to determine if the sticky item has already been moved to position: fixed and reduce the calls to the code reverting position: fixed to the original state: Look at the fiddle here
  3. Now, the only expensive thing in terms of performance the handler is really doing is calling scrollTop on every call. Since the interval bound handler has also its drawbacks, I'll go as far as to argue here that you can reattach the event listener to the original scroll Event to make it feel snappier without many worries. You'll have to profile it though, on every browser you target / support. See it working here

Here's the code:

JS

/* Initialize sticky outside the event listener as a cached selector.
 * Also, initialize any needed variables outside the listener for 
 * performance reasons - no variable instantiation is happening inside the listener.
 */
var sticky = $('#sticky'),
    stickyClone,
    stickyTop = sticky.offset().top,
    scrollTop,
    scrolled = false,
    $window = $(window);

/* Bind the scroll Event */
$window.on('scroll', function (e) {
    scrollTop = $window.scrollTop();

    if (scrollTop >= stickyTop && !stickyClone) {
        /* Attach a clone to replace the "missing" body height */
        stickyClone = sticky.clone().prop('id', sticky.prop('id') + '-clone')
        stickyClone = stickyClone.insertBefore(sticky);
        sticky.addClass('fixed');
    } else if (scrollTop < stickyTop && stickyClone) {
        /* Since sticky is in the viewport again, we can remove the clone and the class */
        stickyClone.remove();
        stickyClone = null;
        sticky.removeClass('fixed');
    }
});

CSS

body {
    margin: 0
}
.sticky {
    padding: 1em;
    background: black;
    color: white;
    width: 100%
}
.sticky.fixed {
    position: fixed;
    top: 0;
    left: 0;
}
.content {
    padding: 1em
}

HTML

<div class="container">
  <div id="page-above" class="content">
    <h2>Some Content above sticky</h2>
    ...some long text...
  </div>
  <div id="sticky" class="sticky">This is sticky</div>
  <div id="page-content" class="content">
    <h2>Some Random Page Content</h2>...some really long text...
  </div>
</div>

Javascript Get Values from Multiple Select Option Box

Take a look at HTMLSelectElement.selectedOptions.

HTML

<select name="north-america" multiple>
  <option valud="ca" selected>Canada</a>
  <option value="mx" selected>Mexico</a>
  <option value="us">USA</a>
</select>

JavaScript

var elem = document.querySelector("select");

console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]

This would also work on non-multiple <select> elements


Warning: Support for this selectedOptions seems pretty unknown at this point

Twitter Bootstrap - add top space between rows

If you're using BootStrap 3.3.7, you can use the open source library bootstrap-spacer via NPM

npm install bootstrap-spacer

or you can visit the github page:

https://github.com/chigozieorunta/bootstrap-spacer

Here's an example of how this works to space rows using the .row-spacer class:

<div class="row row-spacer">
    <div class="col-md-4">
    </div>
    <div class="col-md-4">
    </div>
    <div class="col-md-4">
    </div>
</div>

<div class="row row-spacer">
    <div class="col-md-4">
    </div>
    <div class="col-md-4">
    </div>
    <div class="col-md-4">
    </div>
</div>

If you'd require spaces between columns, you can also add the .row-col-spacer class:

<div class="row row-col-spacer">
    <div class="col-md-4">
    </div>
    <div class="col-md-4">
    </div>
    <div class="col-md-4">
    </div>
</div>

And you can also combine various the .row-spacer & .row-col-spacer classes together:

<div class="row row-spacer row-col-spacer">
    <div class="col-md-4">
    </div>
    <div class="col-md-4">
    </div>
    <div class="col-md-4">
    </div>
</div>

SQLite Reset Primary Key Field

Try this:

delete from your_table;    
delete from sqlite_sequence where name='your_table';

SQLite Autoincrement

SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.

How can I access localhost from another computer in the same network?

localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost they'll be connecting to their computer instead or yours.

To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all on a command line.

You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.

Convert one date format into another in PHP

Try this:

$old_date = date('y-m-d-h-i-s');
$new_date = date('Y-m-d H:i:s', strtotime($old_date));

List of <p:ajax> events

Schedule provides various ajax behavior events to respond user actions.

  • "dateSelect" org.primefaces.event.SelectEvent When a date is selected.
  • "eventSelect" org.primefaces.event.SelectEvent When an event is selected.
  • "eventMove" org.primefaces.event.ScheduleEntryMoveEvent When an event is moved.
  • "eventResize" org.primefaces.event.ScheduleEntryResizeEvent When an event is resized.
  • "viewChange" org.primefaces.event.SelectEvent When a view is changed.
  • "toggleSelect" org.primefaces.event.ToggleSelectEvent When toggle all checkbox changes
  • "expand" org.primefaces.event.NodeExpandEvent When a node is expanded.
  • "collapse" org.primefaces.event.NodeCollapseEvent When a node is collapsed.
  • "select" org.primefaces.event.NodeSelectEvent When a node is selected.-
  • "collapse" org.primefaces.event.NodeUnselectEvent When a node is unselected
  • "expand org.primefaces.event.NodeExpandEvent When a node is expanded.
  • "unselect" org.primefaces.event.NodeUnselectEvent When a node is unselected.
  • "colResize" org.primefaces.event.ColumnResizeEvent When a column is resized
  • "page" org.primefaces.event.data.PageEvent On pagination.
  • "sort" org.primefaces.event.data.SortEvent When a column is sorted.
  • "filter" org.primefaces.event.data.FilterEvent On filtering.
  • "rowSelect" org.primefaces.event.SelectEvent When a row is being selected.
  • "rowUnselect" org.primefaces.event.UnselectEvent When a row is being unselected.
  • "rowEdit" org.primefaces.event.RowEditEvent When a row is edited.
  • "rowEditInit" org.primefaces.event.RowEditEvent When a row switches to edit mode
  • "rowEditCancel" org.primefaces.event.RowEditEvent When row edit is cancelled.
  • "colResize" org.primefaces.event.ColumnResizeEvent When a column is being selected.
  • "toggleSelect" org.primefaces.event.ToggleSelectEvent When header checkbox is toggled.
  • "colReorder" - When columns are reordered.
  • "rowSelectRadio" org.primefaces.event.SelectEvent Row selection with radio.
  • "rowSelectCheckbox" org.primefaces.event.SelectEvent Row selection with checkbox.
  • "rowUnselectCheckbox" org.primefaces.event.UnselectEvent Row unselection with checkbox.
  • "rowDblselect" org.primefaces.event.SelectEvent Row selection with double click.
  • "rowToggle" org.primefaces.event.ToggleEvent Row expand or collapse.
  • "contextMenu" org.primefaces.event.SelectEvent ContextMenu display.
  • "cellEdit" org.primefaces.event.CellEditEvent When a cell is edited.
  • "rowReorder" org.primefaces.event.ReorderEvent On row reorder.

there is more in here https://www.primefaces.org/docs/guide/primefaces_user_guide_5_0.pdf

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

source command not found in sh shell

In Bourne shell(sh), use the . command to source a file

. filename

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

See this http://blog.stevenlevithan.com/archives/date-time-format

you can do anything with date.

file : http://stevenlevithan.com/assets/misc/date.format.js

add this to your html code using script tag and to use you can use it as :

var now = new Date();

now.format("m/dd/yy");
// Returns, e.g., 6/09/07

How to create virtual column using MySQL SELECT?

You could use a CASE statement, like

SELECT name
       ,address
       ,CASE WHEN a < b THEN '1' 
             ELSE '2' END AS one_or_two
FROM ...

What are the differences between "git commit" and "git push"?

Basically git commit "records changes to the repository" while git push "updates remote refs along with associated objects". So the first one is used in connection with your local repository, while the latter one is used to interact with a remote repository.

Here is a nice picture from Oliver Steele, that explains the git model and the commands:

Git data transport commands

Read more about git push and git pull on GitReady.com (the article I referred to first)

Flutter: Setting the height of the AppBar

You can use PreferredSize:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Example',
      home: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(50.0), // here the desired height
          child: AppBar(
            // ...
          )
        ),
        body: // ...
      )
    );
  }
}

Relative path to absolute path in C#?

Assuming you know the real directory the XML file lives in use Path.Combine, e.g.

var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");

If you want to get back the full path with any ..'s collapsed then you can use:

Path.GetFullPath((new Uri(absolute_path)).LocalPath);

Rails select helper - Default selected value, how?

<%= f.select :project_id, @project_select, :selected => params[:pid] %>

How to give a delay in loop execution using Qt

C++11 has some portable timer stuff. Check out sleep_for.

How to check if an element of a list is a list (in Python)?

Expression you are looking for may be:

...
return any( isinstance(e, list) for e in my_list )

Testing:

>>> my_list = [1,2]
>>> any( isinstance(e, list) for e in my_list )
False
>>> my_list = [1,2, [3,4,5]]
>>> any( isinstance(e, list) for e in my_list )
True
>>> 

How to create an array from a CSV file using PHP and the fgetcsv function

Old question, but still relevant for PHP 5.2 users. str_getcsv is available from PHP 5.3. I've written a small function that works with fgetcsv itself.

Below is my function from https://gist.github.com/4152628:

function parse_csv_file($csvfile) {
    $csv = Array();
    $rowcount = 0;
    if (($handle = fopen($csvfile, "r")) !== FALSE) {
        $max_line_length = defined('MAX_LINE_LENGTH') ? MAX_LINE_LENGTH : 10000;
        $header = fgetcsv($handle, $max_line_length);
        $header_colcount = count($header);
        while (($row = fgetcsv($handle, $max_line_length)) !== FALSE) {
            $row_colcount = count($row);
            if ($row_colcount == $header_colcount) {
                $entry = array_combine($header, $row);
                $csv[] = $entry;
            }
            else {
                error_log("csvreader: Invalid number of columns at line " . ($rowcount + 2) . " (row " . ($rowcount + 1) . "). Expected=$header_colcount Got=$row_colcount");
                return null;
            }
            $rowcount++;
        }
        //echo "Totally $rowcount rows found\n";
        fclose($handle);
    }
    else {
        error_log("csvreader: Could not read CSV \"$csvfile\"");
        return null;
    }
    return $csv;
}

Returns

Begin Reading CSV

Array
(
    [0] => Array
        (
            [vid] => 
            [agency] => 
            [division] => Division
            [country] => 
            [station] => Duty Station
            [unit] => Unit / Department
            [grade] => 
            [funding] => Fund Code
            [number] => Country Office Position Number
            [wnumber] => Wings Position Number
            [title] => Position Title
            [tor] => Tor Text
            [tor_file] => 
            [status] => 
            [datetime] => Entry on Wings
            [laction] => 
            [supervisor] => Supervisor Index Number
            [asupervisor] => Alternative Supervisor Index
            [author] => 
            [category] => 
            [parent] => Reporting to Which Position Number
            [vacant] => Status (Vacant / Filled)
            [index] => Index Number
        )

    [1] => Array
        (
            [vid] => 
            [agency] => WFP
            [division] => KEN Kenya, The Republic Of
            [country] => 
            [station] => Nairobi
            [unit] => Human Resources Officer P4
            [grade] => P-4
            [funding] => 5000001
            [number] => 22018154
            [wnumber] => 
            [title] => Human Resources Officer P4
            [tor] => 
            [tor_file] => 
            [status] => 
            [datetime] => 
            [laction] => 
            [supervisor] => 
            [asupervisor] => 
            [author] => 
            [category] => Professional
            [parent] => 
            [vacant] => 
            [index] => xxxxx
        )
) 

Google Maps how to Show city or an Area outline

so I have a solution that isn't perfect but it worked for me. Use the polygon example from Google, and use the pinpoint on Google Maps to get lat & long locations.

Calgary pinpoint

I used what I call "ocular copy & paste" where you look at the screen and then write in the numbers you want ;-)

<style>
  #map {
    height: 500px;
  }
</style>
<script>

// This example creates a simple polygon representing the host city of the 
// Greatest Outdoor Show On Earth.

 function initMap() {
   var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 9,
      center: {lat: 51.039, lng: -114.204},
      mapTypeId: 'terrain'
    });

    // Define the LatLng coordinates for the polygon's path.
    var triangleCoords = [
      {lat: 51.183, lng: -114.234},
      {lat: 51.154, lng: -114.235},
      {lat: 51.156, lng: -114.261},
      {lat: 51.104, lng: -114.259},
      {lat: 51.106, lng: -114.261},
      {lat: 51.102, lng: -114.272},
      {lat: 51.081, lng: -114.271},
      {lat: 51.081, lng: -114.234},
      {lat: 51.009, lng: -114.236},
      {lat: 51.008, lng: -114.141},
      {lat: 50.995, lng: -114.142},
      {lat: 50.998, lng: -114.160},
      {lat: 50.984, lng: -114.163},
      {lat: 50.987, lng: -114.141},
      {lat: 50.979, lng: -114.141},
      {lat: 50.921, lng: -114.141},
      {lat: 50.921, lng: -114.210},
      {lat: 50.893, lng: -114.210},
      {lat: 50.892, lng: -114.140},
      {lat: 50.888, lng: -114.139},
      {lat: 50.878, lng: -114.094},
      {lat: 50.878, lng: -113.994},
      {lat: 50.840, lng: -113.954},
      {lat: 50.854, lng: -113.905},
      {lat: 50.922, lng: -113.906},
      {lat: 50.935, lng: -113.877},
      {lat: 50.943, lng: -113.877},
      {lat: 50.955, lng: -113.912},
      {lat: 51.183, lng: -113.910}
    ];

    // Construct the polygon.
    var bermudaTriangle = new google.maps.Polygon({
      paths: triangleCoords,
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35
    });
    bermudaTriangle.setMap(map);
  }
</script>


<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&callback=initMap">
</script>

This gets you the outline for Calgary. I've attached an image here.

IndentationError: unindent does not match any outer indentation level

For what its worth, my docstring was indented too much and this also throws the same error

class junk: 
     """docstring is indented too much""" 
    def fun(): return   

IndentationError: unindent does not match any outer indentation level

How To Format A Block of Code Within a Presentation?

If you write your code in emacs then you might be interested in the htmlize elisp package.

Iterating over dictionaries using 'for' loops

This is a very common looping idiom. in is an operator. For when to use for key in dict and when it must be for key in dict.keys() see David Goodger's Idiomatic Python article (archived copy).

Twitter Bootstrap alert message close and open again

If you're using an MVVM library such as knockout.js (which I highly recommend) you can do it more cleanly:

<div class="alert alert-info alert-dismissible" data-bind="visible:showAlert">
   <button type="button" class="close" data-bind="click:function(){showAlert(false);}>
        <span aria-hidden="true">&times;</span>
        <span class="sr-only">Close</span>
   </button>
   Warning! Better check yourself, you're not looking too good.
</div>

http://jsfiddle.net/bce9gsav/5/

How to convert Seconds to HH:MM:SS using T-SQL

You want to multiply out to milliseconds as the fractional part is discarded.

SELECT DATEADD(ms, 121.25 * 1000, 0)

If you want it without the date portion you can use CONVERT, with style 114

SELECT CONVERT(varchar, DATEADD(ms, 121.25 * 1000, 0), 114)

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

New og:image size for Facebook share?

The aspect ratio for a Facebook post image is 41:20.

To find the appropriate widths and height for your photo, you can use the Aspect Ratio Calculator.

Here you can select different ratios under “Common ratios:” which includes the option “1200 x 630 (Facebook)". So if the width of your photo is 1800, plug that number into the “W2” slot and it will tell you what the respective height should be.

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

How should I print types like off_t and size_t?

For Microsoft, the answer is different. VS2013 is largely C99 compliant but "[t]he hh, j, z, and t length prefixes are not supported." For size_t "that is, unsigned __int32 on 32-bit platforms, unsigned __int64 on 64-bit platforms" use prefix I (capital eye) with type specifier o, u, x, or X. See VS2013 Size specification

As for off_t, it is defined as long in VC\include\sys\types.h.

How to trigger a click on a link using jQuery

For links this should work:

eval($(selector).attr('href'));

Check if a string is a palindrome

 private void CheckIfPalindrome(string str) 
        {
            //place string in array of chars
            char[] array = str.ToCharArray(); 
            int length = array.Length -1 ;
            Boolean palindrome =true;
            for (int i = 0; i <= length; i++)//go through the array
            {
                if (array[i] != array[length])//compare if the char in the same positions are the same eg "tattarrattat" will compare array[0]=t with array[11] =t if are not the same stop the for loop
                {
                    MessageBox.Show("not");
                    palindrome = false;
                    break;

                }
                else //if they are the same make length smaller by one and do the same 
                {                   
                  length--;
                }

            }
            if (palindrome) MessageBox.Show("Palindrome"); 

        }

PHP Regex to check date is in YYYY-MM-DD format

From Laravel 5.7 and date format i.e.: 12/31/2019

function checkDateFormat(string $date): bool
{
    return preg_match("/^(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])\/[0-9]{4}$/", $date);
}

How to select into a variable in PL/SQL when the result might be null?

I know it's an old thread, but I still think it's worth to answer it.

select (
        SELECT COLUMN FROM MY_TABLE WHERE ....
        ) into v_column
from dual;

Example of use:

declare v_column VARCHAR2(100);
begin
  select (SELECT TABLE_NAME FROM ALL_TABLES WHERE TABLE_NAME = 'DOES NOT EXIST')
  into v_column 
  from dual;
  DBMS_OUTPUT.PUT_LINE('v_column=' || v_column);
end;

PHP How to fix Notice: Undefined variable:

I would guess your query isn't running as expected and you are getting to the return line with undefined variables.

Also, the way you are doing the variable assignment, you would be overwriting the same variable with each loop iteration, so you wouldn't return the entire result set.

Finally, it seems odd to return a numerically-keyed result set instead of an associatively-keyed one. Consider naming only the fields needed in the SELECT and keeping the key assignments. So something like this:

Function ShowDataPatient($idURL){
       $query =" select * from cmu_list_insurance,cmu_home,cmu_patient where cmu_home.home_id = (select home_id from cmu_patient where patient_hn like '%$idURL%')
                 AND cmu_patient.patient_hn like '%$idURL%'
                 AND cmu_list_insurance.patient_id like (select patient_id from cmu_patient where patient_hn like '%$idURL%') ";

   $result = pg_query($query) or die('Query failed: ' . pg_last_error());

   $return = array();
   while ($row = pg_fetch_array($result)){
       $return[] = $row;
   }          

   return $return;
}

You might also consider opening a question about how to improve your query, is it is pretty heinous as it stands now.

SQL update from one Table to another based on a ID match

If above answers not working for you try this

Update Sales_Import A left join RetrieveAccountNumber B on A.LeadID = B.LeadID
Set A.AccountNumber = B.AccountNumber
where A.LeadID = B.LeadID 

How can I check if the current date/time is past a set date/time?

Since PHP >= 5.2.2 you can use the DateTime class as such:

if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
    # current time is greater than 2010-05-15 16:00:00
    # in other words, 2010-05-15 16:00:00 has passed
}

The string passed to the DateTime constructor is parsed according to these rules.


Note that it is also possible to use time and strtotime functions. See original answer.

Assigning default values to shell variables with a single command in bash

If the variable is same, then

: "${VARIABLE:=DEFAULT_VALUE}"

assigns DEFAULT_VALUE to VARIABLE if not defined. The double quotes prevent globbing and word splitting.

Also see Section 3.5.3, Shell Parameter Expansion, in the Bash manual.

CHECK constraint in MySQL is not working

try with set sql_mode = 'STRICT_TRANS_TABLES' OR SET sql_mode='STRICT_ALL_TABLES'

Sorting using Comparator- Descending order (User defined classes)

You can do the descending sort of a user-defined class this way overriding the compare() method,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return b.getName().compareTo(a.getName());
    }
});

Or by using Collection.reverse() to sort descending as user Prince mentioned in his comment.

And you can do the ascending sort like this,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }
});

Replace the above code with a Lambda expression(Java 8 onwards) we get concise:

Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));

As of Java 8, List has sort() method which takes Comparator as parameter(more concise) :

personList.sort((a,b)->b.getName().compareTo(a.getName()));

Here a and b are inferred as Person type by lambda expression.

Best way to parseDouble with comma as decimal separator?

You can use this (the French locale has , for decimal separator)

NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
nf.parse(p);

Or you can use java.text.DecimalFormat and set the appropriate symbols:

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
symbols.setGroupingSeparator(' ');
df.setDecimalFormatSymbols(symbols);
df.parse(p);

Center Oversized Image in Div

based on @Guffa answer
because I lost more than 2 hours to center a very wide image,
for me with a image dimendion of 2500x100px and viewport 1600x1200 or Full HD 1900x1200 works centered like that:

 .imageContainer {
  height: 100px;
  overflow: hidden;
  position: relative;
 }
 .imageCenter {
  width: auto;
  position: absolute;
  left: -10%;
  top: 0;
  margin-left: -500px;
 }
.imageCenter img {
 display: block;
 margin: 0 auto;
 }

I Hope this helps others to finish faster the task :)

Socket accept - "Too many open files"

There are multiple places where Linux can have limits on the number of file descriptors you are allowed to open.

You can check the following:

cat /proc/sys/fs/file-max

That will give you the system wide limits of file descriptors.

On the shell level, this will tell you your personal limit:

ulimit -n

This can be changed in /etc/security/limits.conf - it's the nofile param.

However, if you're closing your sockets correctly, you shouldn't receive this unless you're opening a lot of simulataneous connections. It sounds like something is preventing your sockets from being closed appropriately. I would verify that they are being handled properly.

Netbeans installation doesn't find JDK

We managed installation of netbeans 6.8 under windows 8 successfully the following way:

  • Don't execute but unzip netbeans-6.8-ml-windows.exe with 7zip (or other unzipper) in an emtpy folder
  • execute cmd.exe as administrator
  • cd to the folder in which you unzipped the installer
  • execute 'java org.netbeans.installer.Installer'

-> installation executes without any errors

Can I escape a double quote in a verbatim string literal?

Use double quotation marks.

string foo = @"this ""word"" is escaped";

Install tkinter for Python

for python3 user, install python3-tk package by following command sudo apt-get install python3-tk

Find text string using jQuery?

jQuery has the contains method. Here's a snippet for you:

<script type="text/javascript">
$(function() {
    var foundin = $('*:contains("I am a simple string")');
});
</script>

The selector above selects any element that contains the target string. The foundin will be a jQuery object that contains any matched element. See the API information at: https://api.jquery.com/contains-selector/

One thing to note with the '*' wildcard is that you'll get all elements, including your html an body elements, which you probably don't want. That's why most of the examples at jQuery and other places use $('div:contains("I am a simple string")')

Replace a string in shell script using a variable

To let your shell expand the variable, you need to use double-quotes like

sed -i "s#12345678#$replace#g" file.txt

This will break if $replace contain special sed characters (#, \). But you can preprocess $replace to quote them:

replace_quoted=$(printf '%s' "$replace" | sed 's/[#\]/\\\0/g')
sed -i "s#12345678#$replace_quoted#g" file.txt

How to replace comma with a dot in the number (or any replacement)

From the function's definition (http://www.w3schools.com/jsref/jsref_replace.asp):

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

This method does not change the original string.

Hence, the line: tt.replace(/,/g, '.') does not change the value of tt; it just returns the new value.

You need to replace this line with: tt = tt.replace(/,/g, '.')

Evaluate expression given as a string

Not sure why no one has mentioned two Base R functions specifically to do this: str2lang() and str2expression(). These are variants of parse(), but seem to return the expression more cleanly:

eval(str2lang("5+5"))

# > 10
  
eval(str2expression("5+5"))

# > 10

Also want to push back against the posters saying that anyone trying to do this is wrong. I'm reading in R expressions stored as text in a file and trying to evaluate them. These functions are perfect for this use case.

Can't start Eclipse - Java was started but returned exit code=13

Make sure you don't have special characters (%, $, #, etc.) at Eclipse path.

Passing a Bundle on startActivity()?

You can pass values from one activity to another activity using the Bundle. In your current activity, create a bundle and set the bundle for the particular value and pass that bundle to the intent.

Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);

Now in your NewActivity, you can get this bundle and retrive your value.

Bundle bundle = getArguments();
String value = bundle.getString(key);

You can also pass data through the intent. In your current activity, set intent like this,

Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);

Now in your NewActivity, you can get that value from intent like this,

String value = getIntent().getExtras().getString(key);

SQL - Create view from multiple tables

This works too and you dont have to use join or anything:

DROP VIEW IF EXISTS yourview;

CREATE VIEW yourview AS
    SELECT table1.column1, 
    table2.column2
FROM 
table1, table2 
WHERE table1.column1 = table2.column1;

Instagram API to fetch pictures with specific hashtags

Firstly, the Instagram API endpoint "tags" required OAuth authentication.

You can query results for a particular hashtag (snowy in this case) using the following url

It is rate limited to 5000 (X-Ratelimit-Limit:5000) per hour

https://api.instagram.com/v1/tags/snowy/media/recent

Sample response

{
  "pagination":  {
    "next_max_tag_id": "1370433362010",
    "deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
    "next_max_id": "1370433362010",
    "next_min_id": "1370443976800",
    "min_tag_id": "1370443976800",
    "next_url": "https://api.instagram.com/v1/tags/snowy/media/recent?access_token=40480112.1fb234f.4866541998fd4656a2e2e2beaa5c4bb1&max_tag_id=1370433362010"
  },
  "meta":  {
    "code": 200
  },
  "data":  [
     {
      "attribution": null,
      "tags":  [
        "snowy"
      ],
      "type": "image",
      "location": null,
      "comments":  {
        "count": 0,
        "data":  []
      },
      "filter": null,
      "created_time": "1370418343",
      "link": "http://instagram.com/p/aK1yrGRi3l/",
      "likes":  {
        "count": 1,
        "data":  [
           {
            "username": "iri92lol",
            "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
            "id": "404174490",
            "full_name": "Iri"
          }
        ]
      },
      "images":  {
        "low_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_6.jpg",
          "width": 306,
          "height": 306
        },
        "thumbnail":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_5.jpg",
          "width": 150,
          "height": 150
        },
        "standard_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_7.jpg",
          "width": 612,
          "height": 612
        }
      },
      "users_in_photo":  [],
      "caption":  {
        "created_time": "1370418353",
        "text": "#snowy",
        "from":  {
          "username": "iri92lol",
          "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
          "id": "404174490",
          "full_name": "Iri"
        },
        "id": "471425773832908504"
      },
      "user_has_liked": false,
      "id": "471425689728724453_404174490",
      "user":  {
        "username": "iri92lol",
        "website": "",
        "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
        "full_name": "Iri",
        "bio": "",
        "id": "404174490"
      }
    }
}

You can play around here :

https://apigee.com/console/instagram?req=%7B%22resource%22%3A%22get_tags_media_recent%22%2C%22params%22%3A%7B%22query%22%3A%7B%7D%2C%22template%22%3A%7B%22tag-name%22%3A%22snowy%22%7D%2C%22headers%22%3A%7B%7D%2C%22body%22%3A%7B%22attachmentFormat%22%3A%22mime%22%2C%22attachmentContentDisposition%22%3A%22form-data%22%7D%7D%2C%22verb%22%3A%22get%22%7D

You need to use "Authentication" as OAuth 2 and will be prompted to signin via Instagram. Post that you might have to reneter the "tag-name" in "Template" section.

All the pagination related data is available in the "pagination" parameter in the response and use it's "next_url" to query for the next set of result.

How to run the Python program forever?

I have a small script interruptableloop.py that runs the code at an interval (default 1sec), it pumps out a message to the screen while it's running, and traps an interrupt signal that you can send with CTL-C:

#!/usr/bin/python3
from interruptableLoop import InterruptableLoop

loop=InterruptableLoop(intervalSecs=1) # redundant argument
while loop.ShouldContinue():
   # some python code that I want 
   # to keep on running
   pass

When you run the script and then interrupt it you see this output, (the periods pump out on every pass of the loop):

[py36]$ ./interruptexample.py
CTL-C to stop   (or $kill -s SIGINT pid)
......^C
Exiting at  2018-07-28 14:58:40.359331

interruptableLoop.py:

"""
    Use to create a permanent loop that can be stopped ...

    ... from same terminal where process was started and is running in foreground: 
        CTL-C

    ... from same user account but through a different terminal 
        $ kill -2 <pid> 
        or $ kill -s SIGINT <pid>

"""
import signal
import time
from datetime import datetime as dtt
__all__=["InterruptableLoop",]
class InterruptableLoop:
    def __init__(self,intervalSecs=1,printStatus=True):
        self.intervalSecs=intervalSecs
        self.shouldContinue=True
        self.printStatus=printStatus
        self.interrupted=False
        if self.printStatus:
            print ("CTL-C to stop\t(or $kill -s SIGINT pid)")
        signal.signal(signal.SIGINT, self._StopRunning)
        signal.signal(signal.SIGQUIT, self._Abort)
        signal.signal(signal.SIGTERM, self._Abort)

    def _StopRunning(self, signal, frame):
        self.shouldContinue = False

    def _Abort(self, signal, frame):
        raise 

    def ShouldContinue(self):
        time.sleep(self.intervalSecs)
        if self.shouldContinue and self.printStatus: 
            print( ".",end="",flush=True)
        elif not self.shouldContinue and self.printStatus:
            print ("Exiting at ",dtt.now())
        return self.shouldContinue

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

The dispatcher-servlet.xml file contains all of your configuration for Spring MVC. So in it you will find beans such as ViewHandlerResolvers, ConverterFactories, Interceptors and so forth. All of these beans are part of Spring MVC which is a framework that structures how you handle web requests, providing useful features such as databinding, view resolution and request mapping.

The application-context.xml can optionally be included when using Spring MVC or any other framework for that matter. This gives you a container that may be used to configure other types of spring beans that provide support for things like data persistence. Basically, in this configuration file is where you pull in all of the other goodies Spring offers.

These configuration files are configured in the web.xml file as shown:

Dispatcher Config

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Application Config

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/application-context.xml</param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

To configure controllers, annotate them with @Controller then include the following in the dispatcher-context.xml file:

<mvc:annotation-driven/>
<context:component-scan base-package="package.with.controllers.**" />

C# windows application Event: CLR20r3 on application start

To solve CLR20r3 problem set - Local User Policy \ Computer Configuration \ Windows Settings \ Security Settings \ Local Policies \ Security Options - System cryptography: Use FIPS 140 compliant cryptographic algorithms, including encryption, hashing and signing - Disable

Error Code: 2013. Lost connection to MySQL server during query

I had the same problem - but for me the solution was a DB user with too strict permissions. I had to allow the Execute ability on the mysql table. After allowing that I had no dropping connections anymore

How do you copy and paste into Git Bash

Windows:

  1. Right click
  2. Choose Options
  3. Choose Keys
  4. Enable Ctrl+Shift+letter shortcuts

How does it look like?

Download and install an ipa from self hosted url on iOS

NSURL *url = [NSURL URLWithString:@"itms-services://?action=download-manifest&amp;url=https://xxxxxx.com/rest/images/apps/ipa/dev/xyz.plist"]];
[[UIApplication sharedApplication] openURL:url];

openUrl method was deprecated.

[[UIApplication sharedApplication] openURL: url options:@{} completionHandler:nil];

This method latest openUrl method and it will display prompt dialog.The dialog will show

xxxxxx.com would like to install "YOUR_APP_NAME"

this messages. If you click the "install" button application will close and ipa will download.

Android Studio - How to increase Allocated Heap Size

Note: I now this is not the answer for the post, but maybe this will be helpful for some one that is looking.

If Nothing of this works for you, try on a Mac this to see if helps you, in the last version of Android Studio, the studio.vmoptions is inside the AndroidStudio.app in your Applications folder.

So right click or ctrl click on your AndroidStudio.App and then select show package content the studio.vmoptions is in:

Contents/bin/studio.vmoptions

Replace or change it and you will get all the RAM you need.

enter image description here enter image description here

Regards.

How To limit the number of characters in JTextField?

import java.awt.KeyboardFocusManager;
import javax.swing.InputVerifier;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

/**
 *
 * @author Igor
 */
public class CustomLengthTextField extends JTextField {

    protected boolean upper = false;
    protected int maxlength = 0;

    public CustomLengthTextField() {
        this(-1);
    }

    public CustomLengthTextField(int length, boolean upper) {
        this(length, upper, null);
    }

    public CustomLengthTextField(int length, InputVerifier inpVer) {
        this(length, false, inpVer);
    }

    /**
     *
     * @param length - maksimalan length
     * @param upper - turn it to upercase
     * @param inpVer - InputVerifier
     */
    public CustomLengthTextField(int length, boolean upper, InputVerifier inpVer) {
        super();
        this.maxlength = length;
        this.upper = upper;
        if (length > 0) {
            AbstractDocument doc = (AbstractDocument) getDocument();
            doc.setDocumentFilter(new DocumentSizeFilter());
        }
        setInputVerifier(inpVer);
    }

    public CustomLengthTextField(int length) {
        this(length, false);
    }

    public void setMaxLength(int length) {
        this.maxlength = length;
    }

    class DocumentSizeFilter extends DocumentFilter {

        public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
                throws BadLocationException {

            //This rejects the entire insertion if it would make
            //the contents too long. Another option would be
            //to truncate the inserted string so the contents
            //would be exactly maxCharacters in length.
            if ((fb.getDocument().getLength() + str.length()) <= maxlength) {
                super.insertString(fb, offs, str, a);
            }
        }

        public void replace(FilterBypass fb, int offs,
                int length,
                String str, AttributeSet a)
                throws BadLocationException {

            if (upper) {
                str = str.toUpperCase();
            }

            //This rejects the entire replacement if it would make
            //the contents too long. Another option would be
            //to truncate the replacement string so the contents
            //would be exactly maxCharacters in length.
            int charLength = fb.getDocument().getLength() + str.length() - length;

            if (charLength <= maxlength) {
                super.replace(fb, offs, length, str, a);
                if (charLength == maxlength) {
                    focusNextComponent();
                }
            } else {
                focusNextComponent();
            }
        }

        private void focusNextComponent() {
            if (CustomLengthTextField.this == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) {
                KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
            }
        }
    }
}

How do I find ' % ' with the LIKE operator in SQL Server?

Try this:

declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%' 

You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _

How to enable CORS in AngularJs

        var result=[];
        var app = angular.module('app', []);
        app.controller('myCtrl', function ($scope, $http) {
             var url="";// your request url    
             var request={};// your request parameters
             var headers = {
             // 'Authorization': 'Basic ' + btoa(username + ":" + password),
            'Access-Control-Allow-Origin': true,
            'Content-Type': 'application/json; charset=utf-8',
            "X-Requested-With": "XMLHttpRequest"
              }
             $http.post(url, request, {
                        headers
                 })
                 .then(function Success(response) {
                      result.push(response.data);             
                      $scope.Data = result;              
                 }, 
                  function Error(response) {
                      result.push(response.data);
                       $scope.Data = result;
                    console.log(response.statusText + " " + response.status)
               }); 
     });

And also add following code in your WebApiConfig file            
        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

Using :: in C++

The :: are used to dereference scopes.

const int x = 5;

namespace foo {
  const int x = 0;
}

int bar() {
  int x = 1;
  return x;
}

struct Meh {
  static const int x = 2;
}

int main() {
  std::cout << x; // => 5
  {
    int x = 4;
    std::cout << x; // => 4
    std::cout << ::x; // => 5, this one looks for x outside the current scope
  }
  std::cout << Meh::x; // => 2, use the definition of x inside the scope of Meh
  std::cout << foo::x; // => 0, use the definition of x inside foo
  std::cout << bar(); // => 1, use the definition of x inside bar (returned by bar)
}

unrelated: cout and cin are not functions, but instances of stream objects.

EDIT fixed as Keine Lust suggested

How can I disable the Maven Javadoc plugin from the command line?

You can use the maven.javadoc.skip property to skip execution of the plugin, going by the Mojo's javadoc. You can specify the value as a Maven property:

<properties>
    <maven.javadoc.skip>true</maven.javadoc.skip>
</properties>

or as a command-line argument: -Dmaven.javadoc.skip=true, to skip generation of the Javadocs.

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

You will get this error when you call any of the setXxx() methods on PreparedStatement, while the SQL query string does not have any placeholders ? for this.

For example this is wrong:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (val1, val2, val3)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1); // Fail.
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

You need to fix the SQL query string accordingly to specify the placeholders.

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)";
// ...

preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, val1);
preparedStatement.setString(2, val2);
preparedStatement.setString(3, val3);

Note the parameter index starts with 1 and that you do not need to quote those placeholders like so:

String sql = "INSERT INTO tablename (col1, col2, col3) VALUES ('?', '?', '?')";

Otherwise you will still get the same exception, because the SQL parser will then interpret them as the actual string values and thus can't find the placeholders anymore.

See also:

Virtualhost For Wildcard Subdomain and Static Subdomain

<VirtualHost *:80>
  DocumentRoot /var/www/app1
  ServerName app1.example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/example
  ServerName example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/wildcard
  ServerName other.example.com
  ServerAlias *.example.com
</VirtualHost>

Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.

Force SSL/https using .htaccess and mod_rewrite

I found a mod_rewrite solution that works well for both proxied and unproxied servers.

If you are using CloudFlare, AWS Elastic Load Balancing, Heroku, OpenShift or any other Cloud/PaaS solution and you are experiencing redirect loops with normal HTTPS redirects, try the following snippet instead.

RewriteEngine On

# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]

# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on

# Redirect to https version
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

How to use bitmask?

Briefly bitmask helps to manipulate position of multiple values. There is a good example here ;

Bitflags are a method of storing multiple values, which are not mutually exclusive, in one variable. You've probably seen them before. Each flag is a bit position which can be set on or off. You then have a bunch of bitmasks #defined for each bit position so you can easily manipulate it:

    #define LOG_ERRORS            1  // 2^0, bit 0
    #define LOG_WARNINGS          2  // 2^1, bit 1
    #define LOG_NOTICES           4  // 2^2, bit 2
    #define LOG_INCOMING          8  // 2^3, bit 3
    #define LOG_OUTGOING         16  // 2^4, bit 4
    #define LOG_LOOPBACK         32  // and so on...

// Only 6 flags/bits used, so a char is fine
unsigned char flags;

// initialising the flags
// note that assigning a value will clobber any other flags, so you
// should generally only use the = operator when initialising vars.
flags = LOG_ERRORS;
// sets to 1 i.e. bit 0

//initialising to multiple values with OR (|)
flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING;
// sets to 1 + 2 + 8 i.e. bits 0, 1 and 3

// setting one flag on, leaving the rest untouched
// OR bitmask with the current value
flags |= LOG_INCOMING;

// testing for a flag
// AND with the bitmask before testing with ==
if ((flags & LOG_WARNINGS) == LOG_WARNINGS)
   ...

// testing for multiple flags
// as above, OR the bitmasks
if ((flags & (LOG_INCOMING | LOG_OUTGOING))
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

// removing a flag, leaving the rest untouched
// AND with the inverse (NOT) of the bitmask
flags &= ~LOG_OUTGOING;

// toggling a flag, leaving the rest untouched
flags ^= LOG_LOOPBACK;



**

WARNING: DO NOT use the equality operator (i.e. bitflags == bitmask) for testing if a flag is set - that expression will only be true if that flag is set and all others are unset. To test for a single flag you need to use & and == :

**

if (flags == LOG_WARNINGS) //DON'T DO THIS
   ...
if ((flags & LOG_WARNINGS) == LOG_WARNINGS) // The right way
   ...
if ((flags & (LOG_INCOMING | LOG_OUTGOING)) // Test for multiple flags set
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

You can also search C++ Triks

What do Clustered and Non clustered index actually mean?

Clustered Index - A clustered index defines the order in which data is physically stored in a table. Table data can be sorted in only way, therefore, there can be only one clustered index per table. In SQL Server, the primary key constraint automatically creates a clustered index on that particular column.

Non-Clustered Index - A non-clustered index doesn’t sort the physical data inside the table. In fact, a non-clustered index is stored at one place and table data is stored in another place. This is similar to a textbook where the book content is located in one place and the index is located in another. This allows for more than one non-clustered index per table.It is important to mention here that inside the table the data will be sorted by a clustered index. However, inside the non-clustered index data is stored in the specified order. The index contains column values on which the index is created and the address of the record that the column value belongs to.When a query is issued against a column on which the index is created, the database will first go to the index and look for the address of the corresponding row in the table. It will then go to that row address and fetch other column values. It is due to this additional step that non-clustered indexes are slower than clustered indexes

Differences between clustered and Non-clustered index

  1. There can be only one clustered index per table. However, you can create multiple non-clustered indexes on a single table.
  2. Clustered indexes only sort tables. Therefore, they do not consume extra storage. Non-clustered indexes are stored in a separate place from the actual table claiming more storage space.
  3. Clustered indexes are faster than non-clustered indexes since they don’t involve any extra lookup step.

For more information refer to this article.

Get request URL in JSP which is forwarded by Servlet

Same as @axtavt, but you can use also the RequestDispatcher constant.

request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);

How to make tesseract to recognize only numbers, when they are mixed with letters?

You can instruct tesseract to use only digits, and if that is not accurate enough then best chance of getting better results is to go trough training process: http://www.resolveradiologic.com/blog/2013/01/15/training-tesseract/

What issues should be considered when overriding equals and hashCode in Java?

Still amazed that none recommended the guava library for this.

 //Sample taken from a current working project of mine just to illustrate the idea

    @Override
    public int hashCode(){
        return Objects.hashCode(this.getDate(), this.datePattern);
    }

    @Override
    public boolean equals(Object obj){
        if ( ! obj instanceof DateAndPattern ) {
            return false;
        }
        return Objects.equal(((DateAndPattern)obj).getDate(), this.getDate())
                && Objects.equal(((DateAndPattern)obj).getDate(), this.getDatePattern());
    }

Print a string as hex bytes?

This can be done in following ways:

from __future__ import print_function
str = "Hello World !!"
for char in str:
    mm = int(char.encode('hex'), 16)
    print(hex(mm), sep=':', end=' ' )

The output of this will be in hex as follows:

0x48 0x65 0x6c 0x6c 0x6f 0x20 0x57 0x6f 0x72 0x6c 0x64 0x20 0x21 0x21

Allowing Untrusted SSL Certificates with HttpClient

Or you can use for the HttpClient in the Windows.Web.Http namespace:

var filter = new HttpBaseProtocolFilter();
#if DEBUG
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
#endif
using (var httpClient = new HttpClient(filter)) {
    ...
}

What design patterns are used in Spring framework?

Service Locator Pattern - ServiceLocatorFactoryBean keeps information of all the beans in the context. When client code asks for a service (bean) using name, it simply locates that bean in the context and returns it. Client code does not need to write spring related code to locate a bean.

adding classpath in linux

Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH% is used to represent value of existing path variable in Windows while ${PATH} is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:

export CLASSPATH=${CLASSPATH}:/new/path

but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:

  1. -cp options overrides CLASSPATH environment variable.
  2. Classpath defined in Manifest file overrides both -cp and CLASSPATH envorinment variable.

Reference: How Classpath works in Java.

How to force 'cp' to overwrite directory instead of creating another one inside?

Try to use this composed of two steps command:

rm -rf bar && cp -r foo bar

How to export datagridview to excel using vb.net?

Regarding your need to 'print directly from datagridview', check out this article on CodeProject:

The DataGridViewPrinter Class

There are a number of similar articles but I've had luck with the one I linked.

How to check type of files without extensions in python?

With newer subprocess library, you can now use the following code (*nix only solution):

import subprocess
import shlex

filename = 'your_file'
cmd = shlex.split('file --mime-type {0}'.format(filename))
result = subprocess.check_output(cmd)
mime_type = result.split()[-1]
print mime_type

How to get pandas.DataFrame columns containing specific dtype

There's a new feature in 0.14.1, select_dtypes to select columns by dtype, by providing a list of dtypes to include or exclude.

For example:

df = pd.DataFrame({'a': np.random.randn(1000),
                   'b': range(1000),
                   'c': ['a'] * 1000,
                   'd': pd.date_range('2000-1-1', periods=1000)})


df.select_dtypes(['float64','int64'])

Out[129]: 
            a    b
0    0.153070    0
1    0.887256    1
2   -1.456037    2
3   -1.147014    3
...

Stored procedure return into DataSet in C# .Net

Try this

    DataSet ds = new DataSet("TimeRanges");
    using(SqlConnection conn = new SqlConnection("ConnectionString"))
    {               
            SqlCommand sqlComm = new SqlCommand("Procedure1", conn);               
            sqlComm.Parameters.AddWithValue("@Start", StartTime);
            sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
            sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);

            sqlComm.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = sqlComm;

            da.Fill(ds);
     }

[Vue warn]: Cannot find element

I get the same error. the solution is to put your script code before the end of body, not in the head section.

Visual Studio 2015 is very slow

Try uninstalling either Node.js Tools for Visual Studio (NTVS) or the commercial add-on called ReSharper from JetBrains. Using both NTVS and Resharper causes memory leaks in Visual Studio 2015.

NTVS = Node Tools for Visual Studio

How do I get a PHP class constructor to call its parent's parent's constructor?

Another option that doesn't use a flag and might work in your situation:

<?php
// main class that everything inherits
class Grandpa 
{
    public function __construct(){
        $this->GrandpaSetup();
    }

    public function GrandpaSetup(){
        $this->prop1 = 'foo';
        $this->prop2 = 'bar';
    }
}

class Papa extends Grandpa
{
    public function __construct()
    {
        // call Grandpa's constructor
        parent::__construct();
        $this->prop1 = 'foobar';
    }

}
class Kiddo extends Papa
{
    public function __construct()
    {
        $this->GrandpaSetup();
    }
}

$kid = new Kiddo();
echo "{$kid->prop1}\n{$kid->prop2}\n";

html form - make inputs appear on the same line

This test shows three blocks of two blocks together on the same line.

_x000D_
_x000D_
.group {
    display:block;
    box-sizing:border-box;
}
.group>div {
    display:inline-block;
    padding-bottom:4px;
}
.group>div>span,.group>div>div {
    width:200px;
    height:40px;
    text-align: center;
    padding-top:20px;
    padding-bottom:0px;
    display:inline-block;
    border:1px solid black;
    background-color:blue;
    color:white;
}

input[type=text] {
    height:1em;
}
_x000D_
<div class="group">
    <div>
        <span>First Name</span>
        <span><input type="text"/></span>
    </div>
    <div>
        <div>Last Name</div>
        <div><input type="text"/></div>
    </div>
    <div>
        <div>Address</div>
        <div><input type="text"/></div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

matplotlib: Group boxplots

Grouped boxplots, towards subtle academic publication styling... (source)

(Left) Python 2.7.12 Matplotlib v1.5.3. (Right) Python 3.7.3. Matplotlib v3.1.0.

grouped boxplot example png for Python 2.7.12 Matplotlib v1.5.3 grouped boxplot example png for Python 3.7.3 Matplotlib v3.1.0

Code:

import numpy as np
import matplotlib.pyplot as plt

# --- Your data, e.g. results per algorithm:
data1 = [5,5,4,3,3,5]
data2 = [6,6,4,6,8,5]
data3 = [7,8,4,5,8,2]
data4 = [6,9,3,6,8,4]

# --- Combining your data:
data_group1 = [data1, data2]
data_group2 = [data3, data4]

# --- Labels for your data:
labels_list = ['a','b']
xlocations  = range(len(data_group1))
width       = 0.3
symbol      = 'r+'
ymin        = 0
ymax        = 10

ax = plt.gca()
ax.set_ylim(ymin,ymax)
ax.set_xticklabels( labels_list, rotation=0 )
ax.grid(True, linestyle='dotted')
ax.set_axisbelow(True)
ax.set_xticks(xlocations)
plt.xlabel('X axis label')
plt.ylabel('Y axis label')
plt.title('title')

# --- Offset the positions per group:
positions_group1 = [x-(width+0.01) for x in xlocations]
positions_group2 = xlocations

plt.boxplot(data_group1, 
            sym=symbol,
            labels=['']*len(labels_list),
            positions=positions_group1, 
            widths=width, 
#           notch=False,  
#           vert=True, 
#           whis=1.5,
#           bootstrap=None, 
#           usermedians=None, 
#           conf_intervals=None,
#           patch_artist=False,
            )

plt.boxplot(data_group2, 
            labels=labels_list,
            sym=symbol,
            positions=positions_group2, 
            widths=width, 
#           notch=False,  
#           vert=True, 
#           whis=1.5,
#           bootstrap=None, 
#           usermedians=None, 
#           conf_intervals=None,
#           patch_artist=False,
            )

plt.savefig('boxplot_grouped.png')  
plt.savefig('boxplot_grouped.pdf')    # when publishing, use high quality PDFs
#plt.show()                   # uncomment to show the plot. 

How to know/change current directory in Python shell?

The easiest way to change the current working directory in python is using the 'os' package. Below there is an example for windows computer:

# Import the os package
import os

# Confirm the current working directory 
os.getcwd()

# Use '\\' while changing the directory 
os.chdir("C:\\user\\foldername")

How to get the input from the Tkinter Text Widget?

Here is how I did it with python 3.5.2:

from tkinter import *
root=Tk()
def retrieve_input():
    inputValue=textBox.get("1.0","end-1c")
    print(inputValue)

textBox=Text(root, height=2, width=10)
textBox.pack()
buttonCommit=Button(root, height=1, width=10, text="Commit", 
                    command=lambda: retrieve_input())
#command=lambda: retrieve_input() >>> just means do this when i press the button
buttonCommit.pack()

mainloop()

with that, when i typed "blah blah" in the text widget and pressed the button, whatever i typed got printed out. So i think that is the answer for storing user input from Text widget to variable.

Full Screen Theme for AppCompat

Your "workaround" (hiding the actionBar yourself) is the normal way. But google recommands to always hide the ActionBar when the TitleBar is hidden. Have a look here: https://developer.android.com/training/system-ui/status.html

Find UNC path of a network drive?

If you have Microsoft Office:

  1. RIGHT-drag the drive, folder or file from Windows Explorer into the body of a Word document or Outlook email
  2. Select 'Create Hyperlink Here'

The inserted text will be the full UNC of the dragged item.

How to interpret "loss" and "accuracy" for a machine learning model

The lower the loss, the better a model (unless the model has over-fitted to the training data). The loss is calculated on training and validation and its interperation is how well the model is doing for these two sets. Unlike accuracy, loss is not a percentage. It is a summation of the errors made for each example in training or validation sets.

In the case of neural networks, the loss is usually negative log-likelihood and residual sum of squares for classification and regression respectively. Then naturally, the main objective in a learning model is to reduce (minimize) the loss function's value with respect to the model's parameters by changing the weight vector values through different optimization methods, such as backpropagation in neural networks.

Loss value implies how well or poorly a certain model behaves after each iteration of optimization. Ideally, one would expect the reduction of loss after each, or several, iteration(s).

The accuracy of a model is usually determined after the model parameters are learned and fixed and no learning is taking place. Then the test samples are fed to the model and the number of mistakes (zero-one loss) the model makes are recorded, after comparison to the true targets. Then the percentage of misclassification is calculated.

For example, if the number of test samples is 1000 and model classifies 952 of those correctly, then the model's accuracy is 95.2%.

enter image description here

There are also some subtleties while reducing the loss value. For instance, you may run into the problem of over-fitting in which the model "memorizes" the training examples and becomes kind of ineffective for the test set. Over-fitting also occurs in cases where you do not employ a regularization, you have a very complex model (the number of free parameters W is large) or the number of data points N is very low.

Difference between object and class in Scala

The object keyword creates a new singleton type, which is like a class that only has a single named instance. If you’re familiar with Java, declaring an object in Scala is a lot like creating a new instance of an anonymous class.

Scala has no equivalent to Java’s static keyword, and an object is often used in Scala where you might use a class with static members in Java.

Display QImage with QtGui

Simple, but complete example showing how to display QImage might look like this:

#include <QtGui/QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QImage myImage;
    myImage.load("test.png");

    QLabel myLabel;
    myLabel.setPixmap(QPixmap::fromImage(myImage));

    myLabel.show();

    return a.exec();
}

react-native: command not found

Install react-native globally by using the following command

npm i -g react-native-cli