Programs & Examples On #Collect

Difference between map and collect in Ruby?

I did a benchmark test to try and answer this question, then found this post so here are my findings (which differ slightly from the other answers)

Here is the benchmark code:

require 'benchmark'

h = { abc: 'hello', 'another_key' => 123, 4567 => 'third' }
a = 1..10
many = 500_000 do |b|
  GC.start"hash keys collect") do
    many.times do

  GC.start"hash keys map") do
    many.times do

  GC.start"array collect") do
    many.times do

  GC.start"array map") do
    many.times do

And the results I got were:

                   user     system      total        real
hash keys collect  0.540000   0.000000   0.540000 (  0.570994)
hash keys map      0.500000   0.010000   0.510000 (  0.517126)
array collect      1.670000   0.020000   1.690000 (  1.731233)
array map          1.680000   0.020000   1.700000 (  1.744398) 

Perhaps an alias isn't free?

Check date with todays date

Does this help?

Calendar c = Calendar.getInstance();

// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);

// and get that as a Date
Date today = c.getTime();

// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();

// user-specified date which you are testing
// let's say the components come from a form or something
int year = 2011;
int month = 5;
int dayOfMonth = 20;

// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

// and get that as a Date
Date dateSpecified = c.getTime();

// test your condition
if (dateSpecified.before(today)) {
  System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
} else {
  System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");

how to make a whole row in a table clickable as a link?

This code bellow will make your whole table clickable. Clicking the links in this example will show the link in an alert dialog instead of following the link.


Here's the HTML behind the above example:

    <table id="example">
     <td><a href="apples">Edit</a></td>
     <td>Blah blah blah blah</td>
     <td><a href="bananas">Edit</a></td>
     <td>Blah blah blah blah</td>
     <td><a href="oranges">Edit</a></td>
     <td>Blah blah blah blah</td>


And the CSS:

    table#example {
    border-collapse: collapse;   
#example tr {
    background-color: #eee;
    border-top: 1px solid #fff;
#example tr:hover {
    background-color: #ccc;
#example th {
    background-color: #fff;
#example th, #example td {
    padding: 3px 5px;
#example td:hover {
    cursor: pointer;

The jQuery

And finally the jQuery which makes the magic happen:

    $(document).ready(function() {

    $('#example tr').click(function() {
        var href = $(this).find("a").attr("href");
        if(href) {
            window.location = href;


What it does is when a row is clicked, a search is done for the href belonging to an anchor. If one is found, the window's location is set to that href.

Angular cli generate a service and include the provider in one step

In Command prompt go to project folder and execute following:

ng g s servicename

Check folder size in Bash

Use a summary (-s) and bytes (-b). You can cut the first field of the summary with cut. Putting it all together:

CHECK=$(du -sb /data/sflow_log | cut -f1)

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

After facing a similar issue, below is what I did :

  • Created a class extending and added a Cors Filter to it.

To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");.

Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*" instead of any specific URL to allow any URL.

public class RestApplication
    extends Application
    private Set<Object> singletons = new HashSet<Object>();

    public MessageApplication()
        singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
        CorsFilter corsFilter = new CorsFilter();
        // To allow all origins for CORS add following, otherwise add only specific urls.
        // corsFilter.getAllowedOrigins().add("*");
        System.out.println("To only allow restrcited urls ");
        singletons = new LinkedHashSet<Object>();

    public Set<Object> getSingletons()
        return singletons;
  • And here is my web.xml:
<web-app id="WebApp_ID" version="2.4"
    <display-name>Restful Web Application</display-name>

    <!-- Auto scan rest service -->






The most important code which I was missing when I was getting this issue was, I was not adding my class extending i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>


And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.

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


select to_char(date_column,'YYYY-MM-DD') from table;

How to store an array into mysql?

You can always serialize the array and store that in the database.
PHP Serialize

You can then unserialize the array when needed.

Sublime Text 2 Code Formatting

A similar option in Sublime Text is the built in Edit->Line->Reindent. You can put this code in Preferences -> Key Bindings User:

{ "keys": ["alt+shift+f"], "command": "reindent"} 

I use alt+shift+f because I'm a Netbeans user.

To format your code, select all by pressing ctrl+a and "your key combination". Excuse me for my bad english.

Or if you don't want to select all before formatting, add an argument to the command instead:

{ "keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false} }

(as per comment by @Supr below)

Read XML Attribute using XmlDocument

You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.

Then the code would be something similar to

string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;

Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Yep, confirmed that simply using hh instead of HH fixed my issue.

Changed from this:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm aa");

To this:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

You can still use HH to store the time if you don't want to bother storing and dealing with the AM/PM. Then when you retrieve it, use hh.

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

For Chrome users, I recommend Stylebot, which will let you override any CSS on any page, also let you search and install other share custom CSS. However, for our purpose we don't need any advance theme. Open Stylebot, change to Edit CSS. Jupyter captures some keystrokes, so you will not be able to type the code below in. Just copy and paste, or just your editor:

#notebook-container.container {
    width: 90%;

Change the width as you like, I find 90% looks nicer than 100%. But it is totally up to your eye.

What is the functionality of setSoTimeout and how it works?

Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?

No, it means that if no data arrives within 2000ms a SocketTimeoutException will be thrown.

What does it mean timeout expire?

It means the 2000ms (in your case) elapses without any data arriving.

What is the option which must be enabled prior to blocking operation?

There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.

Infinite Timeout menas that the socket does't read anymore?

What a strange suggestion. It means that if no data ever arrives you will block in the read forever.

How to Validate Google reCaptcha on Form Submit

Verify Google reCapcha is valid or not after form submit

if ($post['g-recaptcha-response']) {
      $captcha = $post['g-recaptcha-response'];
      $secretKey = 'type here private key';
      $response = file_get_contents("" . $secretKey . "&response=" . $captcha);
        $responseKeys = json_decode($response, true);
        if (intval($responseKeys["success"]) !== 1) {
            return "failed";
        } else {
            return "success";
    else {
        return "failed";

File tree view in Notepad++

Tree like structure in Notepad++ without plugin

Download Notepad++ 6.8.8 & then follow step below :

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

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

This is it. Enjoy

Python: avoiding pylint warnings about too many arguments

Perhaps you could turn some of the arguments into member variables. If you need that much state a class sounds like a good idea to me.

Set output of a command as a variable (with pipes)

I find myself a tad amazed at the lack of what I consider the best answer to this question anywhere on the internet. I struggled for many years to find the answer. Many answers online come close, but none really answer it. The real answer is

(cmd & echo.) >2 & (set /p =)<2

The "secret sauce" being the "closely guarded coveted secret" that "echo." sends a CR/LF (ENTER/new line/0x0D0A). Otherwise, what I am doing here is redirecting the output of the first command to the standard error stream. I then redirect the standard error stream into the standard input stream for the "set /p =" command.


(echo foo & echo.) >2 & (set /p bar=)<2

JavaScript .replace only replaces first Match

For that you neet to use the g flag of regex.... Like this :

var new_string=old_string.replace( / (regex) /g,  replacement_text);

That sh

Best way to store time (hh:mm) in a database

Store the ticks as a long/bigint, which are currently measured in milliseconds. The updated value can be found by looking at the TimeSpan.TicksPerSecond value.

Most databases have a DateTime type that automatically stores the time as ticks behind the scenes, but in the case of some databases e.g. SqlLite, storing ticks can be a way to store the date.

Most languages allow the easy conversion from Ticks ? TimeSpan ? Ticks.


In C# the code would be:

long TimeAsTicks = TimeAsTimeSpan.Ticks;

TimeAsTimeSpan = TimeSpan.FromTicks(TimeAsTicks);

Be aware though, because in the case of SqlLite, which only offers a small number of different types, which are; INT, REAL and VARCHAR It will be necessary to store the number of ticks as a string or two INT cells combined. This is, because an INT is a 32bit signed number whereas BIGINT is a 64bit signed number.


My personal preference however, would be to store the date and time as an ISO8601 string.

Git ignore file for Xcode projects

The people of GitHub have exhaustive and documented .gitignore files for Xcode projects:



How to pass 2D array (matrix) in a function in C?

C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:

1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports VLA's:

#define ROWS 4
#define COLS 5

void func(int array[ROWS][COLS])
  int i, j;

  for (i=0; i<ROWS; i++)
    for (j=0; j<COLS; j++)
      array[i][j] = i*j;

void func_vla(int rows, int cols, int array[rows][cols])
  int i, j;

  for (i=0; i<rows; i++)
    for (j=0; j<cols; j++)
      array[i][j] = i*j;

int main()
  int x[ROWS][COLS];

  func_vla(ROWS, COLS, x);

2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.

void func(int** array, int rows, int cols)
  int i, j;

  for (i=0; i<rows; i++)
    for (j=0; j<cols; j++)
      array[i][j] = i*j;

int main()
  int rows, cols, i;
  int **x;

  /* obtain values for rows & cols */

  /* allocate the array */
  x = malloc(rows * sizeof *x);
  for (i=0; i<rows; i++)
    x[i] = malloc(cols * sizeof *x[i]);

  /* use the array */
  func(x, rows, cols);

  /* deallocate the array */
  for (i=0; i<rows; i++)

3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays:

void func(int* array, int rows, int cols)
  int i, j;

  for (i=0; i<rows; i++)
    for (j=0; j<cols; j++)

int main()
  int rows, cols;
  int *x;

  /* obtain values for rows & cols */

  /* allocate the array */
  x = malloc(rows * cols * sizeof *x);

  /* use the array */
  func(x, rows, cols);

  /* deallocate the array */

4) Use a dynamically allocated VLA. One advantage of this over option 2 is that there is a single memory allocation; another is that less memory is needed because the array of pointers is not required.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

extern void func_vla(int rows, int cols, int array[rows][cols]);
extern void get_rows_cols(int *rows, int *cols);
extern void dump_array(const char *tag, int rows, int cols, int array[rows][cols]);

void func_vla(int rows, int cols, int array[rows][cols])
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            array[i][j] = (i + 1) * (j + 1);

int main(void)
    int rows, cols;

    get_rows_cols(&rows, &cols);

    int (*array)[cols] = malloc(rows * cols * sizeof(array[0][0]));
    /* error check omitted */

    func_vla(rows, cols, array);
    dump_array("After initialization", rows, cols, array);

    return 0;

void dump_array(const char *tag, int rows, int cols, int array[rows][cols])
    printf("%s (%dx%d):\n", tag, rows, cols);
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            printf("%4d", array[i][j]);

void get_rows_cols(int *rows, int *cols)
    srand(time(0));           // Only acceptable because it is called once
    *rows = 5 + rand() % 10;
    *cols = 3 + rand() % 12;

(See srand() — why call it only once?.)

What are "named tuples" in Python?

namedtuples are a great feature, they are perfect container for data. When you have to "store" data you would use tuples or dictionaries, like:

user = dict(name="John", age=20)


user = ("John", 20)

The dictionary approach is overwhelming, since dict are mutable and slower than tuples. On the other hand, the tuples are immutable and lightweight but lack readability for a great number of entries in the data fields.

namedtuples are the perfect compromise for the two approaches, the have great readability, lightweightness and immutability (plus they are polymorphic!).

An object reference is required to access a non-static member

You should make your audioSounds and minTime members static:

public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

But I would consider using singleton objects instead of static members instead:

public class SoundManager : MonoBehaviour

    public List<AudioSource> audioSounds = new List<AudioSource>();
    public double minTime = 0.5;

    public static SoundManager Instance { get; private set; }

    void Awake()
        Instance = this;

    public void playSound(AudioClip sourceSound, Vector3 objectPosition, int volume, float audioPitch, int dopplerLevel)
        bool playsound = false;
        foreach (AudioSource sound in audioSounds) // Loop through List with foreach
            if ( != && sound.time <= minTime)
                playsound = true;

        if(playsound) {
            AudioSource.PlayClipAtPoint(sourceSound, objectPosition);


Update from September 2020:

Six years later, it is still one of my most upvoted answers on StackOverflow, so I feel obligated to add: singleton is a pattern that creates a lot of problems down the road, and personally, I consider it to be an anti-pattern. It can be accessed from anywhere, and using singletons for different game systems creates a spaghetti of invisible dependencies between different parts of your project.

If you're just learning to program, using singletons is OK for now. But please, consider reading about Dependency Injection, Inversion of Control and other architectural patterns. At least file it under "stuff I will learn later". This may sound as an overkill when you first learn about them, but a proper architecture can become a life-saver on middle and big projects.

How to count lines in a document?

cat file.log | wc -l | grep -oE '\d+'
  • grep -oE '\d+': In order to return the digit numbers ONLY.

String.Format like functionality in T-SQL?

here's what I found with my experiments using the built-in


sp_addmessage @msgnum=50001,@severity=1,@msgText='Hello %s you are #%d',@replace='replace'
SELECT FORMATMESSAGE(50001, 'Table1', 5)

when you call up sp_addmessage, your message template gets stored into the system table master.dbo.sysmessages (verified on SQLServer 2000).

You must manage addition and removal of template strings from the table yourself, which is awkward if all you really want is output a quick message to the results screen.

The solution provided by Kathik DV, looks interesting but doesn't work with SQL Server 2000, so i altered it a bit, and this version should work with all versions of SQL Server:

IF OBJECT_ID( N'[dbo].[FormatString]', 'FN' ) IS NOT NULL
    DROP FUNCTION [dbo].[FormatString]
Object Name : FormatString
Purpose : Returns the formatted string.
Original Author : Karthik D V
Sample Call:
SELECT dbo.FormatString ( N'Format {0} {1} {2} {0}', N'1,2,3' )
CREATE FUNCTION [dbo].[FormatString](
@Format NVARCHAR(4000) ,
@Parameters NVARCHAR(4000)
    --DECLARE @Format NVARCHAR(4000), @Parameters NVARCHAR(4000) select @format='{0}{1}', @Parameters='hello,world'
    DECLARE @Message NVARCHAR(400), @Delimiter CHAR(1)
    DECLARE @ParamTable TABLE ( ID INT IDENTITY(0,1), Parameter VARCHAR(1000) )
    Declare @startPos int, @endPos int
    SELECT @Message = @Format, @Delimiter = ','

    --handle first parameter
     set @endPos=CHARINDEX(@Delimiter,@Parameters)
    if (@endPos=0 and @Parameters is not null) --there is only one parameter
        insert into @ParamTable (Parameter) values(@Parameters)
    else begin
        insert into @ParamTable (Parameter) select substring(@Parameters,0,@endPos)

    while @endPos>0
        --insert a row for each parameter in the 
        set @startPos = @endPos + LEN(@Delimiter)
        set @endPos = CHARINDEX(@Delimiter,@Parameters, @startPos)
        if (@endPos>0)
            insert into @ParamTable (Parameter) select substring(@Parameters,@startPos,@endPos)
            insert into @ParamTable (Parameter) select substring(@Parameters,@startPos,4000)            

    UPDATE @ParamTable SET @Message = REPLACE ( @Message, '{'+CONVERT(VARCHAR,ID) + '}', Parameter )
    RETURN @Message
    grant execute,references on dbo.formatString to public


print dbo.formatString('hello {0}... you are {1}','world,good')
--result: hello world... you are good

How to set a DateTime variable in SQL Server 2008?

First of all - use single quotes around your date literals!

Second of all, I would strongly recommend always using the ISO-8601 date format - this works regardless of what your locale, regional or language settings are on your SQL Server.

The ISO-8601 format is either:

  • YYYYMMDD for dates only (e.g. 20110825 for the 25th of August, 2011)
  • YYYY-MM-DDTHH:MM:SS for dates and time (e.g. 2011-08-25T14:15:00 for 25th of AUgust, 14:15/2:15pm in the afternoon)

configure: error: C compiler cannot create executables

I just had this issue building react-native app when I try to install Pod. I had to export 2 variables:

export CC=/Applications/
CPP='/Applications/ -E'

How do I run a bat file in the background from another bat file?

Since START is the only way to execute something in the background from a CMD script, I would recommend you keep using it. Instead of the /B modifier, try /MIN so the newly created window won't bother you. Also, you can set the priority to something lower with /LOW or /BELOWNORMAL, which should improve your system responsiveness.

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

On Salesforce platform this error is caused by /, the solution is to escape these as //.

Cordova - Error code 1 for command | Command failed for

I removed android platforms and installed again then worked. I wrote these lines in command window:

cordova platform remove android
cordova platform add android

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

I use this script on sql server 2008 R2.

USE [db_name]


DBCC SHRINKFILE([log_file_name]/log_file_number, wanted_size)


How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...

How to create EditText with cross(x) button at end of it?

Android's support libarary has a SearchView class that does exactly this. (Not derrived from EditText though, so have to use a SearchView.OnQueryTextListener instead of a TextWatcher)

Search view with no text (and hint text "Search")

enter image description here

Use in XML like so:

            app:queryHint="@string/SearchHint" />

Passing in class names to react components

You can achieve this by "interpolating" the className passed from the parent component to the child component using this.props.className. Example below:

export default class ParentComponent extends React.Component {
    return <ChildComponent className="your-modifier-class" />

export default class ChildComponent extends React.Component {
    return <div className={"original-class " + this.props.className}></div>

Cannot create Maven Project in eclipse

It's actually easy and straight forward.

just navigate to your .m2 folder.


inside this maven folder, you will see a folder called Archetypes... delete this folder and the problem is solved.

but if you don't feel like deleting the whole folder, you can navigate into the archetype folder and delete all the archetype you want there. The reason why it keeps failing is because, the archetype you are trying to create is trying to tell you that she already exists in that folder, hence move away...

summarily, deleting the archetype folder in the .m2 folder is the easiest solution.

How to programmatically modify WCF app.config endpoint address setting?

MyServiceClient client = new MyServiceClient(binding, endpoint);
client.Endpoint.Address = new EndpointAddress("net.tcp://localhost/webSrvHost/service.svc");
client.Endpoint.Binding = new NetTcpBinding()
                Name = "yourTcpBindConfig",
                ReaderQuotas = XmlDictionaryReaderQuotas.Max,
                ListenBacklog = 40 }

It's very easy to modify the uri in config or binding info in config. Is this what you want?

How to tell if JRE or JDK is installed

according to JAVA documentation, the JDK should be installed in this path:


See the uninstall JDK part at

So if you can find such folder then the JDK is installed

No generated file in my project

I Had a similar problem

Best way to Identify this problem is to identify Lint warnings:: *Right Click on project > Android Tools > Run Lint : Common Errors*

  • That helps us to show some errors through which we can fix things which make regenerated once again
  • By following above steps i identified that i had added some image files that i have not used -> I removed them -> That fixed the problem !

Finally Clean the project !

How do I declare and use variables in PL/SQL like I do in T-SQL?

In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:

  myname varchar2(20) := 'tom';
  for result_cursor in (select * from mytable where first_name = myname) loop
  end loop;

If you have a query that returns exactly one row, then you can use the select...into... syntax, e.g.:

  myname varchar2(20);
  select first_name into myname 
    from mytable 
    where person_id = 123;

Get individual query parameters from Uri

You could reference System.Web in your console application and then look for the Utility functions that split the URL parameters.

Lightweight XML Viewer that can handle large files

I like Microsoft's XML Notepad 2007, but I don't know how it handles very large files, sorry.

How do I close a single buffer (out of many) in Vim?

How about

vim -O a a

That way you can edit a single file on your left and navigate the whole dir on your right... Just a thought, not the solution...

What is :: (double colon) in Python when subscripting sequences?

it means 'nothing for the first argument, nothing for the second, and jump by three'. It gets every third item of the sequence sliced. Extended slices is what you want. New in Python 2.3

System.Collections.Generic.List does not contain a definition for 'Select'

This question's bit old, but, there's a tricky scenario which also leads to this error:

In controller: = //id from querystring
List<string> = GrabDataFromDBByID(>a.ToString());

The above code will lead to an error in this part: .Select(a=>a.ToString()) because of the below reason: You're passing a to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:


So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.

Dump a mysql database to a plaintext (CSV) backup from the command line

If you really need a "Backup" then you also need database schema, like table definitions, view definitions, store procedures and so on. A backup of a database isn't just the data.

The value of the mysqldump format for backup is specifically that it is very EASY to use it to restore mysql databases. A backup that isn't easily restored is far less useful. If you are looking for a method to reliably backup mysql data to so you can restore to a mysql server then I think you should stick with the mysqldump tool.

Mysql is free and runs on many different platforms. Setting up a new mysql server that I can restore to is simple. I am not at all worried about not being able to setup mysql so I can do a restore.

I would be far more worried about a custom backup/restore based on a fragile format like csv/tsv failing. Are you sure that all your quotes, commas, or tabs that are in your data would get escaped correctly and then parsed correctly by your restore tool?

If you are looking for a method to extract the data then see several in the other answers.

Disabled UIButton not faded or grey

#import "UIButton+My.h"
#import <QuartzCore/QuartzCore.h>
@implementation UIButton (My)

-(void)fade :(BOOL)enable{



#import <UIKit/UIKit.h>
@interface UIButton (My)

-(void)fade :(BOOL)enable;


How to Remove the last char of String in C#?

var input = "12342";
var output = input.Substring(0, input.Length - 1); 


var output = input.Remove(input.Length - 1);

Binning column with python pandas

Using numba module for speed up.

On big datasets (500k >) pd.cut can be quite slow for binning data.

I wrote my own function in numba with just in time compilation, which is roughly 16x faster:

from numba import njit

def cut(arr):
    bins = np.empty(arr.shape[0])
    for idx, x in enumerate(arr):
        if (x >= 0) & (x < 1):
            bins[idx] = 1
        elif (x >= 1) & (x < 5):
            bins[idx] = 2
        elif (x >= 5) & (x < 10):
            bins[idx] = 3
        elif (x >= 10) & (x < 25):
            bins[idx] = 4
        elif (x >= 25) & (x < 50):
            bins[idx] = 5
        elif (x >= 50) & (x < 100):
            bins[idx] = 6
            bins[idx] = 7

    return bins

# array([5., 5., 7., 5.])

Optional: you can also map it to bins as strings:

a = cut(df['percentage'].to_numpy())

conversion_dict = {1: 'bin1',
                   2: 'bin2',
                   3: 'bin3',
                   4: 'bin4',
                   5: 'bin5',
                   6: 'bin6',
                   7: 'bin7'}

bins = list(map(conversion_dict.get, a))

# ['bin5', 'bin5', 'bin7', 'bin5']

Speed comparison:

# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)


# (8000000, 1)

# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)

# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Delete with "Join" in Oracle sql Query

Use a subquery in the where clause. For a delete query requirig a join, this example will delete rows that are unmatched in the joined table "docx_document" and that have a create date > 120 days in the "docs_documents" table.

delete from docs_documents d
where in (
    select from docs_documents a
    left join docx_document b on = a.document_id
    where is null
        and floor(sysdate - a.create_date) > 120

How to git ignore subfolders / subdirectories?

The only way I got this to work on my machine was to do it this way:

# Ignore all directories, and all sub-directories, and it's contents:

#Now ignore all files in the current directory 
#(This fails to ignore files without a ".", for example 
#'file.txt' works, but 
#'file' doesn't):

#Only Include these specific directories and subdirectories:

Notice how you have to explicitly allow content for each level you want to include. So if I have subdirectories 5 deep under themes, I still need to spell that out.

This is from @Yarin's comment here:

These were useful topics:

I also tried


and **/wp-content/themes/**

or /wp-content/themes/**/*

None of that worked for me, either. Lots of trail and error!

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

The moral of this strangeness is:

  • Use dates and times in UTC wherever possible.
  • If you can not display a date or time in UTC, always indicate the time-zone.
  • If you can not require an input date/time in UTC, require an explicitly indicated time-zone.

Search and replace part of string in database

I would consider writing a CLR replace function with RegEx support for this kind of string manipulation.

WCF Service , how to increase the timeout?

Got the same error recently but was able to fixed it by ensuring to close every wcf client call. eg.

WCFServiceClient client = new WCFServiceClient ();
//More codes here
// Always close the client.


using(WCFServiceClient client = new WCFServiceClient ())
    //More codes here 

How to select all instances of a variable and edit variable name in Sublime

I know the question is about Macs, but I got here searching the answer for Ubuntu, so I guess my answer could be useful to someone.

Easy way to do it: AltF3.

Is there a method for String conversion to Title Case?

If I may submit my take on the solution...

The following method is based on the one that dfa posted. It makes the following major change (which is suited to the solution I needed at the time): it forces all characters in the input string into lower case unless it is immediately preceded by an "actionable delimiter" in which case the character is coerced into upper case.

A major limitation of my routine is that it makes the assumption that "title case" is uniformly defined for all locales and is represented by the same case conventions I have used and so it is less useful than dfa's code in that respect.

public static String toDisplayCase(String s) {

    final String ACTIONABLE_DELIMITERS = " '-/"; // these cause the character following
                                                 // to be capitalized
    StringBuilder sb = new StringBuilder();
    boolean capNext = true;

    for (char c : s.toCharArray()) {
        c = (capNext)
                ? Character.toUpperCase(c)
                : Character.toLowerCase(c);
        capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
    return sb.toString();


a string

maRTin o'maLLEY

john wilkes-booth



A String

Martin O'Malley

John Wilkes-Booth

Yet Another String

Makefile If-Then Else and Loops

Have you tried the GNU make documentation? It has a whole section about conditionals with examples.

Yes/No message box using QMessageBox

QMessageBox includes static methods to quickly ask such questions:

#include <QApplication>
#include <QMessageBox>

int main(int argc, char **argv)
    QApplication app{argc, argv};
    while (QMessageBox::question(nullptr,
                                 qApp->translate("my_app", "Test"),
                                 qApp->translate("my_app", "Are you sure you want to quit?"),
           != QMessageBox::Yes)
        // ask again

If your needs are more complex than provided for by the static methods, you should construct a new QMessageBox object, and call its exec() method to show it in its own event loop and obtain the pressed button identifier. For example, we might want to make "No" be the default answer:

#include <QApplication>
#include <QMessageBox>

int main(int argc, char **argv)
    QApplication app{argc, argv};
    auto question = new QMessageBox(QMessageBox::Question,
                                    qApp->translate("my_app", "Test"),
                                    qApp->translate("my_app", "Are you sure you want to quit?"),

    while (question->exec() != QMessageBox::Yes)
        // ask again

MySQL Workbench Edit Table Data is read only

This is the Known limitation in MySQLWorkbench (you can't edit table w/o PK):

To Edit the Table:

Method 1: (method not working in somecases)
right-click on a table within the Object Browser and choose the Edit Table Data option from there.

Method 2:
I would rather suggest you to add Primary Key Instead:

ALTER TABLE `your_table_name` ADD PRIMARY KEY (`column_name`);

and you might want to remove the existing rows first:

Truncate table your_table_name

'^M' character at end of lines

od -a $file is useful to explore those types of question on Linux (similar to dumphex in the above).

Loop through JSON in EJS

in my case, datas is an objects of Array for more information please Click Here

<% for(let [index,data] of datas.entries() || []){  %>
 Index : <%=index%>
 Data : <%=data%>
<%} %>

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

A very simple solution is to add the database name with your table name like if your DB name is DBMS and table is info then it will be for any query.

If your query is

select * from STUDENTREC where ROLL_NO=1;

it might show an error but

select * from DBMS.STUDENTREC where ROLL_NO=1; 

it doesn't because now actually your table is found.

How to edit my Excel dropdown list?

Attribute_Brands is a named range.

On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.

This will take you to the named range.

The data in it can be updated by typing new values into the cells.

The named range can be altered via the 'Insert - Name - Define' menu.

C# "No suitable method found to override." -- but there is one

Make sure that you have the child class explicitly inherit the parent class:

public class Ext : Base { // stuff }

Regex matching beginning AND end strings

Well, the simple regex is this:


It would be better, however, to use the string manipulation functionality of whatever programming language you're using to slice off the first four and the last three characters of the string and check whether they're what you want.

Is there a difference between "==" and "is"?

is tests for identity == tests for equality

Each (small) integer value is mapped to a single value, so every 3 is identical and equal. This is an implementation detail, not part of the language spec though

What is the effect of encoding an image in base64?

Encoding an image to base64 will make it about 30% bigger.

See the details in the wikipedia article about the Data URI scheme, where it states:

Base64-encoded data URIs are 1/3 larger in size than their binary equivalent. (However, this overhead is reduced to 2-3% if the HTTP server compresses the response using gzip)

Select where count of one field is greater than one

You can also do this with a self-join:

SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND !=

Concatenating variables and strings in React

the best way to concat props/variables:

var sample = "test";    
var result = `this is just a ${sample}`;    
//this is just a test

tomcat - CATALINA_BASE and CATALINA_HOME variables

Pointing CATALINA_BASE to a different directory from CATALINA_HOME allows you to separate the configuration directory from the binaries directory.

By default, CATALINA_BASE (configurations) and CATALINA_HOME (binaries) point to the same folder, but separating the configurations from the binaries can help you to run multiple instances of Tomcat side by side without duplicating the binaries.

It is also useful when you want to update the binaries, without modifying, or needing to backup/restore your configuration files for Tomcat.

Update 2018

There is an easier way to set CATALINA_BASE now with the makebase utility. I have posted a tutorial that covers this subject at along with a video tutorial at

Original answer continued below

To take advantage of this feature, simply create the config directory and point to it with the CATALINA_BASE environment variable. You will have to put some files in that directory:

  • Copy the conf directory from the original Tomcat installation directory, including its contents, and ensure that Tomcat has read permissions to it. Edit the configuration files according to your needs.
  • Create a logs directory if conf/ points to ${catalina.base}/logs, and ensure that Tomcat has read/write permissions to it.
  • Create a temp directory if you are not overriding the default of $CATALINA_TMPDIR which points to ${CATALINA_BASE}/temp, and ensure that Tomcat has write permissions to it.
  • Create a work directory which defaults to ${CATALINA_BASE}/work, and ensure that Tomcat has write permissions to it.

How to pass event as argument to an inline event handler in JavaScript?

You don't need to pass this, there already is the event object passed by default automatically, which contains which has the object it's coming from. You can lighten your syntax:


<p onclick="doSomething()">

Will work with this:

function doSomething(){

You don't need to instantiate the event object, it's already there. Try it out. And will contain the entire object calling it, which you were referencing as "this" before.

Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent:

document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));

Then doSomething() will see event and as per usual!

No need to pass this everywhere, and you can keep your function signatures free from wiring information and simplify things.

How to set focus on input field?

##(EDIT: I've added an updated solution below this explanation)

Mark Rajcok is the man... and his answer is a valid answer, but it has had a defect (sorry Mark)...

...Try using the boolean to focus on the input, then blur the input, then try using it to focus the input again. It won't work unless you reset the boolean to false, then $digest, then reset it back to true. Even if you use a string comparison in your expression, you'll be forced to change the string to something else, $digest, then change it back. (This has been addressed with the blur event handler.)

So I propose this alternate solution:

Use an event, the forgotten feature of Angular.

JavaScript loves events after all. Events are inherently loosely coupled, and even better, you avoid adding another $watch to your $digest.

app.directive('focusOn', function() {
   return function(scope, elem, attr) {
      scope.$on(attr.focusOn, function(e) {

So now you could use it like this:

<input type="text" focus-on="newItemAdded" />

and then anywhere in your app...

$scope.addNewItem = function () {
    /* stuff here to add a new item... */


This is awesome because you can do all sorts of things with something like this. For one, you could tie into events that already exist. For another thing you start doing something smart by having different parts of your app publish events that other parts of your app can subscribe to.

Anyhow, this type of thing screams "event driven" to me. I think as Angular developers we try really hard to hammer $scope shaped pegs into event shape holes.

Is it the best solution? I don't know. It is a solution.

Updated Solution

After @ShimonRachlenko's comment below, I've changed my method of doing this slightly. Now I use a combination of a service and a directive that handles an event "behind the scenes":

Other than that, it's the same principal outlined above.

Here is a quick demo Plunk


<input type="text" focus-on="focusMe"/>
app.controller('MyCtrl', function($scope, focus) {


app.directive('focusOn', function() {
   return function(scope, elem, attr) {
      scope.$on('focusOn', function(e, name) {
        if(name === attr.focusOn) {

app.factory('focus', function ($rootScope, $timeout) {
  return function(name) {
    $timeout(function (){
      $rootScope.$broadcast('focusOn', name);

Arithmetic operation resulted in an overflow. (Adding integers)

2055786000 + 93552000 = 2149338000, which is greater than 2^31. So if you're using signed integers coded on 4 bytes, the result of the operation doesn't fit and you get an overflow exception.

What is the meaning of the word logits in TensorFlow?

Logits often are the values of Z function of the output layer in Tensorflow.

Javascript loop through object array?

To reference the contents of the single array containing one or more objects i.e. everything in the brackets of something like this {messages: [{"a":1,"b":2}] } ,just add [0] to the query to get the first array element

e.g. messages[0] will reference the object {"a":1,"b":2} as opposed to just messages which would reference the entire array [{"a":1,"b":2}]

from there you can work with the result as typical object and use Object.keys for example to get "a" and "b".

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
      $ git checkout master           # back to master branch now
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
      # reset
      $ git reset --hard HEAD
      $ git checkout master
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
      # or, shortcut
      $ git checkout -      # back to the previous state

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

Thanks Friend, i got an answer. This is only possible because of your help. you all give me a ray of hope towards resolving this problem.

Here is the code:

package facebook;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Facebook {
    public static void main(String args[]){
        WebDriver driver = new FirefoxDriver();
        WebElement email= driver.findElement("email"));
        Actions builder = new Actions(driver);
        Actions seriesOfActions = builder.moveToElement(email).click().sendKeys(email, "[email protected]");
        WebElement pass = driver.findElement("pass"));
        WebElement login =driver.findElement("u_0_b"));
        Actions seriesOfAction = builder.moveToElement(pass).click().sendKeys(pass, "naveench").click(login);

Openssl is not recognized as an internal or external command

use this worked for me. please change your Path

C:\Program Files\Java\jre7\bin keytool -exportcert -alias androiddebugkey -keystore "C:\Users\\debug.keystore" | "C:\openssl\bin

\openssl.exe" sha1 -binary | "C:\openssl\bin\openssl.exe" base64

SQL Server Installation - What is the Installation Media Folder?

If you are using an executable,

  • just run the executable (for example: "en_sql_server_2012_express_edition_with_advanced_services_x64.exe")
  • Navigate to the "options" tab
  • Copy the "Installation Media Root Directory" (should look something like the below snipping)
  • Paste it into the open "Browse for SQL server Installation Media" window

enter image description here

Save yourself the hastle of renaming and unzipping etc.!

Increase number of axis ticks


ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = seq(min(dat$x), max(dat$x), by = 0.05))

Works for binned or discrete scaled x-axis data (I.e., rounding not necessary).

CSS Div width percentage and padding without breaking layout

You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.

An example:

width: calc((100%) - (32px))

Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.

.outer {_x000D_
  width: 200px;_x000D_
  height: 120px;_x000D_
  background-color: black;_x000D_
.inner {_x000D_
  height: 40px;_x000D_
  top: 30px;_x000D_
  position: relative;_x000D_
  padding: 16px;_x000D_
  background-color: teal;_x000D_
#inner-1 {_x000D_
  width: 100%;_x000D_
#inner-2 {_x000D_
  width: calc((100%) - (32px));_x000D_
<div class="outer" id="outer-1">_x000D_
  <div class="inner" id="inner-1"> width of 100% </div>_x000D_
<div class="outer" id="outer-2">_x000D_
  <div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_

Does hosts file exist on the iPhone? How to change it?

Not programming related, but I'll answer anyway. It's in /etc/hosts.

You can change it with a simple text editor such as nano.

(Obviously you would need a jailbroken iphone for this)

Converting String array to java.util.List

As of Java 8 and Stream API you can use and Collectors.toList:

String[] array = new String[]{"a", "b", "c"};
List<String> list =;

This is practical especially if you intend to perform further operations on the list.

String[] array = new String[]{"a", "bb", "ccc"};
List<String> list =
                          .filter(str -> str.length() > 1)
                          .map(str -> str + "!")

How do I get the project basepath in CodeIgniter

Obviously you mean the baseurl. If so:

base url: URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash.

Root in codeigniter specifically means that the position where you can append your controller to your url.

For example, if the root is localhost/ci_installation/index.php/, then to access the mycont controller you should go to localhost/ci_installation/index.php/mycont.

So, instead of writing such a long link you can (after loading "url" helper) , replace the term localhost/ci_installation/index.php/ by base_url() and this function will return the same string url.

NOTE: if you hadn't appended index.php/ to your base_url in your config.php, then if you use base_url(), it will return something like that localhost/ci_installation/mycont. And that will not work, because you have to access your controllers from index.php, instead of that you can place a .htaccess file to your codeigniter installation position. Cope that the below code to it:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /imguplod/index.php/$1 [L]

And it should work :)

How to Install Sublime Text 3 using Homebrew

$ brew tap caskroom/cask
$ brew install brew-cask
$ brew tap caskroom/versions
$ brew cask install sublime-text

Using jquery to get all checked checkboxes with a certain class name

If you need to get the value of all checked checkboxes as an array:

let myArray = (function() {
    let a = [];
    $(".checkboxes:checked").each(function() {
    return a;

Laravel Eloquent Sum of relation's column

I tried doing something similar, which took me a lot of time before I could figure out the collect() function. So you can have something this way:


This will give you the sum total of all the items.

How to correctly get image from 'Resources' folder in NetBeans

This was a pain, using netBeans IDE 7.2.

  1. You need to remember that Netbeans cleans up the Build folder whenever you rebuild, so
  2. Add a resource folder to the src folder:

    • (project)
      • src
        • project package folder (contains .java files)
        • resources (whatever name you want)
        • images (optional subfolders)
  3. After the clean/build this structure is propogated into the Build folder:

    • (project)
      • build
        • classes
          • project package folder (contains generated .class files)
          • resources (your resources)
          • images (your optional subfolders)

To access the resources:

dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));


if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {

worked for me. Note that in one case there is a leading "/" and in the other there isn't. So the root of the path to the resources is the "classes" folder within the build folder.

Double click on the executable jar file in the dist folder. The path to the resources still works.

Show/hide 'div' using JavaScript

Instead your both functions use toggle function with following body

this[target] = 'none'
this[source] = 'block'

function toggle(target, source) {
  this[target] = 'none'
  this[source] = 'block'
<button onClick="toggle('target', 'replace_target')">View Portfolio</button>
<button onClick="toggle('replace_target', 'target')">View Results</button>

  <span id="target">div1</span>

<div style="display:none">
  <span id="replace_target">div2</span>

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
render: function () {
  return <div>
        placeholder="Password (confirm)"
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
        <label className="error">Please enter the same password again.</label>
  return null;

React.js inline style best practices

The main purpose of the style attribute is for dynamic, state based styles. For example, you could have a width style on a progress bar based on some state, or the position or visibility based on something else.

Styles in JS impose the limitation that the application can't provide custom styling for a reusable component. This is perfectly acceptable in the aforementioned situations, but not when you change the visible characteristics, especially color.

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

Look at SignalR Tests for the feature.

Test "SendToUser" takes automatically the user identity passed by using a regular owin authentication library.

The scenario is you have a user who has connected from multiple devices/browsers and you want to push a message to all his active connections.

From io.Reader to string in Go


Since 1.10, strings.Builder exists. Example:

buf := new(strings.Builder)
n, err := io.Copy(buf, r)
// check errors


The short answer is that it it will not be efficient because converting to a string requires doing a complete copy of the byte array. Here is the proper (non-efficient) way to do what you want:

buf := new(bytes.Buffer)
s := buf.String() // Does a complete copy of the bytes in the buffer.

This copy is done as a protection mechanism. Strings are immutable. If you could convert a []byte to a string, you could change the contents of the string. However, go allows you to disable the type safety mechanisms using the unsafe package. Use the unsafe package at your own risk. Hopefully the name alone is a good enough warning. Here is how I would do it using unsafe:

buf := new(bytes.Buffer)
b := buf.Bytes()
s := *(*string)(unsafe.Pointer(&b))

There we go, you have now efficiently converted your byte array to a string. Really, all this does is trick the type system into calling it a string. There are a couple caveats to this method:

  1. There are no guarantees this will work in all go compilers. While this works with the plan-9 gc compiler, it relies on "implementation details" not mentioned in the official spec. You can not even guarantee that this will work on all architectures or not be changed in gc. In other words, this is a bad idea.
  2. That string is mutable! If you make any calls on that buffer it will change the string. Be very careful.

My advice is to stick to the official method. Doing a copy is not that expensive and it is not worth the evils of unsafe. If the string is too large to do a copy, you should not be making it into a string.

WPF: Grid with column/row margin/padding?

I did it right now with one of my grids.

  • First apply the same margin to every element inside the grid. You can do this mannualy, using styles, or whatever you like. Lets say you want an horizontal spacing of 6px and a vertical spacing of 2px. Then you add margins of "3px 1px" to every child of the grid.
  • Then remove the margins created around the grid (if you want to align the borders of the controls inside the grid to the same position of the grid). Do this setting a margin of "-3px -1px" to the grid. That way, other controls outside the grid will be aligned with the outtermost controls inside the grid.

Returning IEnumerable<T> vs. IQueryable<T>

Yes, both will give you deferred execution.

The difference is that IQueryable<T> is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable<T>, that query will be executed in the database, if possible.

For the IEnumerable<T> case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.

In code:

IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:

IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

This is quite an important difference, and working on IQueryable<T> can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take and Skip on IQueryable, you will only get the number of rows requested; doing that on an IEnumerable<T> will cause all of your rows to be loaded in memory.

Finding what branch a Git commit came from


Use the below if you care about shell exit statuses:

  • branch-current - the current branch's name
  • branch-names - clean branch names (one per line)
  • branch-name - Ensure that only one branch is returned from branch-names

Both branch-name and branch-names accept a commit as the argument, and default to HEAD if none is given.

Aliases useful in scripting

branch-current = "symbolic-ref --short HEAD"  #
branch-names = !"[ -z \"$1\" ] && git branch-current 2>/dev/null || git branch --format='%(refname:short)' --contains \"${1:-HEAD}\" #"  #
branch-name = !"br=$(git branch-names \"$1\") && case \"$br\" in *$'\\n'*) printf \"Multiple branches:\\n%s\" \"$br\">&2; exit 1;; esac; echo \"$br\" #"

Commit only reachable from only one branch

% git branch-name eae13ea
% echo $?
  • Output is to STDOUT
  • Exit value is 0.

Commit reachable from multiple branches

% git branch-name 4bc6188
Multiple branches:
% echo $?
  • Output is to STDERR
  • The exit value is 1.

Because of the exit status, these can be safely built upon. For example, to get the remote used for fetching:

remote-fetch = !"branch=$(git branch-name \"$1\") && git config branch.\"$branch\".remote || echo origin #"

You are trying to add a non-nullable field 'new_field' to userprofile without a default

If you are fine with truncating the table of the model in question, you can specify a one-off default value of None in the prompt. The migration will have superfluous default=None while your code has no default. It can be applied just fine because there's no data in the table anymore which would require a default.

Which terminal command to get just IP address and nothing else?

Command ifconfig is deprected and you should use ip command on Linux.

Also ip a will give you scope on the same line as IP so it's easier to use.

This command will show you your global (external) IP:

ip a | grep "scope global" | grep -Po '(?<=inet )[\d.]+'

All IPv4 (also

ip a | grep "scope" | grep -Po '(?<=inet )[\d.]+'

All IPv6 (also ::1):

ip a | grep "scope" | grep -Po '(?<=inet6 )[\da-z:]+'

How to cast the size_t to double or int C++

Static cast:


iOS UIImagePickerController result image orientation after upload

Here is a Swift version of the answer by @an0:

func normalizedImage() -> UIImage {

  if (self.imageOrientation == UIImageOrientation.Up) { 
      return self;

  UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
  let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)

  let normalizedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()
  return normalizedImage;

Also in a more general function:

func fixOrientation(img:UIImage) -> UIImage {

  if (img.imageOrientation == UIImageOrientation.Up) { 
      return img;

  UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale);
  let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)

  let normalizedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()
  return normalizedImage;


Swift 3 version:

func fixOrientation(img: UIImage) -> UIImage {
    if (img.imageOrientation == .up) {
        return img

    UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale)
    let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
    img.draw(in: rect)

    let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()!

    return normalizedImage

How to import a class from default package

Create a new package And then move the classes of default package in new package and use those classes

100% width in React Native Flexbox

Simply add alignSelf: "stretch" to your item's stylesheet.

line1: {
    backgroundColor: '#FDD7E4',
    alignSelf: 'stretch',
    textAlign: 'center',

How to install grunt and how to build script with it

I got the same issue, but i solved it with changing my Grunt.js to Gruntfile.js Check your file name before typing grunt.cmd on windows cmd (if you're using windows).

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

this could happen if you are trying to use your public key to create certificate instead of your private key. you should use private key

is there a function in lodash to replace matched item

[ES6] This code works for me.

let result = => === ? updatedItem : item)

JPA 2.0, Criteria API, Subqueries, In Expressions

You can use double join, if table A B are connected only by table AB.

public static Specification<A> findB(String input) {
    return (Specification<A>) (root, cq, cb) -> {
        Join<A,AB> AjoinAB = root.joinList(A_.AB_LIST,JoinType.LEFT);
        Join<AB,B> ABjoinB = AjoinAB.join(AB_.B,JoinType.LEFT);
        return cb.equal(ABjoinB.get(B_.NAME),input);

That's just an another option
Sorry for that timing but I have came across this question and I also wanted to make SELECT IN but I didn't even thought about double join. I hope it will help someone.

How do you UDP multicast in Python?

Just another answer to explain some subtle points in the code of the other answers:

  • socket.INADDR_ANY - (Edited) In the context of IP_ADD_MEMBERSHIP, this doesn't really bind the socket to all interfaces but just choose the default interface where multicast is up (according to routing table)
  • Joining a multicast group isn't the same as binding a socket to a local interface address

see What does it mean to bind a multicast (UDP) socket? for more on how multicast works

Multicast receiver:

import socket
import struct
import argparse

def run(groups, port, iface=None, bind_group=None):
    # generally speaking you want to bind to one of the groups you joined in
    # this script,
    # but it is also possible to bind to group which is added by some other
    # programs (like another python program instance of this)

    # assert bind_group in groups + [None], \
    #     'bind group not in groups to join'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

    # allow reuse of socket (to allow another instance of python running this
    # script binding to the same ip/port)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    sock.bind(('' if bind_group is None else bind_group, port))
    for group in groups:
        mreq = struct.pack(
            '4sl' if iface is None else '4s4s',
            socket.INADDR_ANY if iface is None else socket.inet_aton(iface))

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    while True:

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=19900)
    parser.add_argument('--join-mcast-groups', default=[], nargs='*',
                        help='multicast groups (ip addrs) to listen to join')
        '--iface', default=None,
        help='local interface to use for listening to multicast data; '
        'if unspecified, any interface would be chosen')
        '--bind-group', default=None,
        help='multicast groups (ip addrs) to bind to for the udp socket; '
        'should be one of the multicast groups joined globally '
        '(not necessarily joined in this python program) '
        'in the interface specified by --iface. '
        'If unspecified, bind to '
        '(all addresses (all multicast addresses) of that interface)')
    args = parser.parse_args()
    run(args.join_mcast_groups, args.port, args.iface, args.bind_group)

sample usage: (run the below in two consoles and choose your own --iface (must be same as the interface that receives the multicast data))

python3 --iface='' --join-mcast-groups '' '' '' --bind-group ''

python3 --iface='' --join-mcast-groups ''

Multicast sender:

import socket
import argparse

def run(group, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)
    sock.sendto(b'from ' +
                f'group: {group}, port: {port}'.encode(), (group, port))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--mcast-group', default='')
    parser.add_argument('--port', default=19900)
    args = parser.parse_args()
    run(args.mcast_group, args.port)

sample usage: # assume the receiver binds to the below multicast group address and that some program requests to join that group. And to simplify the case, assume the receiver and the sender are under the same subnet

python3 --mcast-group ''

python3 --mcast-group ''

Copying from one text file to another using Python

The oneliner:

open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l])

Recommended with with:

with open("in.txt") as f:
    lines = f.readlines()
    lines = [l for l in lines if "ROW" in l]
    with open("out.txt", "w") as f1:

Using less memory:

with open("in.txt") as f:
    with open("out.txt", "w") as f1:
        for line in f:
            if "ROW" in line:

How to use JUnit to test asynchronous processes

An alternative is to use the CountDownLatch class.

public class DatabaseTest {

     * Data limit
    private static final int DATA_LIMIT = 5;

     * Countdown latch
    private CountDownLatch lock = new CountDownLatch(1);

     * Received data
    private List<Data> receiveddata;

    public void testDataRetrieval() throws Exception {
        Database db = new MockDatabaseImpl();
        db.getData(DATA_LIMIT, new DataCallback() {
            public void onSuccess(List<Data> data) {
                receiveddata = data;

        lock.await(2000, TimeUnit.MILLISECONDS);

        assertEquals(DATA_LIMIT, receiveddata.size());

NOTE you can't just used syncronized with a regular object as a lock, as fast callbacks can release the lock before the lock's wait method is called. See this blog post by Joe Walnes.

EDIT Removed syncronized blocks around CountDownLatch thanks to comments from @jtahlborn and @Ring

What's the best way to select the minimum value from several columns?

There are likely to be many ways to accomplish this. My suggestion is to use Case/When to do it. With 3 columns, it's not too bad.

Select Id,
       Case When Col1 < Col2 And Col1 < Col3 Then Col1
            When Col2 < Col1 And Col2 < Col3 Then Col2 
            Else Col3
            End As TheMin
From   YourTableNameHere

In Django, how do I check if a user is in a certain group?

In one line:

'Groupname' in user.groups.values_list('name', flat=True)

This evaluates to either True or False.

How to order results with findBy() in Doctrine

$cRepo = $em->getRepository('KaleLocationBundle:Country');

// Leave the first array blank
$countries = $cRepo->findBy(array(), array('name'=>'asc'));

Is <div style="width: ;height: ;background: "> CSS?

For example :

<div style="height:100px; width:100px; background:#000000"></div>


you give css to div of height and width having 100px and background as black.

PS : try to avoid inline-css you can make external CSS and import in your html file.

you can refer here for CSS

hope this helps.

How to remove new line characters from data rows in mysql?

update mytable set title=trim(replace(REPLACE(title,CHAR(13),''),CHAR(10),''));

Above is working for fine.

How can I create a "Please Wait, Loading..." animation using jQuery?

Place this code on your body tag

<div class="loader">
<div class="loader-centered">
    <div class="object square-one"></div>
    <div class="object square-two"></div>
    <div class="object square-three"></div>
<div class="container">
<div class="jumbotron">
    <h1 id="loading-text">Loading...</h1>

And use this jquery script

<script type="text/javascript">

jQuery(window).load(function() {
//in production change 5000 to 400
$("#loading-text").addClass('text-success').html('page loaded');

See a full example working here.

Comparing results with today's date?

If you have a table with just a stored date (no time) and want to get those by "now", then you can do this:


This results in rows which day difference is 0 (so today).

How to display table data more clearly in oracle sqlplus

If you mean you want to see them like this:

----------- ---------- -------------- ---------
          1 HSBC       Nugegoda Road      43434
          2 HNB Bank   Colombo Road      223423

then in SQL Plus you can set the column widths like this (for example):

column name format a10
column address format a20
column telephone format 999999999

You can also specify the line size and page size if necessary like this:

set linesize 100 pagesize 50

You do this by typing those commands into SQL Plus before running the query. Or you can put these commands and the query into a script file e.g. myscript.sql and run that. For example:

column name format a10
column address format a20
column telephone format 999999999

select name, address, telephone
from mytable;

How to call Makefile from another Makefile?

Instead of the -f of make you might want to use the -C <path> option. This first changes the to the path '<path>', and then calles make there.


  rm -f ./*~ ./gmon.out ./core $(SRC_DIR)/*~ $(OBJ_DIR)/*.o
  rm -f ../svn-commit.tmp~
  rm -f $(BIN_DIR)/$(PROJECT)
  $(MAKE) -C gtest-1.4.0/make clean

google maps v3 marker info window on mouseover

Here's an example:

marker.addListener('mouseover', function() {, this);

// assuming you also want to hide the infowindow when user mouses-out
marker.addListener('mouseout', function() {

C++ Redefinition Header Files (winsock2.h)

By using "header guards":

#ifndef MYCLASS_H
#define MYCLASS_H

// This is unnecessary, see comments.
//#pragma once

// MyClass.h

#include <winsock2.h>

class MyClass

// methods
    MyClass(unsigned short port);
    virtual ~MyClass(void);


Download Excel file via AJAX MVC

CSL's answer was implemented in a project I'm working on but the problem I incurred was scaling out on Azure broke our file downloads. Instead, I was able to do this with one AJAX call:


public FileResult DownloadInvoice(int id1, int id2)
    //necessary to get the filename in the success of the ajax callback
    HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

    byte[] fileBytes = _service.GetInvoice(id1, id2);
    string fileName = "Invoice.xlsx";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

CLIENT (modified version of Handle file download from ajax post)

$("#downloadInvoice").on("click", function() {

    var xhr = new XMLHttpRequest();
    var params = [];'POST', "@Html.Raw(Url.Action("DownloadInvoice", "Controller", new { id1 = Model.Id1, id2 = Model.Id2 }))", true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function () {
        if (this.status === 200) {
            var filename = "";
            var disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('attachment') !== -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            var type = xhr.getResponseHeader('Content-Type');

            var blob = typeof File === 'function'
                ? new File([this.response], filename, { type: type })
                : new Blob([this.response], { type: type });
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                window.navigator.msSaveBlob(blob, filename);
            } else {
                var URL = window.URL || window.webkitURL;
                var downloadUrl = URL.createObjectURL(blob);

                if (filename) {
                    // use HTML5 a[download] attribute to specify filename
                    var a = document.createElement("a");
                    // safari doesn't support this yet
                    if (typeof === 'undefined') {
                        window.location = downloadUrl;
                    } else {
                        a.href = downloadUrl;
               = filename;
                } else {
                    window.location = downloadUrl;


                setTimeout(function() {
                }, 100); // cleanup
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

Getting error: ISO C++ forbids declaration of with no type

You forgot the return types in your member function definitions:

int ttTree::ttTreeInsert(int value) { ... }

and so on.

How to enable curl in Wamp server

The steps are as follows :

  1. Close WAMP (if running)
  2. Navigate to WAMP\bin\php\(your version of php)\
  3. Edit php.ini
  4. Search for curl, uncomment extension=php_curl.dll
  5. Navigate to WAMP\bin\Apache\(your version of apache)\bin\
  6. Edit php.ini
  7. Search for curl, uncomment extension=php_curl.dll
  8. Save both
  9. Restart WAMP

MS-access reports - The search key was not found in any record - on save

I know this is a very old post but as I was searching for additional solutions to this same error while running my command (I'd previously encountered the spaces in the Excel wb headers and remedied it with VBA each time the file is updated so I knew it wasn't that). I considered the fact that the xlsm file and DB were on separate network drives but didn't want to explore moving one unless it was my last resort.

I attempted to run the save import manually and there it was right in front of my face. The folder containing the xlsm file had been renamed....I changed the name back to match my saved import and....smh, it was that all along.

Regular Expression to get a string between parentheses in Javascript


var str = "I expect five hundred dollars ($500) ($1).";
str.match(/\(.*?\)/g).map(x => x.replace(/[()]/g, ""));
? (2) ["$500", "$1"]

It is possible to replace brackets with square or curly brackets if you need

Generate a random date between two other dates

In python:

>>> from dateutil.rrule import rrule, DAILY
>>> import datetime, random
>>> random.choice(
datetime.datetime(2010, 2, 1, 0, 0)

(need python dateutil library – pip install python-dateutil)

node.js hash string?

Take a look at crypto.createHash(algorithm)

var filename = process.argv[2];
var crypto = require('crypto');
var fs = require('fs');

var md5sum = crypto.createHash('md5');

var s = fs.ReadStream(filename);
s.on('data', function(d) {

s.on('end', function() {
  var d = md5sum.digest('hex');
  console.log(d + '  ' + filename);

SwiftUI - How do I change the background color of a View?

I like to declare a modifier for changing the background color of a view.

extension View {
  func background(with color: Color) -> some View {
    background(GeometryReader { geometry in
      Rectangle().path(in: geometry.frame(in: .local)).foregroundColor(color)

Then I use the modifier by passing in a color to a view.

struct Content: View {

  var body: some View {
    Text("Foreground Label").foregroundColor(.green).background(with: .black)


enter image description here

Put buttons at bottom of screen with LinearLayout?

Just add layout_weight="1" to in your linearLayout which having Buttons.

Edit :- let me make it simple

follow something like below, tags name may not be correct, it is just an Idea

<LL>// Top Parrent LinearLayout
   <LL1 height="fill_parent" weight="1" "other tags as requirement"> <TV /><Butons /></LL1> // this layout will fill your screen.
   <LL2 height="wrap_content" weight="1"  orientation="Horizontal" "other tags as requirement"> <BT1 /><BT2/ ></LL2> // this layout gonna take lower part of button height of your screen


Batch not-equal (inequality) operator


if NOT "asdf" == "fdas" echo asdf

smtp configuration for php mail

But now it is not working and I contacted our hosting team then they told me to use smtp

Newsflash - it was using SMTP before. They've not provided you with the information you need to solve the problem - or you've not relayed it accurately here.

Its possible that they've disabled the local MTA on the webserver, in which case you'll need to connect the SMTP port on a remote machine. There are lots of toolkits which will do the heavy lifting for you. Personally I like phpmailer because it adds other functionality.

Certainly if they've taken away a facility which was there before and your paying for a service then your provider should be giving you better support than that (there are also lots of programs to drop in in place of a full MTA which would do the job).


JavaScript hashmap equivalent

Problem description

JavaScript has no built-in general map type (sometimes called associative array or dictionary) which allows to access arbitrary values by arbitrary keys. JavaScript's fundamental data structure is the object, a special type of map which only accepts strings as keys and has special semantics like prototypical inheritance, getters and setters and some further voodoo.

When using objects as maps, you have to remember that the key will be converted to a string value via toString(), which results in mapping 5 and '5' to the same value and all objects which don't overwrite the toString() method to the value indexed by '[object Object]'. You might also involuntarily access its inherited properties if you don't check hasOwnProperty().

JavaScript's built-in array type does not help one bit: JavaScript arrays are not associative arrays, but just objects with a few more special properties. If you want to know why they can't be used as maps, look here.

Eugene's Solution

Eugene Lazutkin already described the basic idea of using a custom hash function to generate unique strings which can be used to look up the associated values as properties of a dictionary object. This will most likely be the fastest solution, because objects are internally implemented as hash tables.

  • Note: Hash tables (sometimes called hash maps) are a particular implementation of the map concept using a backing array and lookup via numeric hash values. The runtime environment might use other structures (such as search trees or skip lists) to implement JavaScript objects, but as objects are the fundamental data structure, they should be sufficiently optimised.

In order to get a unique hash value for arbitrary objects, one possibility is to use a global counter and cache the hash value in the object itself (for example, in a property named __hash).

A hash function which does this is and works for both primitive values and objects is:

function hash(value) {
    return (typeof value) + ' ' + (value instanceof Object ?
        (value.__hash || (value.__hash = ++arguments.callee.current)) :

hash.current = 0;

This function can be used as described by Eugene. For convenience, we will further wrap it in a Map class.

My Map implementation

The following implementation will additionally store the key-value-pairs in a doubly linked list in order to allow fast iteration over both keys and values. To supply your own hash function, you can overwrite the instance's hash() method after creation.

// Linking the key-value-pairs is optional.
// If no argument is provided, linkItems === undefined, i.e. !== false
// --> linking will be enabled
function Map(linkItems) {
    this.current = undefined;
    this.size = 0;

    if(linkItems === false)

Map.noop = function() {
    return this;

Map.illegal = function() {
    throw new Error("illegal operation for maps without linking");

// Map initialisation from an existing object
// doesn't add inherited properties if not explicitly instructed to:
// omitting foreignKeys means foreignKeys === undefined, i.e. == false
// --> inherited properties won't be added
Map.from = function(obj, foreignKeys) {
    var map = new Map;

    for(var prop in obj) {
        if(foreignKeys || obj.hasOwnProperty(prop))
            map.put(prop, obj[prop]);

    return map;

Map.prototype.disableLinking = function() { = Map.noop;
    this.unlink = Map.noop;
    this.disableLinking = Map.noop; = Map.illegal;
    this.key = Map.illegal;
    this.value = Map.illegal;
    this.removeAll = Map.illegal;

    return this;

// Overwrite in Map instance if necessary
Map.prototype.hash = function(value) {
    return (typeof value) + ' ' + (value instanceof Object ?
        (value.__hash || (value.__hash = ++arguments.callee.current)) :

Map.prototype.hash.current = 0;

// --- Mapping functions

Map.prototype.get = function(key) {
    var item = this[this.hash(key)];
    return item === undefined ? undefined : item.value;

Map.prototype.put = function(key, value) {
    var hash = this.hash(key);

    if(this[hash] === undefined) {
        var item = { key : key, value : value };
        this[hash] = item;;
    else this[hash].value = value;

    return this;

Map.prototype.remove = function(key) {
    var hash = this.hash(key);
    var item = this[hash];

    if(item !== undefined) {

        delete this[hash];

    return this;

// Only works if linked
Map.prototype.removeAll = function() {

    return this;

// --- Linked list helper functions = function(item) {
    if(this.size == 0) {
        item.prev = item; = item;
        this.current = item;
    else {
        item.prev = this.current.prev; = item; = this.current;
        this.current.prev = item;

Map.prototype.unlink = function(item) {
    if(this.size == 0)
        this.current = undefined;
    else { =; = item.prev;
        if(item === this.current)
            this.current =;

// --- Iterator functions - only work if map is linked = function() {
    this.current =;

Map.prototype.key = function() {
    return this.current.key;

Map.prototype.value = function() {
    return this.current.value;


The following script,

var map = new Map;

map.put('spam', 'eggs').
    put('foo', 'bar').
    put('foo', 'baz').
    put({}, 'an object').
    put({}, 'another object').
    put(5, 'five').
    put(5, 'five again').
    put('5', 'another five');

for(var i = 0; i++ < map.size;
    document.writeln(map.hash(map.key()) + ' : ' + map.value());

generates this output:

string spam : eggs
string foo : baz
object 1 : an object
object 2 : another object
number 5 : five again
string 5 : another five

Further considerations

PEZ suggested to overwrite the toString() method, presumably with our hash function. This is not feasible, because it doesn't work for primitive values (changing toString() for primitives is a very bad idea). If we want toString() to return meaningful values for arbitrary objects, we would have to modify Object.prototype, which some people (myself not included) consider verboten.

The current version of my Map implementation as well as other JavaScript goodies can be obtained from here.

Self-reference for cell, column and row in worksheet functions

Just for row, but try referencing a cell just below the selected cell and subtracting one from row.


Yields the Row of cell A1 (This formula would go in cell A1.

This avoids all the indirect() and index() use but still works.

How do I get a python program to do nothing?

you can use pass inside if statement.

What is a difference between unsigned int and signed int in C?

Here is the very nice link which explains the storage of signed and unsigned INT in C -

Taken from this above article -

"process called two's complement is used to transform positive numbers into negative numbers. The side effect of this is that the most significant bit is used to tell the computer if the number is positive or negative. If the most significant bit is a 1, then the number is negative. If it's 0, the number is positive."

Adding headers when using httpClient.GetAsync

Following the greenhoorn's answer, you can use "Extensions" like this:

  public static class HttpClientExtensions
        public static HttpClient AddTokenToHeader(this HttpClient cl, string token)
            //int timeoutSec = 90;
            //cl.Timeout = new TimeSpan(0, 0, timeoutSec);
            string contentType = "application/json";
            cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
            cl.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token));
            var userAgent = "d-fens HttpClient";
            cl.DefaultRequestHeaders.Add("User-Agent", userAgent);
            return cl;

And use:

string _tokenUpdated = "TOKEN";
HttpClient _client;

Constructor in an Interface?

Here´s an example using this Technic. In this specifik example the code is making a call to Firebase using a mock MyCompletionListener that is an interface masked as an abstract class, an interface with a constructor

private interface Listener {
    void onComplete(databaseError, databaseReference);

public abstract class MyCompletionListener implements Listener{
    String id;
    String name;
    public MyCompletionListener(String id, String name) { = id; = name;

private void removeUserPresenceOnCurrentItem() {
    mFirebase.removeValue(child("some_key"), new MyCompletionListener(UUID.randomUUID().toString(), "removeUserPresenceOnCurrentItem") {
        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {


public void removeValue(DatabaseReference ref, final MyCompletionListener var1) {
    CompletionListener cListener = new CompletionListener() {
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    if (var1 != null){
                        System.out.println("Im back and my id is: " + " and my name is: ";
                        var1.onComplete(databaseError, databaseReference);

Override console.log(); for production

Put this at the top of the file:

var console = {};
console.log = function(){};

For some browsers and minifiers, you may need to apply this onto the window object.

window.console = console;

How can Bash execute a command in a different directory context?

(cd /path/to/your/special/place;/bin/your-special-command ARGS)

What is the purpose of meshgrid in Python / NumPy?

meshgrid helps in creating a rectangular grid from two 1-D arrays of all pairs of points from the two arrays.

x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])

Now, if you have defined a function f(x,y) and you wanna apply this function to all the possible combination of points from the arrays 'x' and 'y', then you can do this:

f(*np.meshgrid(x, y))

Say, if your function just produces the product of two elements, then this is how a cartesian product can be achieved, efficiently for large arrays.

Referred from here

How to override maven property in command line?

See Introduction to the POM

finalName is created as:


One of the solutions is to add own property:


And now try:

mvn -DfinalName=build clean package

GET and POST methods with the same Action name in the same Controller

Can not multi action same name and same parameter

    public ActionResult Index()
        return View();
    public ActionResult Index(int id)
        return View();

althought int id is not used

How to compare only date in moment.js

In my case i did following code for compare 2 dates may it will help you ...

var date1 = "2010-10-20";_x000D_
var date2 = "2010-10-20";_x000D_
var time1 = moment(date1).format('YYYY-MM-DD');_x000D_
var time2 = moment(date2).format('YYYY-MM-DD');_x000D_
if(time2 > time1){_x000D_
 console.log('date2 is Greter than date1');_x000D_
}else if(time2 > time1){_x000D_
 console.log('date2 is Less than date1');_x000D_
 console.log('Both date are same');_x000D_
<script src=""></script>

LINQ with groupby and count

userInfos.GroupBy(userInfo => userInfo.metric)
        .OrderBy(group => group.Key)
        .Select(group => Tuple.Create(group.Key, group.Count()));

Warning: A non-numeric value encountered

$sn = 0;//increment the serial number, then add the sn to job
for($x = 0; $x<20; $x++)
$added_date = "10/10/10";
$job_title = "new job";
$salary = $sn*1000;
$cd = "27/10/2017";//the closing date
$ins = "some institution";//the institution for the vacancy 
$notes = "some notes here";//any notes about the jobs

$sn_div = "<div class='sn_div'>".$sn."</div>";
$ad_div = "<div class='ad_div'>".$added_date."</div>";
$job_div = "<div class='job_div'>".$job_title."</div>";
$salary_div = "<div class='salary_div'>".$salary."</div>";
$cd_div = "<div class='cd_div'>".$cd."</div>";//cd means closing date
$ins_div = "<div class='ins_div'>".$ins."</div>";//ins means institution
$notes_div = "<div class='notes_div'>".$notes."</div>";

/*erroneous line*/$job_no = "job"+$sn;//to create the job rows
$$job_no = "<div class='job_wrapper'>".$sn_div.$ad_div.$job_div.$salary_div.$cd_div.$ins_div.$notes_div."</div>";

echo $$job_no;//and then echo each job


that's the code I had which looped and created new html div elements. The code worked fine and the elements were formed, but i got the same warning in the error_log.

After reading the useful other answers, I figured that I was summing up a string and a number in the erroneous line. So I changed the code at that line to

/*erroneous line*/$job_no = "job"&&$sn;//this is the new variable that will create the job rows

Now the code works as earlier but with no warnings this time. Hope this example would be useful to someone.

Freeing up a TCP/IP port?

You can use tcpkill (part of the dsniff package) to kill the connection that's on the port you need:

sudo tcpkill -9 port PORT_NUMBER


From the manual: The SELECT ... INTO OUTFILE statement is intended primarily to let you very quickly dump a table to a text file on the server machine. If you want to create the resulting file on some client host other than the server host, you cannot use SELECT ... INTO OUTFILE. In that case, you should instead use a command such as mysql -e "SELECT ..." > file_name to generate the file on the client host."

An example:

mysql -h -u usrname--password=pass db_name -e 'SELECT foo FROM bar' > /tmp/myfile.txt

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

You are getting AttributeError because you're calling groups on None, which hasn't any methods. returning None means the regex couldn't find anything matching the pattern from supplied string.

when using regex, it is nice to check whether a match has been made:

Result =, htmlString)

if Result:
    print Result.groups()

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(" $","")

Age from birthdate in python

from datetime import date

def calculate_age(born):
    today =
        birthday = born.replace(year=today.year)
    except ValueError: # raised when birth date is February 29 and the current year is not a leap year
        birthday = born.replace(year=today.year, month=born.month+1, day=1)
    if birthday > today:
        return today.year - born.year - 1
        return today.year - born.year

Update: Use Danny's solution, it's better

With CSS, use "..." for overflowed block of multi-lines

There are also several jquery plugins that deal with this issue, but many do not handle multiple lines of text. Following works:

There also some preformance tests.

Linq style "For Each"

The Array and List<T> classes already have ForEach methods, though only this specific implementation. (Note that the former is static, by the way).

Not sure it really offers a great advantage over a foreach statement, but you could write an extension method to do the job for all IEnumerable<T> objects.

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
    foreach (var item in source)

This would allow the exact code you posted in your question to work just as you want.

PHP Fatal error: Call to undefined function mssql_connect()

php.ini probably needs to read: extension=ext\php_sqlsrv_53_nts.dll

Or move the file to same directory as the php executable. This is what I did to my php5 install this week to get odbc_pdo working. :P

Additionally, that doesn't look like proper phpinfo() output. If you make a file with contents
<? phpinfo(); ?> and visit that page, the HTML output should show several sections, including one with loaded modules. (Edited to add: like shown in the screenshot of the above accepted answer)

What is a regular expression for a MAC Address?

You can use following procedure by passing mac address for validation,

private static final String MAC_PATTERN = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";

private boolean validateMAC(final String mac){          
    Pattern pattern = Pattern.compile(MAC_PATTERN);
    Matcher matcher = pattern.matcher(mac);
    return matcher.matches();             

Why do people hate SQL cursors so much?

basicaly 2 blocks of code that do the same thing. maybe it's a bit weird example but it proves the point. SQL Server 2005:

SELECT * INTO #temp FROM master..spt_values


SELECT @startTime = GETDATE()
UPDATE #temp
SET number = 0
select DATEDIFF(ms, @startTime, GETDATE())



    FOR SELECT name FROM #temp

OPEN tempCursor

INTO @name

SELECT @startTime = GETDATE()

    UPDATE #temp SET number = 0 WHERE NAME = @name
    FETCH NEXT FROM tempCursor 
    INTO @name

select DATEDIFF(ms, @startTime, GETDATE())
CLOSE tempCursor


the single update takes 156 ms while the cursor takes 2016 ms.

Sort collection by multiple fields in Kotlin

sortedWith + compareBy (taking a vararg of lambdas) do the trick:

val sortedList = list.sortedWith(compareBy({ it.age }, { }))

You can also use the somewhat more succinct callable reference syntax:

val sortedList = list.sortedWith(compareBy(Person::age, Person::name))

vertical alignment of text element in SVG

The alignment-baseline property is what you're looking for it can take the following values

auto | baseline | before-edge | text-before-edge | 
middle | central | after-edge | text-after-edge | 
ideographic | alphabetic | hanging | mathematical | 

Description from w3c

This property specifies how an object is aligned with respect to its parent. This property specifies which baseline of this element is to be aligned with the corresponding baseline of the parent. For example, this allows alphabetic baselines in Roman text to stay aligned across font size changes. It defaults to the baseline with the same name as the computed value of the alignment-baseline property. That is, the position of "ideographic" alignment-point in the block-progression-direction is the position of the "ideographic" baseline in the baseline-table of the object being aligned.

W3C Source

Unfortunately, although this is the "correct" way of achieving what you're after it would appear Firefox have not implemented a lot of the presentation attributes for the SVG Text Module ('SVG in Firefox' MDN Documentation)

Conditional WHERE clause in SQL Server

To answer the underlying question of how to use a CASE expression in the WHERE clause:

First remember that the value of a CASE expression has to have a normal data type value, not a boolean value. It has to be a varchar, or an int, or something. It's the same reason you can't say SELECT Name, 76 = Age FROM [...] and expect to get 'Frank', FALSE in the result set.

Additionally, all expressions in a WHERE clause need to have a boolean value. They can't have a value of a varchar or an int. You can't say WHERE Name; or WHERE 'Frank';. You have to use a comparison operator to make it a boolean expression, so WHERE Name = 'Frank';

That means that the CASE expression must be on one side of a boolean expression. You have to compare the CASE expression to something. It can't stand by itself!


    DateDropped = 0
            WHEN @JobsOnHold  = 1 AND DateAppr >= 0 THEN 'True'
            WHEN DateAppr != 0 THEN 'True'
            ELSE 'False'
        END = 'True'

Notice how in the end the CASE expression on the left will turn the boolean expression into either 'True' = 'True' or 'False' = 'True'.

Note that there's nothing special about 'False' and 'True'. You can use 0 and 1 if you'd rather, too.

You can typically rewrite the CASE expression into boolean expressions we're more familiar with, and that's generally better for performance. However, sometimes is easier or more maintainable to use an existing expression than it is to convert the logic.

How to hide keyboard in swift on pressing return key?

Another way of doing this which mostly uses the storyboard and easily allows you to have multiple text fields is:

@IBAction func resignKeyboard(sender: AnyObject) {

Connect all your text fields for that view controller to that action on the Did End On Exit event of each field.

Equivalent of SQL ISNULL in LINQ?

You can use the ?? operator to set the default value but first you must set the Nullable property to true in your dbml file in the required field (xx.Online)

var hht = from x in db.HandheldAssets
        join a in db.HandheldDevInfos on x.AssetID equals a.DevName into DevInfo
        from aa in DevInfo.DefaultIfEmpty()
        select new
        AssetID = x.AssetID,
        Status = xx.Online ?? false

JBoss default password

I can also verify the above solution except I had to change in

**..\server\<server profile>\conf\props\**

ASP.NET MVC - Extract parameter of an URL

public ActionResult Index(int id,string value)

This function get values form URL After that you can use below function

Request.RawUrl - Return complete URL of Current page

RouteData.Values - Return Collection of Values of URL

Request.Params - Return Name Value Collections

Detect when input has a 'readonly' attribute

Since JQuery 1.6, always use .prop() Read why here:

if($('input').prop('readonly')){ }

.prop() can also be used to set the property



Check if datetime instance falls in between other two datetime objects

Do simple compare > and <.

if (dateA>dateB && dateA<dateC)
    //do something

If you care only on time:

if (dateA.TimeOfDay>dateB.TimeOfDay && dateA.TimeOfDay<dateC.TimeOfDay)
    //do something

performSelector may cause a leak because its selector is unknown

My guess about this is this: since the selector is unknown to the compiler, ARC cannot enforce proper memory management.

In fact, there are times when memory management is tied to the name of the method by a specific convention. Specifically, I am thinking of convenience constructors versus make methods; the former return by convention an autoreleased object; the latter a retained object. The convention is based on the names of the selector, so if the compiler does not know the selector, then it cannot enforce the proper memory management rule.

If this is correct, I think that you can safely use your code, provided you make sure that everything is ok as to memory management (e.g., that your methods do not return objects that they allocate).

Simple function to sort an array of objects

I modified @Geuis 's answer by using lambda and convert it upper case first:

people.sort((a, b) => a.toLocaleUpperCase() < b.toLocaleUpperCase() ? -1 : 1);

Auto expand a textarea using jQuery

function autoResizeTextarea() {_x000D_
  for (let index = 0; index < $('textarea').length; index++) {_x000D_
    let element = $('textarea')[index];_x000D_
    let offset = element.offsetHeight - element.clientHeight;_x000D_
    $(element).css('resize', 'none');_x000D_
    $(element).on('input', function() {_x000D_
      $(this).height(0).height(this.scrollHeight - offset - parseInt($(this).css('padding-top')));_x000D_

this should work.

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

Here is some weak adobe documentation on different flash 9 wmode settings.

A note of caution on wmode transparent is here in the adobe bug trac.

And new for flash 10, are two new wmodes: gpu and direct. Please refer to Adobe Knowledge Base about wmode.

Fixed Table Cell Width

I had one long table td cell, this forced the table to the edges of the browser and looked ugly. I just wanted that column to be fixed size only and break the words when it reaches the specified width. So this worked well for me:

<td><div style='width: 150px;'>Text to break here</div></td>

You don't need to specify any kind of style to table, tr elements. You may also use overflow:hidden; as suggested by other answers but it causes for the excess text to disappear.

How to document a method with parameter(s)?

Docstrings are only useful within interactive environments, e.g. the Python shell. When documenting objects that are not going to be used interactively (e.g. internal objects, framework callbacks), you might as well use regular comments. Here’s a style I use for hanging indented comments off items, each on their own line, so you know that the comment is applying to:

def Recomputate \
      # the rotary gyrator to operate on
      # the computrons to perform the recomputation with
      # whether to recomputate forthwith or at one's leisure
  ) :
  # recomputates the specified rotary gyrator with
  # the desired computrons.
#end Recomputate

You can’t do this sort of thing with docstrings.

Multiple selector chaining in jQuery?

You should be able to use:

$('#Edit.myClass, #Create.myClass').plugin({options here});

jQuery | Multiple Selectors

Android Dialog: Removing title bar

create your XML which is shown in dialog here it is activity_no_title_dialog

final Dialog dialog1 = new Dialog(context);

Prepend text to beginning of string

Since the question is about what is the fastest method, I thought I'd throw up add some perf metrics.

TL;DR The winner, by a wide margin, is the + operator, and please never use regex

enter image description here

how to show only even or odd rows in sql server 2008?

Try following


How to kill a nodejs process in Linux?

sudo netstat -lpn |grep :'3000'

3000 is port i was looking for, After first command you will have Process ID for that port

kill -9 1192

in my case 1192 was process Id of process running on 3000 PORT use -9 for Force kill the process

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

ORA-00932: inconsistent datatypes: expected - got CLOB

You can't put a CLOB in the WHERE clause. From the documentation:

Large objects (LOBs) are not supported in comparison conditions. However, you can use PL/SQL programs for comparisons on CLOB data.

If your values are always less than 4k, you can use:

   SET TEST_Category           = 'just testing'  
 WHERE to_char(TEST_SCRIPT)    = 'something'
   AND ID                      = '10000239';

It is strange to search by a CLOB anyways.. could you not just search by the ID column?

Get the cartesian product of a series of lists?

import itertools
>>> for i in itertools.product([1,2,3],['a','b'],[4,5]):
...         print i
(1, 'a', 4)
(1, 'a', 5)
(1, 'b', 4)
(1, 'b', 5)
(2, 'a', 4)
(2, 'a', 5)
(2, 'b', 4)
(2, 'b', 5)
(3, 'a', 4)
(3, 'a', 5)
(3, 'b', 4)
(3, 'b', 5)

Function overloading in Javascript - Best practices

There are two ways you could approach this better:

  1. Pass a dictionary (associative array) if you want to leave a lot of flexibility

  2. Take an object as the argument and use prototype based inheritance to add flexibility.

How to send email to multiple recipients with addresses stored in Excel?

ToAddress = "[email protected]"
ToAddress1 = "[email protected]"
ToAddress2 = "[email protected]"
MessageSubject = "It works!."
Set ol = CreateObject("Outlook.Application")
Set newMail = ol.CreateItem(olMailItem)
newMail.Subject = MessageSubject

Scroll to the top of the page after render in react.js

All of the above didn't work for me - not sure why but:


worked, where HEADER is the id of my header element

Reading a file line by line in Go

EDIT: As of go1.1, the idiomatic solution is to use bufio.Scanner

I wrote up a way to easily read each line from a file. The Readln(*bufio.Reader) function returns a line (sans \n) from the underlying bufio.Reader struct.

// Readln returns a single line (without the ending \n)
// from the input buffered reader.
// An error is returned iff there is an error with the
// buffered reader.
func Readln(r *bufio.Reader) (string, error) {
  var (isPrefix bool = true
       err error = nil
       line, ln []byte
  for isPrefix && err == nil {
      line, isPrefix, err = r.ReadLine()
      ln = append(ln, line...)
  return string(ln),err

You can use Readln to read every line from a file. The following code reads every line in a file and outputs each line to stdout.

f, err := os.Open(fi)
if err != nil {
    fmt.Printf("error opening file: %v\n",err)
r := bufio.NewReader(f)
s, e := Readln(r)
for e == nil {
    s,e = Readln(r)


What is the fastest way to create a checksum for large files in C#

As Anton Gogolev noted, FileStream reads 4096 bytes at a time by default, But you can specify any other value using the FileStream constructor:

new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 16 * 1024 * 1024)

Note that Brad Abrams from Microsoft wrote in 2004:

there is zero benefit from wrapping a BufferedStream around a FileStream. We copied BufferedStream’s buffering logic into FileStream about 4 years ago to encourage better default performance


How to read/process command line arguments?

import sys


sys.argv is a list that contains all the arguments passed to the script on the command line.


import sys

Spring Boot yaml configuration for a list of strings

Ahmet's answer provides on how to assign the comma separated values to String array.

To use the above configuration in different classes you might need to create getters/setters for this.. But if you would like to load this configuration once and keep using this as a bean with Autowired annotation, here is the how I accomplished:


@Bean (name = "ignoreFileNames")
@ConfigurationProperties ( prefix = "ignore.filenames" )
public List<String> ignoreFileNames(){
    return new ArrayList<String>();

In outside classes:

private List<String> ignoreFileNames;

you can use the same list everywhere else by autowiring.

Laravel - Route::resource vs Route::controller

RESTful Resource controller

A RESTful resource controller sets up some default routes for you and even names them.

Route::resource('users', 'UsersController');

Gives you these named routes:

Verb          Path                        Action  Route Name
GET           /users                      index   users.index
GET           /users/create               create  users.create
POST          /users                      store
GET           /users/{user}               show
GET           /users/{user}/edit          edit    users.edit
PUT|PATCH     /users/{user}               update  users.update
DELETE        /users/{user}               destroy users.destroy

And you would set up your controller something like this (actions = methods)

class UsersController extends BaseController {

    public function index() {}

    public function show($id) {}

    public function store() {}


You can also choose what actions are included or excluded like this:

Route::resource('users', 'UsersController', [
    'only' => ['index', 'show']

Route::resource('monkeys', 'MonkeysController', [
    'except' => ['edit', 'create']

API Resource controller

Laravel 5.5 added another method for dealing with routes for resource controllers. API Resource Controller acts exactly like shown above, but does not register create and edit routes. It is meant to be used for ease of mapping routes used in RESTful APIs - where you typically do not have any kind of data located in create nor edit methods.

Route::apiResource('users', 'UsersController');

RESTful Resource Controller documentation

Implicit controller

An Implicit controller is more flexible. You get routed to your controller methods based on the HTTP request type and name. However, you don't have route names defined for you and it will catch all subfolders for the same route.

Route::controller('users', 'UserController');

Would lead you to set up the controller with a sort of RESTful naming scheme:

class UserController extends BaseController {

    public function getIndex()
        // GET request to index

    public function getShow($id)
        // get request to 'users/show/{id}'

    public function postStore()
        // POST request to 'users/store'


Implicit Controller documentation

It is good practice to use what you need, as per your preference. I personally don't like the Implicit controllers, because they can be messy, don't provide names and can be confusing when using php artisan routes. I typically use RESTful Resource controllers in combination with explicit routes.

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] =[df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

How do I pass a method as a parameter in Python

Yes it is possible. Just call it:

class Foo(object):
    def method1(self):
    def method2(self, method):
        return method()

foo = Foo()

How do I format currencies in a Vue component?

UPDATE: I suggest using a solution with filters, provided by @Jess.

I would write a method for that, and then where you need to format price you can just put the method in the template and pass value down

methods: {
    formatPrice(value) {
        let val = (value/1).toFixed(2).replace('.', ',')
        return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".")

And then in template:

        <div class="panel-group"v-for="item in list">
            <div class="col-md-8">
                   Total: <b>{{ formatPrice( }}</b>

BTW - I didn't put too much care on replacing and regular expression. It could be improved.enter code here

Vue.filter('tableCurrency', num => {_x000D_
  if (!num) {_x000D_
    return '0.00';_x000D_
  const number = (num / 1).toFixed(2).replace(',', '.');_x000D_
  return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');_x000D_

Use of PUT vs PATCH methods in REST API real life scenarios

The difference between PUT and PATCH is that:

  1. PUT is required to be idempotent. In order to achieve that, you have to put the entire complete resource in the request body.
  2. PATCH can be non-idempotent. Which implies it can also be idempotent in some cases, such as the cases you described.

PATCH requires some "patch language" to tell the server how to modify the resource. The caller and the server need to define some "operations" such as "add", "replace", "delete". For example:

GET /contacts/1
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "state": "NY",
  "zip": "10001"

PATCH /contacts/1
 [{"operation": "add", "field": "address", "value": "123 main street"},
  {"operation": "replace", "field": "email", "value": "[email protected]"},
  {"operation": "delete", "field": "zip"}]

GET /contacts/1
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "state": "NY",
  "address": "123 main street",

Instead of using explicit "operation" fields, the patch language can make it implicit by defining conventions like:

in the PATCH request body:

  1. The existence of a field means "replace" or "add" that field.
  2. If the value of a field is null, it means delete that field.

With the above convention, the PATCH in the example can take the following form:

PATCH /contacts/1
  "address": "123 main street",
  "email": "[email protected]",

Which looks more concise and user-friendly. But the users need to be aware of the underlying convention.

With the operations I mentioned above, the PATCH is still idempotent. But if you define operations like: "increment" or "append", you can easily see it won't be idempotent anymore.

POST JSON to API using Rails and HTTParty

The :query_string_normalizer option is also available, which will override the default normalizer HashConversions.to_params(query)

query_string_normalizer: ->(query){query.to_json}

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

For me this location worked: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\DevDiv\vc\Servicing\11.0\RuntimeMinimum\Version

Check what version you have after you installed the package and use that as a condition in your installer. (mine is set to 11.0.50727 after installing VCred).

open link of google play store in mobile version android

Below code may helps you for display application link of google play sore in mobile version.

For Application link :

Uri uri = Uri.parse("market://details?id=" + mContext.getPackageName());
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);

  try {

      } catch (ActivityNotFoundException e) {

        //the device hasn't installed Google Play
        Toast.makeText(Setting.this, "You don't have Google Play installed", Toast.LENGTH_LONG).show();

For Developer link :

Uri uri = Uri.parse("market://search?q=pub:" + YourDeveloperName);
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);

            try {


            } catch (ActivityNotFoundException e) {

                //the device hasn't installed Google Play
                Toast.makeText(Settings.this, "You don't have Google Play installed", Toast.LENGTH_LONG).show();


Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.

The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.

What's your most controversial programming opinion?

Microsoft Windows is the best platform for software development.

Reasoning: Microsoft spoils its developers with excellent and cheap development tools, the platform and its API's are well documented, the platform is evolving at a rappid rate which creates a lot of opportunities for developers, The OS has a large user base which is important for obvious commercial reasons, there is a big community of Windows developers, I haven't yet been fired for choosing Microsoft.

To delay JavaScript function call using jQuery

function sample() {
    alert("This is sample function");

$(function() {
    $("#button").click(function() {
        setTimeout(sample, 2000);



If you want to encapsulate sample() there, wrap the whole thing in a self invoking function (function() { ... })().

How to get tf.exe (TFS command line client)?

Following on from the earlier answers above but based on a VS 2019 install ;
I needed to run "tf git permission" commands, and copied the following files from:

C:\Program Files (x86)\Microsoft Visual Studio\2019\TeamExplorer\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer


How to get the total number of rows of a GROUP BY query?

I don't use PDO for MySQL and PgSQL, but I do for SQLite. Is there a way (without completely changing the dbal back) to count rows like this in PDO?

Accordingly to this comment, the SQLite issue was introduced by an API change in 3.x.

That said, you might want to inspect how PDO actually implements the functionality before using it.

I'm not familiar with its internals but I'd be suspicious at the idea that PDO parses your SQL (since an SQL syntax error would appear in the DB's logs) let alone tries to make the slightest sense of it in order to count rows using an optimal strategy.

Assuming it doesn't indeed, realistic strategies for it to return a count of all applicable rows in a select statement include string-manipulating the limit clause out of your SQL statement, and either of:

  1. Running a select count() on it as a subquery (thus avoiding the issue you described in your PS);
  2. Opening a cursor, running fetch all and counting the rows; or
  3. Having opened such a cursor in the first place, and similarly counting the remaining rows.

A much better way to count, however, would be to execute the fully optimized query that will do so. More often than not, this means rewriting meaningful chunks of the initial query you're trying to paginate -- stripping unneeded fields and order by operations, etc.

Lastly, if your data sets are large enough that counts any kind of lag, you might also want to investigate returning the estimate derived from the statistics instead, and/or periodically caching the result in Memcache. At some point, having precisely correct counts is no longer useful...

C# importing class into another class doesn't work

If they are separate class files within the same project, then you do not need to have an 'import' statement. Just use the class straight off. If the files are in separate projects, you need to add a reference to the project first before you can use an 'import' statement on it.