Programs & Examples On #Moosex types

How organize uploaded media in WP?

Currently, media organisation is possible.

The "problem" with the media library in wordpress is always interesting. Check the following plugin to solve this: WordPress Real Media Library. WP RML creates a virtual folder structure based on an own taxonomy.

Drag & Drop your files

It allows you to organize your wordpress media library in a nice way with folders. It is easy to use, just drag&drop your files and move it to a specific folder. Filter when inserting media or create a gallery from a folder.

Turn your WordPress media library to the next level with folders / categories. Get organized with thousands of images.

RML (Real Media Library) is one of the most wanted media wordpress plugins. It is easy to use and it allows you to organize your thousands of images in folders. It is similar to wordpress categories like in the posts.

Use your mouse (or touch) to drag and drop your files. Create, rename, delete or reorder your folders If you want to select a image from the “Select a image”-dialog (e. g. featured image) you can filter when inserting media. Just install this plugin and it works fine with all your image and media files. It also supports multisite.

If you buy, you get: Forever FREE updates and high quality and fast support.

From the product description i can quote. If you want to try the plugin, there is also a demo on the plugin page.

Update #1 (2017-01-27): Manage your uploads physically

A long time ago I started to open this thread and now there is a usable extension plugin for Real Media Library which allows you to physically manage your uploads folder.

enter image description here

Check out this plugin: https://wordpress.org/plugins/physical-custom-upload-folder/

Do you know the wp-content/uploads folder? There, the files are stored in year/month based folders. This can be a very complicated and mass process, especially when you are working with a FTP client like FileZilla.

Moving already uploaded files: This plugin does not allow to move the files physically when you move a file in the Real Media Library because WordPress uses the URL's in different places. It is very hard to maintain such a process. So this only works for new uploads.

Physical organisation on server?

(Please read on if you are developer) I as developer thought about a solution about this. Does it make sense to organize the uploads on server, too? Yes, i think. Many people ask to organize it physically. I think also that the process of moving files on server and updating the image references is very hard to develop. There are many plugins out now, which are saving the URLs in their own-created database-tables.

Please check this thread where i explained the problem: https://wordpress.stackexchange.com/questions/226675/physical-organization-of-wordpress-media-library-real-media-library-plugin

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

HTTP response header content disposition for attachments

Try the Content-Disposition header

Content-Disposition: attachment; filename=<file name.ext> 

How can I shrink the drawable on a button?

Using Kotlin Extension

val drawable = ContextCompat.getDrawable(context, R.drawable.my_icon)
// or resources.getDrawable(R.drawable.my_icon, theme)
val sizePx = 25
drawable?.setBounds(0, 0, sizePx, sizePx)
//                            (left,     top,  right, bottom)
my_button.setCompoundDrawables(drawable, null, null, null)

I suggest creating an extension function on TextView (Button extends it) for easy reuse.

button.leftDrawable(R.drawable.my_icon, 25)

// Button extends TextView
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
    val drawable = ContextCompat.getDrawable(context, id)
    val size = context.resources.getDimensionPixelSize(sizeRes)
    drawable?.setBounds(0, 0, size, size)
    this.setCompoundDrawables(drawable, null, null, null)
}

how to create a logfile in php?

Use below function

// Enable error reporting
ini_set('display_errors', 1);
//Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//error_reporting(E_ALL & ~E_NOTICE);
// Tell php where your custom php error log is
ini_set('error_log', 'php_error.log');

$dateTime=date("Y-m-d H:i:s");
$ip= $_SERVER['REMOTE_ADDR'];
$errorString="Error occured on time $dateTime by ip $ip";
$php_error_msg.=$errorString;
// Append the error message to the php-error log
//error_log($php_error_msg);
error_log("A custom error has been triggered",1,"email_address","From: email_address");

Above function will create a log in file php_error with proper description and email will be sent.

React Router Pass Param to Component

Here's typescript version. works on "react-router-dom": "^4.3.1"

export const AppRouter: React.StatelessComponent = () => {
    return (
        <BrowserRouter>
            <Switch>
                <Route exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />} />
                <Route path="/" exact component={App} />
            </Switch>
        </BrowserRouter>
    );
};

and component

export class ProblemPage extends React.Component<ProblemRouteTokens> {

    public render(): JSX.Element {
        return <div>{this.props.problemId}</div>;
    }
}

where ProblemRouteTokens

export interface ProblemRouteTokens { problemId: string; }

require is not defined? Node.js

Point 1: Add require() function calling line of code only in the app.js file or main.js file.

Point 2: Make sure the required package is installed by checking the pacakage.json file. If not updated, run "npm i".

Executing a command stored in a variable from PowerShell

Try invoking your command with Invoke-Expression:

Invoke-Expression $cmd1

Here is a working example on my machine:

$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd

iex is an alias for Invoke-Expression so you could do:

iex $cmd1

For a full list : Visit https://ss64.com/ps/ for more Powershell stuff.

Good Luck...

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

I had a very related issue but for higher Java versions:

$ ./gradlew clean assemble

... <other normal Gradle output>

Could not target platform: 'Java SE 11' using tool chain: 'JDK 8 (1.8)'.

I noticed that the task succeeded when running using InteliJ. Adding a file (same level as build.gradle) called .java-version solved my issue:

 # .java-version
 11.0.3

Authentication issue when debugging in VS2013 - iis express

VS 2015 changes this. It added a .vs folder to my web project and the applicationhost.config was in there. I made the changes suggested (window authentication = true, anon=false) and it started delivering a username instead of a blank.

How to change node.js's console font color?

I've made a file in my snippets directory called styles.js, and I think it might help anybody who wants to import a single file.

It's a small modification to the styles.js file of color.js and has helped me a lot.

Here's the file's contents:

// Original: https://github.com/Marak/colors.js/blob/master/lib/styles.js

const styleCodes = {
    // Reset all styles.
    reset: [0, 0],
    
    // Text styles.
    bold: [1, 22],
    dim: [2, 22],
    italic: [3, 23],
    underline: [4, 24],
    inverse: [7, 27],
    hidden: [8, 28],
    strikethrough: [9, 29],
    
    // Foregound classic colours.
    fgBlack: [30, 39],
    fgRed: [31, 39],
    fgGreen: [32, 39],
    fgYellow: [33, 39],
    fgBlue: [34, 39],
    fgMagenta: [35, 39],
    fgCyan: [36, 39],
    fgWhite: [37, 39],
    fgGray: [90, 39],
    
    // Foreground bright colours.
    fgBrightRed: [91, 39],
    fgBrightGreen: [92, 39],
    fgBrightYellow: [93, 39],
    fgBrightBlue: [94, 39],
    fgBrightMagenta: [95, 39],
    fgBrightCyan: [96, 39],
    fgBrightWhite: [97, 39],

    // Background basic colours.
    bgBlack: [40, 49],
    bgRed: [41, 49],
    bgGreen: [42, 49],
    bgYellow: [43, 49],
    bgBlue: [44, 49],
    bgMagenta: [45, 49],
    bgCyan: [46, 49],
    bgWhite: [47, 49],
    bgGray: [100, 49],
    bgGrey: [100, 49],
    
    // Background bright colours.
    bgBrightRed: [101, 49],
    bgBrightGreen: [102, 49],
    bgBrightYellow: [103, 49],
    bgBrightBlue: [104, 49],
    bgBrightMagenta: [105, 49],
    bgBrightCyan: [106, 49],
    bgBrightWhite: [107, 49],
};

// This object will contain the string representation for all style codes.
const styles = {};

// Loop over all the style codes and assign them to the `styles` object.
// 
// The a `styleCode` in the `styleCodes` object consists of two numbers:
// Index 0: The opening style code (In HTML this can be the opening <b> tag).
// Index 1: The closing style code (In HTML this can be the closing </b> tag).
for (let styleCode of Object.keys(styleCodes)) {
    styles[styleCode] = {
        open: `\x1B[${styleCodes[styleCode][0]}m`,
        close: `\x1B[${styleCodes[styleCode][1]}m`,
    };
}

module.exports = styles;

It's actually quite simple to use.

const styles = require("/path/to/styles.js");

// Let's say we've got an error:
const errorOpen = styles.bold.open + styles.bgRed.open + styles.fgWhite.open;
const errorClose = styles.reset.close; // Close everything
console.log(errorOpen, "ERROR", errorClose, ": Missing semicolon at line 9.");

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 
</shape> 

What is the difference between a deep copy and a shallow copy?

Shallow copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed; for a reference type --> the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type --> a bit-by-bit copy of the field is performed. If a field is a reference type --> a new copy of the referred object is performed. The classes to be cloned must be flagged as [Serializable].

How do I choose grid and block dimensions for CUDA kernels?

There are two parts to that answer (I wrote it). One part is easy to quantify, the other is more empirical.

Hardware Constraints:

This is the easy to quantify part. Appendix F of the current CUDA programming guide lists a number of hard limits which limit how many threads per block a kernel launch can have. If you exceed any of these, your kernel will never run. They can be roughly summarized as:

  1. Each block cannot have more than 512/1024 threads in total (Compute Capability 1.x or 2.x and later respectively)
  2. The maximum dimensions of each block are limited to [512,512,64]/[1024,1024,64] (Compute 1.x/2.x or later)
  3. Each block cannot consume more than 8k/16k/32k/64k/32k/64k/32k/64k/32k/64k registers total (Compute 1.0,1.1/1.2,1.3/2.x-/3.0/3.2/3.5-5.2/5.3/6-6.1/6.2/7.0)
  4. Each block cannot consume more than 16kb/48kb/96kb of shared memory (Compute 1.x/2.x-6.2/7.0)

If you stay within those limits, any kernel you can successfully compile will launch without error.

Performance Tuning:

This is the empirical part. The number of threads per block you choose within the hardware constraints outlined above can and does effect the performance of code running on the hardware. How each code behaves will be different and the only real way to quantify it is by careful benchmarking and profiling. But again, very roughly summarized:

  1. The number of threads per block should be a round multiple of the warp size, which is 32 on all current hardware.
  2. Each streaming multiprocessor unit on the GPU must have enough active warps to sufficiently hide all of the different memory and instruction pipeline latency of the architecture and achieve maximum throughput. The orthodox approach here is to try achieving optimal hardware occupancy (what Roger Dahl's answer is referring to).

The second point is a huge topic which I doubt anyone is going to try and cover it in a single StackOverflow answer. There are people writing PhD theses around the quantitative analysis of aspects of the problem (see this presentation by Vasily Volkov from UC Berkley and this paper by Henry Wong from the University of Toronto for examples of how complex the question really is).

At the entry level, you should mostly be aware that the block size you choose (within the range of legal block sizes defined by the constraints above) can and does have a impact on how fast your code will run, but it depends on the hardware you have and the code you are running. By benchmarking, you will probably find that most non-trivial code has a "sweet spot" in the 128-512 threads per block range, but it will require some analysis on your part to find where that is. The good news is that because you are working in multiples of the warp size, the search space is very finite and the best configuration for a given piece of code relatively easy to find.

How to ORDER BY a SUM() in MySQL?

The problem I see here is that "sum" is an aggregate function.

first, you need to fix the query itself.

Select sum(c_counts + f_counts) total, [column to group sums by]
from table
group by [column to group sums by]

then, you can sort it:

Select *
from (query above) a
order by total

EDIT: But see post by Virat. Perhaps what you want is not the sum of your total fields over a group, but just the sum of those fields for each record. In that case, Virat has the right solution.

java : convert float to String and String to float

Float to string - String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

String to Float - Float.parseFloat()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

Can't find android device using "adb devices" command

I had Xamarin installed and tried to use Unity. Basically in any case you have to kill any application that might be talking to your device through ADB

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

I write out a rule in web.config after $locationProvider.html5Mode(true) is set in app.js.

Hope, helps someone out.

  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

In my index.html I added this to <head>

<base href="/">

Don't forget to install IIS URL Rewrite on server.

Also if you use Web API and IIS, this will work if your API is at www.yourdomain.com/api because of the third input (third line of condition).

java: run a function after a specific number of seconds

you could use the Thread.Sleep() function

Thread.sleep(4000);
myfunction();

Your function will execute after 4 seconds. However this might pause the entire program...

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

I'm going to expand your question a bit and also include the compile function.

  • compile function - use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive. (If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link' attribute is ignored if the 'compile' attribute is defined.)

  • link function - normally use for registering listener callbacks (i.e., $watch expressions on the scope) as well as updating the DOM (i.e., manipulation of iElement = individual instance element). It is executed after the template has been cloned. E.g., inside an <li ng-repeat...>, the link function is executed after the <li> template (tElement) has been cloned (into an iElement) for that particular <li> element. A $watch allows a directive to be notified of scope property changes (a scope is associated with each instance), which allows the directive to render an updated instance value to the DOM.

  • controller function - must be used when another directive needs to interact with this directive. E.g., on the AngularJS home page, the pane directive needs to add itself to the scope maintained by the tabs directive, hence the tabs directive needs to define a controller method (think API) that the pane directive can access/call.

    For a more in-depth explanation of the tabs and pane directives, and why the tabs directive creates a function on its controller using this (rather than on $scope), please see 'this' vs $scope in AngularJS controllers.

In general, you can put methods, $watches, etc. into either the directive's controller or link function. The controller will run first, which sometimes matters (see this fiddle which logs when the ctrl and link functions run with two nested directives). As Josh mentioned in a comment, you may want to put scope-manipulation functions inside a controller just for consistency with the rest of the framework.

npm ERR cb() never called

If you have npm version 5 or above, try this first:

$ sudo npm cache verify

Otherwise:

$ sudo npm cache clean

My node and npm versions are:

$ node -v
v0.10.0

$ npm -v
1.2.14

https://docs.npmjs.com/cli/cache

White spaces are required between publicId and systemId

If you're working from some network that requires you to use a proxy in your browser to connect to the internet (likely an office building), that might be it. I had the same issue and adding the proxy configs to the network settings solved it.

  • Go to your preferences (Eclipse -> Preferences on a Mac, or Window -> Preferences on a Windows)
  • Then -> General -> expand to view the list underneath -> Select Network Connections (don't expand)
  • At the top of the page that appears there is a drop down, select "Manual."
  • Then select "HTTP" in the list directly below the drop down (which now should have all it's options checked) and then click the "Edit" button to the right of the list.
  • Enter in the proxy url and port you need to connect to the internet in your web browser normally.
  • Repeat for "HTTPS."

If you don't know the proxy url and port, talk to your network admin.

Are "while(true)" loops so bad?

It's more of an aesthetics thing, much easier to read code where you explicitly know why the loop will stop right in the declaration of the loop.

angular js unknown provider

This took me way too long to track down. Make sure you minisafe your controller within your directive.

.directive('my_directive', ['injected_item', function (injected_item){

  return {

    controller: ['DO_IT_HERE_TOO', function(DO_IT_HERE_TOO){

    }]
  }
}

Hope that helps

Variably modified array at file scope

If you're going to use the preprocessor anyway, as per the other answers, then you can make the compiler determine the value of NUM_TYPES automagically:

#define NUM_TYPES (sizeof types / sizeof types[0])
static int types[] = { 
  1,
  2, 
  3, 
  4 };

How to uninstall downloaded Xcode simulator?

Slightly off topic but could be very useful as it could be the basis for other tasks you might want to do with simulators.

I like to keep my simulator list to a minimum, and since there is no multi-select in the "Devices and Simulators" it is a pain to delete them all.

So I boot all the sims that I want to use then, remove all the simulators that I don't have booted.

Delete all the shutdown simulators:

xcrun simctl list | grep -w "Shutdown"  | grep -o "([-A-Z0-9]*)" | sed 's/[\(\)]//g' | xargs -I uuid xcrun simctl delete  uuid

If you need individual simulators back, just add them back to the list in "Devices and Simulators" with the plus button.

enter image description here

Eclipse - java.lang.ClassNotFoundException

I had tried all of the solutions on this page: refresh project, rebuild, all projects clean, restart Eclipse, re-import (even) the projects, rebuild maven and refresh. Nothing worked. What did work was copying the class to a new name which runs fine -- bizarre but true.

After putting up with this for some time, I just fixed it by:

  1. Via the Run menu
  2. Select Run Configurations
  3. Choose the run configuration that is associated with your unit test.
  4. Removing the entry from the Run Configuration by pressing delete or clicking the red X.

Something must have been screwed up with the cached run configuration.

What is the main difference between Collection and Collections in Java?

Are you asking about the Collections class versus the classes which implement the Collection interface?

If so, the Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.

The Collection interface defines methods common to structures which hold other objects. List and Set are subinterfaces of Collection, and ArrayList and HashSet are examples of concrete collections.

java howto ArrayList push, pop, shift, and unshift

I was facing with this problem some time ago and I found java.util.LinkedList is best for my case. It has several methods, with different namings, but they're doing what is needed:

push()    -> LinkedList.addLast(); // Or just LinkedList.add();
pop()     -> LinkedList.pollLast();
shift()   -> LinkedList.pollFirst();
unshift() -> LinkedList.addFirst();

how to download file using AngularJS and calling MVC API?

Here you have the angularjs http request to the API that any client will have to do. Just adapt the WS url and params (if you have) to your case. It's a mixture between Naoe's answer and this one:

$http({
    url: '/path/to/your/API',
    method: 'POST',
    params: {},
    headers: {
        'Content-type': 'application/pdf',
    },
    responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
    // TODO when WS success
    var file = new Blob([data], {
        type: 'application/csv'
    });
    //trick to download store a file having its URL
    var fileURL = URL.createObjectURL(file);
    var a = document.createElement('a');
    a.href = fileURL;
    a.target = '_blank';
    a.download = 'yourfilename.pdf';
    document.body.appendChild(a); //create the link "a"
    a.click(); //click the link "a"
    document.body.removeChild(a); //remove the link "a"
}).error(function (data, status, headers, config) {
    //TODO when WS error
});

Explanation of the code:

  1. Angularjs request a file.pdf at the URL: /path/to/your/API.
  2. Success is received on the response
  3. We execute a trick with JavaScript on the front-end:
    • Create an html link ta: <a>.
    • Click the hyperlink <a> tag, using the JS click() function
  4. Remove the html <a> tag, after its click.

How to insert an object in an ArrayList at a specific position

Here is the simple arraylist example for insertion at specific index

ArrayList<Integer> str=new ArrayList<Integer>();
    str.add(0);
    str.add(1);
    str.add(2);
    str.add(3); 
    //Result = [0, 1, 2, 3]
    str.add(1, 11);
    str.add(2, 12);
    //Result = [0, 11, 12, 1, 2, 3]

jQuery Find and List all LI elements within a UL within a specific DIV

$('li[rel=7]').siblings().andSelf();

// or:

$('li[rel=7]').parent().children();

Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:

var rels = [];

$('ul').each(function() {
    var localRels = [];

    $(this).find('li').each(function(){
        localRels.push( $(this).attr('rel') );
    });

    rels.push(localRels);
});

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

It appears that you are using the default route which is defined as this:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

The key part of that route is the {id} piece. If you look at your action method, your parameter is k instead of id. You need to change your action method to this so that it matches the route parameter:

// change int k to int id
public ActionResult DetailsData(int id)

If you wanted to leave your parameter as k, then you would change the URL to be:

http://localhost:7317/Employee/DetailsData?k=4

You also appear to have a problem with your connection string. In your web.config, you need to change your connection string to this (provided by haim770 in another answer that he deleted):

<connectionStrings>
  <add name="EmployeeContext"
       connectionString="Server=.;Database=mytry;integrated security=True;"
       providerName="System.Data.SqlClient" />
</connectionStrings>

How to dynamically add rows to a table in ASP.NET?

public partial class result : System.Web.UI.Page
{
    static DataTable table1 = new DataTable("Shashank");
    static DataSet set = new DataSet("office");


    protected void Page_Load(object sender, EventArgs e)
    {
        lblEmployeeNumber.Text = HttpContext.Current.Request.Form["txtEmployeeNumber"];
        lblFirstName.Text = Request.Form["txtFirstName"];
        lblLastName.Text = Request.Form["txtLastName"];
        lblTitle.Text = Request.Form["txtTitle"];

        Int32 Rcount = Convert.ToInt32(table1.Rows.Count);

        if (Rcount == 0)
        {

            table1.Columns.Add("ID");
            table1.Columns.Add("FName");
            table1.Columns.Add("LName");
            table1.Columns.Add("Title");
            table1.Rows.Add(lblEmployeeNumber.Text, lblFirstName.Text, lblLastName.Text, lblTitle.Text);
            set.Tables.Add(table1);
        }
        else
        {
            if (lblEmployeeNumber.Text != "")
            {
                DataRow dr = table1.NewRow();
                dr["ID"] = lblEmployeeNumber.Text;
                dr["FName"] = lblFirstName.Text;
                dr["LName"] = lblLastName.Text;
                dr["Title"] = lblTitle.Text;
                table1.Rows.Add(dr);
            }
        }

        gvrEmp.DataSource = set;
        gvrEmp.DataBind();

    }
}

Simple way to sort strings in the (case sensitive) alphabetical order

The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html

private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
        public int compare(String str1, String str2) {
            return ComparisonChain.start().
                                compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
                                compare(str1,str2).
                                result();
         }
 };
Collections.sort(list, stringAlphabeticalComparator);

The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:

"AA","Aa","aa","Development","development"

Inverse of matrix in R

You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package

Python Checking a string's first and last character

You are testing against the string minus the last character:

>>> '"xxx"'[:-1]
'"xxx'

Note how the last character, the ", is not part of the output of the slice.

I think you wanted just to test against the last character; use [-1:] to slice for just the last element.

However, there is no need to slice here; just use str.startswith() and str.endswith() directly.

Cross field validation with Hibernate Validator (JSR 303)

I made a small adaptation in Nicko's solution so that it is not necessary to use the Apache Commons BeanUtils library and replace it with the solution already available in spring, for those using it as I can be simpler:

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(final FieldMatch constraintAnnotation) {
        firstFieldName = constraintAnnotation.first();
        secondFieldName = constraintAnnotation.second();
    }

    @Override
    public boolean isValid(final Object object, final ConstraintValidatorContext context) {

        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
        final Object firstObj = beanWrapper.getPropertyValue(firstFieldName);
        final Object secondObj = beanWrapper.getPropertyValue(secondFieldName);

        boolean isValid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);

        if (!isValid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                .addPropertyNode(firstFieldName)
                .addConstraintViolation();
        }

        return isValid;

    }
}

Perform commands over ssh with Python

All have already stated (recommended) using paramiko and I am just sharing a python code (API one may say) that will allow you to execute multiple commands in one go.

to execute commands on different node use : Commands().run_cmd(host_ip, list_of_commands)

You will see one TODO, which I have kept to stop the execution if any of the commands fails to execute, I don't know how to do it. please share your knowledge

#!/usr/bin/python

import os
import sys
import select
import paramiko
import time


class Commands:
    def __init__(self, retry_time=0):
        self.retry_time = retry_time
        pass

    def run_cmd(self, host_ip, cmd_list):
        i = 0
        while True:
        # print("Trying to connect to %s (%i/%i)" % (self.host, i, self.retry_time))
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(host_ip)
            break
        except paramiko.AuthenticationException:
            print("Authentication failed when connecting to %s" % host_ip)
            sys.exit(1)
        except:
            print("Could not SSH to %s, waiting for it to start" % host_ip)
            i += 1
            time.sleep(2)

        # If we could not connect within time limit
        if i >= self.retry_time:
            print("Could not connect to %s. Giving up" % host_ip)
            sys.exit(1)
        # After connection is successful
        # Send the command
        for command in cmd_list:
            # print command
            print "> " + command
            # execute commands
            stdin, stdout, stderr = ssh.exec_command(command)
            # TODO() : if an error is thrown, stop further rules and revert back changes
            # Wait for the command to terminate
            while not stdout.channel.exit_status_ready():
                # Only print data if there is data to read in the channel
                if stdout.channel.recv_ready():
                    rl, wl, xl = select.select([ stdout.channel ], [ ], [ ], 0.0)
                    if len(rl) > 0:
                        tmp = stdout.channel.recv(1024)
                        output = tmp.decode()
                        print output

        # Close SSH connection
        ssh.close()
        return

def main(args=None):
    if args is None:
        print "arguments expected"
    else:
        # args = {'<ip_address>', <list_of_commands>}
        mytest = Commands()
        mytest.run_cmd(host_ip=args[0], cmd_list=args[1])
    return


if __name__ == "__main__":
    main(sys.argv[1:])

Thank you!

AWS S3 CLI - Could not connect to the endpoint URL

In case it is not working in your default region, try providing a region close to you. This worked for me:

   PS C:\Users\shrig> aws  configure
   AWS Access Key ID [****************C]:**strong text**
   AWS Secret Access Key [****************WD]:
   Default region name [us-east1]: ap-south-1
   Default output format [text]:

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

This can also happen if data model is out of date.

Hopefully this will save someone else frustration :)

How to do relative imports in Python?

Everyone seems to want to tell you what you should be doing rather than just answering the question.

The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.

From PEP 328:

Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change.

Update: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.

How to preview an image before and after upload?

Try this: (For Preview)

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

<body>
    <form id="form1" runat="server">
        <input type="file" onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </form>
</body>

Working Demo here>

How to display svg icons(.svg files) in UI using React Component?

Just write require with path inside the src of image. it will work. like:

<img alt="Clock" src={require('../assets/images/search_icon.svg')}/>

Scheduled run of stored procedure on SQL server

I'll add one thing: where I'm at we used to have a bunch of batch jobs that ran every night. However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job. There are (at least) three reasons for this:

  1. We have some console programs that need to run every night as well. This way all scheduled tasks can be in one place. Of course, this creates a single point of failure, but if the console jobs don't run we're gonna lose a day's work the next day anyway.
  2. The program that kicks off the jobs captures print messages and errors from the server and writes them to a common application log for all our batch processes. It makes logging from withing the sql jobs much simpler.
  3. If we ever need to upgrade the server (and we are hoping to do this soon) we don't need to worry about moving the jobs over. Just re-point the application once.

It's a real short VB.Net app: I can post code if any one is interested.

Java Error: "Your security settings have blocked a local application from running"

Java applets do create a security risk, hence are disabled in most modern browsers. You have to lower the security to run it. There is a guide by Oracle for that.

Java 8 lambda Void argument

Add a static method inside your functional interface

package example;

interface Action<T, U> {
       U execute(T t);
       static  Action<Void,Void> invoke(Runnable runnable){
           return (v) -> {
               runnable.run();
                return null;
            };         
       }
    }

public class Lambda {


    public static void main(String[] args) {

        Action<Void, Void> a = Action.invoke(() -> System.out.println("Do nothing!"));
        Void t = null;
        a.execute(t);
    }

}

Output

Do nothing!

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

Little known: the GO sql statement can take an integer for the number of times to repeat previous command.

So if you:

ALTER DATABASE [DATABASENAME] SET SINGLE_USER
GO

Then:

USE [DATABASENAME]
GO 2000

This will repeat the USE command 2000 times, force deadlock on all other connections, and take ownership of the single connection. (Giving your query window sole access to do as you wish.)

Simple DateTime sql query

select getdate()

O/P
----
2011-05-25 17:29:44.763

select convert(varchar(30),getdate(),131) >= '12/04/2011 12:00:00 AM'

O/P
---
22/06/1432  5:29:44:763PM

How to detect escape key press with pure JS or jQuery?

On Firefox 78 use this ("keypress" doesn't work for Escape key):

function keyPress (e)(){
  if (e.key == "Escape"){
     //do something here      
  }
document.addEventListener("keyup", keyPress);

How can I merge two commits into one if I already started rebase?

If your master branch git log looks something like following:

commit ac72a4308ba70cc42aace47509a5e
Author: <[email protected]>
Date:   Tue Jun 11 10:23:07 2013 +0500

    Added algorithms for Cosine-similarity

commit 77df2a40e53136c7a2d58fd847372
Author: <[email protected]>
Date:   Tue Jun 11 13:02:14 2013 -0700

    Set stage for similar objects

commit 249cf9392da197573a17c8426c282
Author: Ralph <[email protected]>
Date:   Thu Jun 13 16:44:12 2013 -0700

    Fixed a bug in space world automation

and you want to merge the top two commits just do following easy steps:

  1. First to be on safe side checkout the second last commit in a separate branch. You can name the branch anything. git checkout 77df2a40e53136c7a2d58fd847372 -b merged-commits
  2. Now, just cherry-pick your changes from the last commit into this new branch as: git cherry-pick -n -x ac72a4308ba70cc42aace47509a5e. (Resolve conflicts if arise any)
  3. So now, your changes in last commit are there in your second last commit. But you still have to commit, so first add the changes you just cherry-picked and then execute git commit --amend.

That's it. You may push this merged version in branch "merged-commits" if you like.

Also, you can discard the back-to-back two commits in your master branch now. Just update your master branch as:

git checkout master
git reset --hard origin/master (CAUTION: This command will remove any local changes to your master branch)
git pull

Converting string format to datetime in mm/dd/yyyy

You are looking for the DateTime.Parse() method (MSDN Article)

So you can do:

var dateTime = DateTime.Parse("01/01/2001");

Which will give you a DateTime typed object.

If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)

Which you would use in a situation like this (Where you are using a British style date format):

string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);

SVN: Is there a way to mark a file as "do not commit"?

I would instead write a helper bash script that runs svn commit on all the files you need to and none of the ones you don't. This way you have much more control.

For example, with one line, you can commit all files with extension .h and .cpp to which you made changes (and which wouldn't cause a conflict):

svn commit -m "" `svn status | grep "^M.*[h|cpp]$" | awk '{print $2}' | tr "\\n" " "`

Change / add extensions to the [h|cpp] part. Add a log message in between the quotes of -m "" if needed.

How do I get the coordinates of a mouse click on a canvas element?

According to fresh Quirksmode the clientX and clientY methods are supported in all major browsers. So, here it goes - the good, working code that works in a scrolling div on a page with scrollbars:

function getCursorPosition(canvas, event) {
var x, y;

canoffset = $(canvas).offset();
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - Math.floor(canoffset.left);
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - Math.floor(canoffset.top) + 1;

return [x,y];
}

This also requires jQuery for $(canvas).offset().

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

From the proxy_pass documentation:

A special case is using variables in the proxy_pass statement: The requested URL is not used and you are fully responsible to construct the target URL yourself.

Since you're using $1 in the target, nginx relies on you to tell it exactly what to pass. You can fix this in two ways. First, stripping the beginning of the uri with a proxy_pass is trivial:

location /service/ {
  # Note the trailing slash on the proxy_pass.
  # It tells nginx to replace /service/ with / when passing the request.
  proxy_pass http://apache/;
}

Or if you want to use the regex location, just include the args:

location ~* ^/service/(.*) {
  proxy_pass http://apache/$1$is_args$args;
}

View google chrome's cached pictures

This page contains all the cached urls

chrome://cache

Unfortunately to actually see the file you have to select everything on the page and paste it in this tool: http://www.sensefulsolutions.com/2012/01/viewing-chrome-cache-easy-way.html

How do I get the first n characters of a string without checking the size or going out of bounds?

String upToNCharacters = String.format("%."+ n +"s", str);

Awful if n is a variable (so you must construct the format string), but pretty clear if a constant:

String upToNCharacters = String.format("%.10s", str);

docs

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

How to prevent text in a table cell from wrapping

Have a look at the white-space property, used like this:

th {
    white-space: nowrap;
}

This will force the contents of <th> to display on one line.

From linked page, here are the various options for white-space:

normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at preserved newline characters.

nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.

pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

Are email addresses case sensitive?

I know this is an old question but I just want to comment here: To any extent email addresses ARE case sensitive, most users would be "very unwise" to actively use an email address that requires capitals. They would soon stop using the address because they'd be missing a lot of their mail. (Unless they have a specific reason to make things difficult, and they expect mail only from specific senders they know.)

That's because imperfect humans as well as imperfect software exist, (Surprise!) which will assume all email is lowercase, and for this reason these humans and software will send messages using a "lower cased version" of the address regardless of how it was provided to them. If the recipient is unable to receive such messages, it won't be long before they notice they're missing a lot, and switch to a lowercase-only email address, or get their server set up to be case-insensitive.

How Spring Security Filter Chain works

UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

No, UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter, and this contains a RequestMatcher, that means you can define your own processing url, this filter only handle the RequestMatcher matches the request url, the default processing url is /login.

Later filters can still handle the request, if the UsernamePasswordAuthenticationFilter executes chain.doFilter(request, response);.

More details about core fitlers

Does the form-login namespace element auto-configure these filters?

UsernamePasswordAuthenticationFilter is created by <form-login>, these are Standard Filter Aliases and Ordering

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

It depends on whether the before fitlers are successful, but FilterSecurityInterceptor is the last fitler normally.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, every fitlerChain has a RequestMatcher, if the RequestMatcher matches the request, the request will be handled by the fitlers in the fitler chain.

The default RequestMatcher matches all request if you don't config the pattern, or you can config the specific url (<http pattern="/rest/**").

If you want to konw more about the fitlers, I think you can check source code in spring security. doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)

Mount current directory as a volume in Docker on Windows 10

For Git Bash for Windows (in ConEmu), the following works for me (for Docker Windows containers):

docker run --rm -it -v `pwd -W`:c:/api microsoft/dotnet:2-runtime

Note the backticks/backquotes around pwd -W!

With all other variations of PWD I've tried I've received: "Error response from daemon: invalid volume specification: ..."

Update: The above was for Docker Windows containers, for Linux containers use:

docker run --rm -it -v `pwd -W`:/api -p 8080:80 microsoft/aspnetcore:2

check if "it's a number" function in Oracle

I'm against using when others so I would use (returning an "boolean integer" due to SQL not suppporting booleans)

create or replace function is_number(param in varchar2) return integer
 is
   ret number;
 begin
    ret := to_number(param);
    return 1; --true
 exception
    when invalid_number then return 0;
 end;

In the SQL call you would use something like

select case when ( is_number(myTable.id)=1 and (myTable.id >'0') ) 
            then 'Is a number greater than 0' 
            else 'it is not a number or is not greater than 0' 
       end as valuetype  
  from table myTable

What is the most efficient way to concatenate N arrays?

Here is a function by which you can concatenate multiple number of arrays

function concatNarrays(args) {
    args = Array.prototype.slice.call(arguments);
    var newArr = args.reduce( function(prev, next) {
       return prev.concat(next) ;
    });

    return newArr;
}

Example -

console.log(concatNarrays([1, 2, 3], [5, 2, 1, 4], [2,8,9]));

will output

[1,2,3,5,2,1,4,2,8,9]

How do I create a URL shortener?

Why not just translate your id to a string? You just need a function that maps a digit between, say, 0 and 61 to a single letter (upper/lower case) or digit. Then apply this to create, say, 4-letter codes, and you've got 14.7 million URLs covered.

CMD what does /im (taskkill)?

im is "image process name" example /f /im notepad.exe is specified to kill image process name (program) notepad.exe

How to create an integer array in Python?

Use the array module. With it you can store collections of the same type efficiently.

>>> import array
>>> import itertools
>>> a = array_of_signed_ints = array.array("i", itertools.repeat(0, 10))

For more information - e.g. different types, look at the documentation of the array module. For up to 1 million entries this should feel pretty snappy. For 10 million entries my local machine thinks for 1.5 seconds.

The second parameter to array.array is a generator, which constructs the defined sequence as it is read. This way, the array module can consume the zeros one-by-one, but the generator only uses constant memory. This generator does not get bigger (memory-wise) if the sequence gets longer. The array will grow of course, but that should be obvious.

You use it just like a list:

>>> a.append(1)
>>> a.extend([1, 2, 3])
>>> a[-4:]
array('i', [1, 1, 2, 3])
>>> len(a)
14

...or simply convert it to a list:

>>> l = list(a)
>>> len(l)
14

Surprisingly

>>> a = [0] * 10000000

is faster at construction than the array method. Go figure! :)

Tab separated values in awk

echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk -v var="test" 'BEGIN { FS = "[ \t]+" } ; { print $1 "\t" var "\t" $3 }'

Convert a negative number to a positive one in JavaScript

If you'd like to write interesting code that nobody else can ever update, try this:

~--x

SQLAlchemy: print the actual query

I would like to point out that the solutions given above do not "just work" with non-trivial queries. One issue I came across were more complicated types, such as pgsql ARRAYs causing issues. I did find a solution that for me, did just work even with pgsql ARRAYs:

borrowed from: https://gist.github.com/gsakkis/4572159

The linked code seems to be based on an older version of SQLAlchemy. You'll get an error saying that the attribute _mapper_zero_or_none doesn't exist. Here's an updated version that will work with a newer version, you simply replace _mapper_zero_or_none with bind. Additionally, this has support for pgsql arrays:

# adapted from:
# https://gist.github.com/gsakkis/4572159
from datetime import date, timedelta
from datetime import datetime

from sqlalchemy.orm import Query


try:
    basestring
except NameError:
    basestring = str


def render_query(statement, dialect=None):
    """
    Generate an SQL expression string with bound parameters rendered inline
    for the given SQLAlchemy statement.
    WARNING: This method of escaping is insecure, incomplete, and for debugging
    purposes only. Executing SQL statements with inline-rendered user values is
    extremely insecure.
    Based on http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
    """
    if isinstance(statement, Query):
        if dialect is None:
            dialect = statement.session.bind.dialect
        statement = statement.statement
    elif dialect is None:
        dialect = statement.bind.dialect

    class LiteralCompiler(dialect.statement_compiler):

        def visit_bindparam(self, bindparam, within_columns_clause=False,
                            literal_binds=False, **kwargs):
            return self.render_literal_value(bindparam.value, bindparam.type)

        def render_array_value(self, val, item_type):
            if isinstance(val, list):
                return "{%s}" % ",".join([self.render_array_value(x, item_type) for x in val])
            return self.render_literal_value(val, item_type)

        def render_literal_value(self, value, type_):
            if isinstance(value, long):
                return str(value)
            elif isinstance(value, (basestring, date, datetime, timedelta)):
                return "'%s'" % str(value).replace("'", "''")
            elif isinstance(value, list):
                return "'{%s}'" % (",".join([self.render_array_value(x, type_.item_type) for x in value]))
            return super(LiteralCompiler, self).render_literal_value(value, type_)

    return LiteralCompiler(dialect, statement).process(statement)

Tested to two levels of nested arrays.

Importing project into Netbeans

Since you already have all the files in a folder, say "Project", you simply have to open Netbeans and go to File -> Open Project (or Ctrl + Shift+ O on Windows) and then from the dialog box navigate to the folder containing the Folder "Project".

You will see in the dialog box of Netbeans a 'Java cup'. Well, that's your project.

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
    

Allow Access-Control-Allow-Origin header using HTML5 fetch API

Look at https://expressjs.com/en/resources/middleware/cors.html You have to use cors.

Install:

$ npm install cors
const cors = require('cors');
app.use(cors());

You have to put this code in your node server.

How do you convert an entire directory with ffmpeg?

And for Windows, this does not work

FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec mp3 "%~nG.mp3"

even if I do double those %.

I would even suggest:

-acodec ***libmp3lame***

also:

FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec libmp3lame "%~nG.mp3"

Take multiple lists into dataframe

Adding to above answers, we can create on the fly

df= pd.DataFrame()
list1 = list(range(10))
list2 = list(range(10,20))
df['list1'] = list1
df['list2'] = list2
print(df)

hope it helps !

Is there any way to specify a suggested filename when using data: URI?

There is a tiny workaround script on Google Code that worked for me:

http://code.google.com/p/download-data-uri/

It adds a form with the data in it, submits it and then removes the form again. Hacky, but it did the job for me. Requires jQuery.

This thread showed up in Google before the Google Code page and I thought it might be helpful to have the link in here, too.

Limit number of characters allowed in form input text field

<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);"  placeholder="MobileNumber">

<script>
function checkNumber(key) {
  console.log(key);
  var inputNumber = document.querySelector("#MobileNumber").value;
  if(key.key >= 0 && key.key <= 9) {
    inputNumber += key.key;
  }
  else {
    key.preventDefault();
  }
}
</script>

How can I get the corresponding table header (th) from a table cell (td)?

var $th = $td.closest('tbody').prev('thead').find('> tr > th:eq(' + $td.index() + ')');

Or a little bit simplified

var $th = $td.closest('table').find('th').eq($td.index());

How do you get the width and height of a multi-dimensional array?

// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10

Git on Windows: How do you set up a mergetool?

For IntelliJ IDEA (Community Edition) 3-way git mergetool configuration in Windows environment (~/.gitconfig)

Cygwin

[mergetool "ideamerge"]
     cmd = C:/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe merge `cygpath -wa $LOCAL` `cygpath -wa $REMOTE` `cygpath -wa $BASE` `cygpath -wa $MERGED`
[merge]
     tool = ideamerge

Msys

[mergetool "ideamerge"]
cmd = "/c/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe" merge `~/winpath.sh $LOCAL` `~/winpath.sh $REMOTE` `~/winpath.sh $BASE` `~/winpath.sh $MERGED`
[merge]
 tool = ideamerge

The ~/winpath.sh is to convert paths to Windows on msys and is taken from msys path conversion question on stackoverflow

#! /bin/sh                                                               

function wpath {                                                         
    if [ -z "$1" ]; then                                                 
        echo "$@"                                                        
    else                                                                 
        if [ -f "$1" ]; then                                             
            local dir=$(dirname "$1")                                    
            local fn=$(basename "$1")                                    
            echo "$(cd "$dir"; echo "$(pwd -W)/$fn")" | sed 's|/|\\|g';  
        else                                                             
            if [ -d "$1" ]; then                                         
                echo "$(cd "$1"; pwd -W)" | sed 's|/|\\|g';              
            else                                                         
                echo "$1" | sed 's|^/\(.\)/|\1:\\|g; s|/|\\|g';          
            fi                                                           
        fi                                                               
    fi                                                                   
}                                                                        

wpath "$@" 

Adding options to a <select> using jQuery?

How about this

var numbers = [1, 2, 3, 4, 5];
var option = '';

for (var i=0;i<numbers.length;i++){
     option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
    }

    $('#items').append(option);

What is time_t ultimately a typedef to?

[root]# cat time.c

#include <time.h>

int main(int argc, char** argv)
{
        time_t test;
        return 0;
}

[root]# gcc -E time.c | grep __time_t

typedef long int __time_t;

It's defined in $INCDIR/bits/types.h through:

# 131 "/usr/include/bits/types.h" 3 4
# 1 "/usr/include/bits/typesizes.h" 1 3 4
# 132 "/usr/include/bits/types.h" 2 3 4

Check if a string matches a regex in Bash script

In bash version 3 you can use the '=~' operator:

if [[ "$date" =~ ^[0-9]{8}$ ]]; then
    echo "Valid date"
else
    echo "Invalid date"
fi

Reference: http://tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF

NOTE: The quoting in the matching operator within the double brackets, [[ ]], is no longer necessary as of Bash version 3.2

Count number of occurrences of a pattern in a file (even on same line)

Try this:

grep "string to search for" FileNameToSearch | cut -d ":" -f 4 | sort -n | uniq -c

Sample:

grep "SMTP connect from unknown" maillog | cut -d ":" -f 4 | sort -n | uniq -c
  6  SMTP connect from unknown [188.190.118.90]
 54  SMTP connect from unknown [62.193.131.114]
  3  SMTP connect from unknown [91.222.51.253]

Where are static methods and static variables stored in Java?

In addition to the Thomas's answer , static variable are stored in non heap area which is called Method Area.

jQuery Mobile: document ready vs. page events

jQuery Mobile 1.4 Update:

My original article was intended for old way of page handling, basically everything before jQuery Mobile 1.4. Old way of handling is now deprecated and it will stay active until (including) jQuery Mobile 1.5, so you can still use everything mentioned below, at least until next year and jQuery Mobile 1.6.

Old events, including pageinit don't exist any more, they are replaced with pagecontainer widget. Pageinit is erased completely and you can use pagecreate instead, that event stayed the same and its not going to be changed.

If you are interested in new way of page event handling take a look here, in any other case feel free to continue with this article. You should read this answer even if you are using jQuery Mobile 1.4 +, it goes beyond page events so you will probably find a lot of useful information.

Older content:

This article can also be found as a part of my blog HERE.

$(document).on('pageinit') vs $(document).ready()

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate. Because of this $(document).ready() will trigger before your first page is loaded and every code intended for page manipulation will be executed after a page refresh. This can be a very subtle bug. On some systems it may appear that it works fine, but on others it may cause erratic, difficult to repeat weirdness to occur.

Classic jQuery syntax:

$(document).ready(function() {

});

To solve this problem (and trust me this is a problem) jQuery Mobile developers created page events. In a nutshell page events are events triggered in a particular point of page execution. One of those page events is a pageinit event and we can use it like this:

$(document).on('pageinit', function() {

});

We can go even further and use a page id instead of document selector. Let's say we have jQuery Mobile page with an id index:

<div data-role="page" id="index">
    <div data-theme="a" data-role="header">
        <h3>
            First Page
        </h3>
        <a href="#second" class="ui-btn-right">Next</a>
    </div>

    <div data-role="content">
        <a href="#" data-role="button" id="test-button">Test button</a>
    </div>

    <div data-theme="a" data-role="footer" data-position="fixed">

    </div>
</div>

To execute code that will only available to the index page we could use this syntax:

$('#index').on('pageinit', function() {

});

Pageinit event will be executed every time page is about be be loaded and shown for the first time. It will not trigger again unless page is manually refreshed or Ajax page loading is turned off. In case you want code to execute every time you visit a page it is better to use pagebeforeshow event.

Here's a working example: http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem.

Few more notes on this question. No matter if you are using 1 html multiple pages or multiple HTML files paradigm it is advised to separate all of your custom JavaScript page handling into a single separate JavaScript file. This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobile application.

There's also another special jQuery Mobile event and it is called mobileinit. When jQuery Mobile starts, it triggers a mobileinit event on the document object. To override default settings, bind them to mobileinit. One of a good examples of mobileinit usage is turning off Ajax page loading, or changing default Ajax loader behavior.

$(document).on("mobileinit", function(){
  //apply overrides here
});

Page events transition order

First all events can be found here: http://api.jquerymobile.com/category/events/

Lets say we have a page A and a page B, this is a unload/load order:

  1. page B - event pagebeforecreate

  2. page B - event pagecreate

  3. page B - event pageinit

  4. page A - event pagebeforehide

  5. page A - event pageremove

  6. page A - event pagehide

  7. page B - event pagebeforeshow

  8. page B - event pageshow

For better page events understanding read this:

  • pagebeforeload, pageload and pageloadfailed are fired when an external page is loaded
  • pagebeforechange, pagechange and pagechangefailed are page change events. These events are fired when a user is navigating between pages in the applications.
  • pagebeforeshow, pagebeforehide, pageshow and pagehide are page transition events. These events are fired before, during and after a transition and are named.
  • pagebeforecreate, pagecreate and pageinit are for page initialization.
  • pageremove can be fired and then handled when a page is removed from the DOM

Page loading jsFiddle example: http://jsfiddle.net/Gajotres/QGnft/

If AJAX is not enabled, some events may not fire.

Prevent page transition

If for some reason page transition needs to be prevented on some condition it can be done with this code:

$(document).on('pagebeforechange', function(e, data){
    var to = data.toPage,
        from = data.options.fromPage;

    if (typeof to  === 'string') {
        var u = $.mobile.path.parseUrl(to);
        to = u.hash || '#' + u.pathname.substring(1);
        if (from) from = '#' + from.attr('id');

        if (from === '#index' && to === '#second') {
            alert('Can not transition from #index to #second!');
            e.preventDefault();
            e.stopPropagation();

            // remove active status on a button, if transition was triggered with a button
            $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus ui-btn');;
        }
    }
});

This example will work in any case because it will trigger at a begging of every page transition and what is most important it will prevent page change before page transition can occur.

Here's a working example:

Prevent multiple event binding/triggering

jQuery Mobile works in a different way than classic web applications. Depending on how you managed to bind your events each time you visit some page it will bind events over and over. This is not an error, it is simply how jQuery Mobile handles its pages. For example, take a look at this code snippet:

$(document).on('pagebeforeshow','#index' ,function(e,data){
    $(document).on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/CCfL4/

Each time you visit page #index click event will is going to be bound to button #test-button. Test it by moving from page 1 to page 2 and back several times. There are few ways to prevent this problem:

Solution 1

Best solution would be to use pageinit to bind events. If you take a look at an official documentation you will find out that pageinit will trigger ONLY once, just like document ready, so there's no way events will be bound again. This is best solution because you don't have processing overhead like when removing events with off method.

Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/

This working solution is made on a basis of a previous problematic example.

Solution 2

Remove event before you bind it:

$(document).on('pagebeforeshow', '#index', function(){
    $(document).off('click', '#test-button').on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/

Solution 3

Use a jQuery Filter selector, like this:

$('#carousel div:Event(!click)').each(function(){
    //If click is not bind to #carousel div do something
});

Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/

In a nutshell, if speed is your main concern then Solution 2 is much better than Solution 1.

Solution 4

A new one, probably an easiest of them all.

$(document).on('pagebeforeshow', '#index', function(){
    $(document).on('click', '#test-button',function(e) {
        if(e.handled !== true) // This will prevent event triggering more than once
        {
            alert('Clicked');
            e.handled = true;
        }
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/

Tnx to the sholsinger for this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/

pageChange event quirks - triggering twice

Sometimes pagechange event can trigger twice and it does not have anything to do with the problem mentioned before.

The reason the pagebeforechange event occurs twice is due to the recursive call in changePage when toPage is not a jQuery enhanced DOM object. This recursion is dangerous, as the developer is allowed to change the toPage within the event. If the developer consistently sets toPage to a string, within the pagebeforechange event handler, regardless of whether or not it was an object an infinite recursive loop will result. The pageload event passes the new page as the page property of the data object (This should be added to the documentation, it's not listed currently). The pageload event could therefore be used to access the loaded page.

In few words this is happening because you are sending additional parameters through pageChange.

Example:

<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="#care-plan-view?id=9e273f31-2672-47fd-9baa-6c35f093a800&amp;name=Sat"><h3>Sat</h3></a>

To fix this problem use any page event listed in Page events transition order.

Page Change Times

As mentioned, when you change from one jQuery Mobile page to another, typically either through clicking on a link to another jQuery Mobile page that already exists in the DOM, or by manually calling $.mobile.changePage, several events and subsequent actions occur. At a high level the following actions occur:

  • A page change process is begun
  • A new page is loaded
  • The content for that page is “enhanced” (styled)
  • A transition (slide/pop/etc) from the existing page to the new page occurs

This is a average page transition benchmark:

Page load and processing: 3 ms

Page enhance: 45 ms

Transition: 604 ms

Total time: 670 ms

*These values are in milliseconds.

So as you can see a transition event is eating almost 90% of execution time.

Data/Parameters manipulation between page transitions

It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.

Reference: https://stackoverflow.com/a/13932240/1848600

Solution 1:

You can pass values with changePage:

$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });

And read them like this:

$(document).on('pagebeforeshow', "#index", function (event, data) {
    var parameters = $(this).data("url").split("?")[1];;
    parameter = parameters.replace("parameter=","");
    alert(parameter);
});

Example:

index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
    <script>_x000D_
        $(document).on('pagebeforeshow', "#index",function () {_x000D_
            $(document).on('click', "#changePage",function () {_x000D_
                $.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });_x000D_
            });_x000D_
        });_x000D_
_x000D_
        $(document).on('pagebeforeshow', "#second",function () {_x000D_
            var parameters = $(this).data("url").split("?")[1];;_x000D_
            parameter = parameters.replace("parameter=","");_x000D_
            alert(parameter);_x000D_
        });_x000D_
    </script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="index">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                First Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
          <a data-role="button" id="changePage">Test</a>_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

second.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="second">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                Second Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Solution 2:

Or you can create a persistent JavaScript object for a storage purpose. As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

var storeObject = {
    firstname : '',
    lastname : ''
}

Example: http://jsfiddle.net/Gajotres/9KKbx/

Solution 3:

You can also access data from the previous page like this:

$(document).on('pagebeforeshow', '#index',function (e, data) {
    alert(data.prevPage.attr('id'));
});

prevPage object holds a complete previous page.

Solution 4:

As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.

if(typeof(Storage)!=="undefined") {
    localStorage.firstname="Dragan";
    localStorage.lastname="Gaic";
}

Example: http://jsfiddle.net/Gajotres/J9NTr/

Probably best solution but it will fail in some versions of iOS 5.X. It is a well know error.

Don’t Use .live() / .bind() / .delegate()

I forgot to mention (and tnx andleer for reminding me) use on/off for event binding/unbinding, live/die and bind/unbind are deprecated.

The .live() method of jQuery was seen as a godsend when it was introduced to the API in version 1.3. In a typical jQuery app there can be a lot of DOM manipulation and it can become very tedious to hook and unhook as elements come and go. The .live() method made it possible to hook an event for the life of the app based on its selector. Great right? Wrong, the .live() method is extremely slow. The .live() method actually hooks its events to the document object, which means that the event must bubble up from the element that generated the event until it reaches the document. This can be amazingly time consuming.

It is now deprecated. The folks on the jQuery team no longer recommend its use and neither do I. Even though it can be tedious to hook and unhook events, your code will be much faster without the .live() method than with it.

Instead of .live() you should use .on(). .on() is about 2-3x faster than .live(). Take a look at this event binding benchmark: http://jsperf.com/jquery-live-vs-delegate-vs-on/34, everything will be clear from there.

Benchmarking:

There's an excellent script made for jQuery Mobile page events benchmarking. It can be found here: https://github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js. But before you do anything with it I advise you to remove its alert notification system (each “change page” is going to show you this data by halting the app) and change it to console.log function.

Basically this script will log all your page events and if you read this article carefully (page events descriptions) you will know how much time jQm spent of page enhancements, page transitions ....

Final notes

Always, and I mean always read official jQuery Mobile documentation. It will usually provide you with needed information, and unlike some other documentation this one is rather good, with enough explanations and code examples.

Changes:

  • 30.01.2013 - Added a new method of multiple event triggering prevention
  • 31.01.2013 - Added a better clarification for chapter Data/Parameters manipulation between page transitions
  • 03.02.2013 - Added new content/examples to the chapter Data/Parameters manipulation between page transitions
  • 22.05.2013 - Added a solution for page transition/change prevention and added links to the official page events API documentation
  • 18.05.2013 - Added another solution against multiple event binding

What is special about /dev/tty?

The 'c' means it's a character special file.

Is there a php echo/print equivalent in javascript

You can use document.write or even console.write (this is good for debugging).

But your best bet and it gives you more control is to use DOM to update the page.

The Import android.support.v7 cannot be resolved

  1. Go to your project in the navigator, right click on properties.

  2. Go to the Java Build Path tab on the left.

  3. Go to the libraries tab on top.

  4. Click add external jars.

  5. Go to your ADT Bundle folder, go to sdk/extras/android/support/v7/appcompat/libs.

  6. Select the file android-support-v7-appcompat.jar

  7. Go to order and export and check the box next to your new jar.

  8. Click ok.

Change a HTML5 input's placeholder color with CSS

For SASS/SCSS user using Bourbon, it has a built-in function.

//main.scss
@import 'bourbon';

input {
  width: 300px;

  @include placeholder {
    color: red;
  }
}

CSS Output, you can also grab this portion and paste into your code.

//main.css

input {
  width: 300px;
}

input::-webkit-input-placeholder {
  color: red;
}
input:-moz-placeholder {
  color: red;
}
input::-moz-placeholder {
  color: red;
}
input:-ms-input-placeholder {
  color: red;
}

What is the difference between linear regression and logistic regression?

In linear regression the outcome is continuous whereas in logistic regression, the outcome has only a limited number of possible values(discrete).

example: In a scenario,the given value of x is size of a plot in square feet then predicting y ie rate of the plot comes under linear regression.

If, instead, you wanted to predict, based on size, whether the plot would sell for more than 300000 Rs, you would use logistic regression. The possible outputs are either Yes, the plot will sell for more than 300000 Rs, or No.

Laravel 5 Clear Views Cache

use Below command in terminal

php artisan cache:clear
php artisan route:cache 
php artisan config:cache 
php artisan view:clear

What are the differences between a HashMap and a Hashtable in Java?

There is many good answer already posted. I'm adding few new points and summarizing it.

HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys. But there are many differences between HashMap and Hashtable classes that are given below.

HashMap

  1. HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.
  2. HashMap allows one null key and multiple null values.
  3. HashMap is a new class introduced in JDK 1.2.
  4. HashMap is fast.
  5. We can make the HashMap as synchronized by calling this code
    Map m = Collections.synchronizedMap(HashMap);
  6. HashMap is traversed by Iterator.
  7. Iterator in HashMap is fail-fast.
  8. HashMap inherits AbstractMap class.

Hashtable

  1. Hashtable is synchronized. It is thread-safe and can be shared with many threads.
  2. Hashtable doesn't allow any null key or value.
  3. Hashtable is a legacy class.
  4. Hashtable is slow.
  5. Hashtable is internally synchronized and can't be unsynchronized.
  6. Hashtable is traversed by Enumerator and Iterator.
  7. Enumerator in Hashtable is not fail-fast.
  8. Hashtable inherits Dictionary class.

Further reading What is difference between HashMap and Hashtable in Java?

enter image description here

Formatting numbers (decimal places, thousands separators, etc) with CSS

The CSS working group has publish a Draft on Content Formatting in 2008. But nothing new right now.

How to get autocomplete in jupyter notebook without using tab?

As mentioned by @physicsGuy above, You can use the hinterland extension. Simple steps to do it.

Installing nbextension using conda forge channel. Simply run the below command in conda terminal:

conda install -c conda-forge jupyter_nbextensions_configurator

Next Step enabling the hinterland extension. Run the below command in conda terminal:

jupyter nbextension enable hinterland/hinterland

That's it, done.

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

As sklearn.cross_validation module was deprecated, you can use:

import numpy as np
from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5)

X_trn, X_tst, y_trn, y_tst = train_test_split(X, y, test_size=0.2, random_state=42)

How to convert wstring into string?

As Cubbi pointed out in one of the comments, std::wstring_convert (C++11) provides a neat simple solution (you need to #include <locale> and <codecvt>):

std::wstring string_to_convert;

//setup converter
using convert_type = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_type, wchar_t> converter;

//use converter (.to_bytes: wstr->str, .from_bytes: str->wstr)
std::string converted_str = converter.to_bytes( string_to_convert );

I was using a combination of wcstombs and tedious allocation/deallocation of memory before I came across this.

http://en.cppreference.com/w/cpp/locale/wstring_convert

update(2013.11.28)

One liners can be stated as so (Thank you Guss for your comment):

std::wstring str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes("some string");

Wrapper functions can be stated as so: (Thank you ArmanSchwarz for your comment)

std::wstring s2ws(const std::string& str)
{
    using convert_typeX = std::codecvt_utf8<wchar_t>;
    std::wstring_convert<convert_typeX, wchar_t> converterX;

    return converterX.from_bytes(str);
}

std::string ws2s(const std::wstring& wstr)
{
    using convert_typeX = std::codecvt_utf8<wchar_t>;
    std::wstring_convert<convert_typeX, wchar_t> converterX;

    return converterX.to_bytes(wstr);
}

Note: there's some controversy on whether string/wstring should be passed in to functions as references or as literals (due to C++11 and compiler updates). I'll leave the decision to the person implementing, but it's worth knowing.

Note: I'm using std::codecvt_utf8 in the above code, but if you're not using UTF-8 you'll need to change that to the appropriate encoding you're using:

http://en.cppreference.com/w/cpp/header/codecvt

How to determine one year from now in Javascript

As setYear() is deprecated, correct variant is:

// plus 1 year
new Date().setFullYear(new Date().getFullYear() + 1)
// plus 1 month
new Date().setMonth(new Date().getMonth() + 1)
// plus 1 day
new Date().setDate(new Date().getDate() + 1)

All examples return Unix timestamp, if you want to get Date object - just wrap it with another new Date(...)

SQL Query to find the last day of the month

declare @date datetime;
set @date = getdate(); -- or some date
select dateadd(month,1+datediff(month,0,@date),-1);

What is a 'Closure'?

Kyle's answer is pretty good. I think the only additional clarification is that the closure is basically a snapshot of the stack at the point that the lambda function is created. Then when the function is re-executed the stack is restored to that state before executing the function. Thus as Kyle mentions, that hidden value (count) is available when the lambda function executes.

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

OSX -bash: composer: command not found

Tested on Mac OSX after installing via instructions on composer website:

sudo mv composer.phar /usr/local/bin/composer

How to delete Project from Google Developers Console

Simply go to https://console.developers.google.com/iam-admin/projects you must be signed in of course. There you will see the all your projects google console projects so just select the project you want to delete, and click delete project option which is shown at the top of the table. I have provided the screenshothere

Show DialogFragment with animation growing from a point

DialogFragment has a public getTheme() method that you can over ride for this exact reason. This solution uses less lines of code:

public class MyCustomDialogFragment extends DialogFragment{
    ...
    @Override
    public int getTheme() {
        return R.style.MyThemeWithCustomAnimation;
    }
}

Running Git through Cygwin from Windows

I can tell you from personal experience this is a bad idea. Native Windows programs cannot accept Cygwin paths. For example with Cygwin you might run a command

grep -r --color foo /opt

with no issue. With Cygwin / represents the root directory. Native Windows programs have no concept of this, and will likely fail if invoked this way. You should not mix Cygwin and Native Windows programs unless you have no other choice.

Uninstall what Git you have and install the Cygwin git package, save yourself the headache.

How do I preserve line breaks when getting text from a textarea?

Here is an idea as you may have multiple newline in a textbox:

 var text=document.getElementById('post-text').value.split('\n');
 var html = text.join('<br />');

This HTML value will preserve newline. Hope this helps.

Jenkins Pipeline Wipe Out Workspace

Currently both deletedir() and cleanWs() do not work properly when using Jenkins kubernetes plugin, the pod workspace is deleted but the master workspace persists

it should not be a problem for persistant branches, when you have a step to clean the workspace prior to checkout scam. It will basically reuse the same workspace over and over again: but when using multibranch pipelines the master keeps the whole workspace and git directory

I believe this should be an issue with Jenkins, any enlightenment here?

jQuery : select all element with custom attribute

Use the "has attribute" selector:

$('p[MyTag]')

Or to select one where that attribute has a specific value:

$('p[MyTag="Sara"]')

There are other selectors for "attribute value starts with", "attribute value contains", etc.

@ variables in Ruby on Rails

A local variable is only accessible from within the block of it's initialization. Also a local variable begins with a lower case letter (a-z) or underscore (_).

And instance variable is an instance of self and begins with a @ Also an instance variable belongs to the object itself. Instance variables are the ones that you perform methods on i.e. .send etc

example:

@user = User.all

The @user is the instance variable

And Uninitialized instance variables have a value of Nil

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

Assign a variable inside a Block to a variable outside a Block

Just a reminder of a mistake I made myself too, the

 __block

declaration must be done when first declaring the variable, that is, OUTSIDE of the block, not inside of it. This should resolve problems mentioned in the comments about the variable not retaining its value outside of the block.

Decode UTF-8 with Javascript

You should take decodeURI for it.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI

As simple as this:

decodeURI('https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B');
// "https://developer.mozilla.org/ru/docs/JavaScript_?????"

Consider to use it inside try catch block for not missing an URIError.

Also it has full browsers support.

MySql difference between two timestamps in days?

SELECT DATEDIFF(max_date, min_date) as days from my table. This works even if the col max_date and min_date are in string data types.

Looping through GridView rows and Checking Checkbox Control

you have to iterate gridview Rows

for (int count = 0; count < grd.Rows.Count; count++)
{
    if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
    {     
      ((Label)grd.Rows[count].FindControl("labelID")).Text
    }
}

javac is not recognized as an internal or external command, operable program or batch file

Check your environment variables.

In my case I had JAVA_HOME set in the System variables as well as in my User Account variables and the latter was set to a wrong version of Java. I also had the same problem with the Path variable.

After deleting JAVA_HOME from my User Account variables and removing the wrong path from the Path variable it worked correctly.

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

I had a the same problem and I found the solution that I should put the code to retrieve the drop down list from database in the Edit Method. It worked for me. Solution for the similar problem

Disable automatic sorting on the first column when using jQuery DataTables

In the newer version of datatables (version 1.10.7) it seems things have changed. The way to prevent DataTables from automatically sorting by the first column is to set the order option to an empty array.

You just need to add the following parameter to the DataTables options:

"order": [] 

Set up your DataTable as follows in order to override the default setting:

$('#example').dataTable( {
    "order": [],
    // Your other options here...
} );

That will override the default setting of "order": [[ 0, 'asc' ]].

You can find more details regarding the order option here: https://datatables.net/reference/option/order

How do you determine a processing time in Python?

You can implement two tic() and tac() functions, where tic() captures the time which it is called, and tac() prints the time difference since tic() was called. Here is a short implementation:

import time

_start_time = time.time()

def tic():
    global _start_time 
    _start_time = time.time()

def tac():
    t_sec = round(time.time() - _start_time)
    (t_min, t_sec) = divmod(t_sec,60)
    (t_hour,t_min) = divmod(t_min,60) 
    print('Time passed: {}hour:{}min:{}sec'.format(t_hour,t_min,t_sec))

Now in your code you can use it as:

tic()
do_some_stuff()
tac()

and it will, for example, output:

Time passed: 0hour:7min:26sec

See also:

Maven parent pom vs modules pom

From my experience and Maven best practices there are two kinds of "parent poms"

  • "company" parent pom - this pom contains your company specific information and configuration that inherit every pom and doesn't need to be copied. These informations are:

    • repositories
    • distribution managment sections
    • common plugins configurations (like maven-compiler-plugin source and target versions)
    • organization, developers, etc

    Preparing this parent pom need to be done with caution, because all your company poms will inherit from it, so this pom have to be mature and stable (releasing a version of parent pom should not affect to release all your company projects!)

  • second kind of parent pom is a multimodule parent. I prefer your first solution - this is a default maven convention for multi module projects, very often represents VCS code structure

The intention is to be scalable to a large scale build so should be scalable to a large number of projects and artifacts.

Mutliprojects have structure of trees - so you aren't arrown down to one level of parent pom. Try to find a suitable project struture for your needs - a classic exmample is how to disrtibute mutimodule projects

distibution/
documentation/
myproject/
  myproject-core/
  myproject-api/
  myproject-app/
  pom.xml
pom.xml

A few bonus questions:

  • Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).

This configuration has to be wisely splitted into a "company" parent pom and project parent pom(s). Things related to all you project go to "company" parent and this related to current project go to project one's.

  • How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?

Company parent pom have to be released first. For multiprojects standard rules applies. CI server need to know all to build the project correctly.

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

As mentioned in comments, this is a scoping issue. Specifically, $con is not in scope within your getPosts function.

You should pass your connection object in as a dependency, eg

function getPosts(mysqli $con) {
    // etc

I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");

getPosts($con);

Understanding dict.copy() - shallow or deep?

Contents are shallow copied.

So if the original dict contains a list or another dictionary, modifying one them in the original or its shallow copy will modify them (the list or the dict) in the other.

Elasticsearch query to return all records

elasticsearch(ES) supports both a GET or a POST request for getting the data from the ES cluster index.

When we do a GET:

http://localhost:9200/[your index name]/_search?size=[no of records you want]&q=*:*

When we do a POST:

http://localhost:9200/[your_index_name]/_search
{
  "size": [your value] //default 10
  "from": [your start index] //default 0
  "query":
   {
    "match_all": {}
   }
}   

I would suggest to use a UI plugin with elasticsearch http://mobz.github.io/elasticsearch-head/ This will help you get a better feeling of the indices you create and also test your indices.

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

Concatenating two std::vectors

std::vector<int> first;
std::vector<int> second;

first.insert(first.end(), second.begin(), second.end());

TypeError: sequence item 0: expected string, int found

Replace

values = ",".join(value_list)

with

values = ','.join([str(i) for i in value_list])

OR

values = ','.join(str(value_list)[1:-1])

Is there a Python equivalent to Ruby's string interpolation?

String interpolation is going to be included with Python 3.6 as specified in PEP 498. You will be able to do this:

name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')

Note that I hate Spongebob, so writing this was slightly painful. :)

Execute a SQL Stored Procedure and process the results

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1

sqlConnection1.Open()

Dim adapter As System.Data.SqlClient.SqlDataAdapter
Dim dsdetailwk As New DataSet

Try
   adapter = New System.Data.SqlClient.SqlDataAdapter
   adapter.SelectCommand = cmd
   adapter.Fill(dsdetailwk, "delivery")
   Catch Err As System.Exception
End Try

sqlConnection1.Close()

datagridview1.DataSource = dsdetailwk.Tables(0)

How to get current date in jquery?

Since the question is tagged as JQuery:

If you are also using JQuery UI you can use $.datepicker.formatDate():

$.datepicker.formatDate('yy/mm/dd', new Date());

See this demo.

How to make Firefox headless programmatically in Selenium with Python?

To invoke Firefox Browser headlessly, you can set the headless property through Options() class as follows:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True
driver = webdriver.Firefox(options=options, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://google.com/")
print ("Headless Firefox Initialized")
driver.quit()

There's another way to accomplish headless mode. If you need to disable or enable the headless mode in Firefox, without changing the code, you can set the environment variable MOZ_HEADLESS to whatever if you want Firefox to run headless, or don't set it at all.

This is very useful when you are using for example continuous integration and you want to run the functional tests in the server but still be able to run the tests in normal mode in your PC.

$ MOZ_HEADLESS=1 python manage.py test # testing example in Django with headless Firefox

or

$ export MOZ_HEADLESS=1   # this way you only have to set it once
$ python manage.py test functional/tests/directory
$ unset MOZ_HEADLESS      # if you want to disable headless mode

Outro

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

Working with TIFFs (import, export) in Python using numpy

In case of image stacks, I find it easier to use scikit-image to read, and matplotlib to show or save. I have handled 16-bit TIFF image stacks with the following code.

from skimage import io
import matplotlib.pyplot as plt

# read the image stack
img = io.imread('a_image.tif')
# show the image
plt.imshow(mol,cmap='gray')
plt.axis('off')
# save the image
plt.savefig('output.tif', transparent=True, dpi=300, bbox_inches="tight", pad_inches=0.0)

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

If any one is interested here is what query is executed by psql on postgres 9.1:

SELECT n.nspname as "Schema",
  p.proname as "Name",
  pg_catalog.pg_get_function_result(p.oid) as "Result data type",
  pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
 CASE
  WHEN p.proisagg THEN 'agg'
  WHEN p.proiswindow THEN 'window'
  WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
  ELSE 'normal'
 END as "Type"
FROM pg_catalog.pg_proc p
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE pg_catalog.pg_function_is_visible(p.oid)
      AND n.nspname <> 'pg_catalog'
      AND n.nspname <> 'information_schema'
ORDER BY 1, 2, 4;

You can get what psql runs for a backslash command by running psql with the -E flag.

How to remove youtube branding after embedding video in web page?

You can add ?modestbranding=1 to your url. That will remove the logo.

modestbranding (supported players: AS3, HTML5)

This parameter lets you use a YouTube player that does not show a YouTube logo. Set the parameter value to 1 to prevent the YouTube logo from displaying in the control bar. Note that a small YouTube text label will still display in the upper-right corner of a paused video when the user's mouse pointer hovers over the player.

&showinfo=0 will remove the title bar.

showinfo (supported players: AS3, AS2, HTML5)

Values: 0 or 1. The parameter's default value is 1. If you set the parameter value to 0, then the player will not display information like the video title and uploader before the video starts playing.

You can find all options on the Google Developers website.

Note:

It doesn't fully remove the logo. There is still a small logo on the bottom left.

showinfo is deprecated and will be ignored after September 25, 2018: https://developers.google.com/youtube/player_parameters

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

I suggest you use TO_CHAR() when converting to string. In order to do that, you need to build a date first.

SELECT TO_CHAR(TO_DATE(DAY||'-'||MONTH||'-'||YEAR, 'dd-mm-yyyy'), 'dd-mm-yyyy') AS FORMATTED_DATE
FROM
    (SELECT EXTRACT( DAY FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy')
        FROM DUAL
        )) AS DAY, TO_NUMBER(EXTRACT( MONTH FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )), 09) AS MONTH, EXTRACT(YEAR FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )) AS YEAR
    FROM DUAL
    );

Python: Pandas Dataframe how to multiply entire column with a scalar

Here's the answer after a bit of research:

df.loc[:,'quantity'] *= -1 #seems to prevent SettingWithCopyWarning 

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

it's also a good thing to make sure you have the right import

I had an issue like that and I found out that the bean was using

    javax.faces.view.ViewScoped;
                 ^

instead of

    javax.faces.bean.ViewScoped;
                 ^

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

You can do it easily with puse CSS without any kind of JS. you have to add position: sticky; top: 0; z-index:999; in table th . But this won't work on Chrome Browser but other browser. To work on chrome you have to add those code in table thead th

_x000D_
_x000D_
.table-fixed {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
/*This will work on every browser but Chrome Browser*/_x000D_
.table-fixed thead {_x000D_
  position: sticky;_x000D_
  position: -webkit-sticky;_x000D_
  top: 0;_x000D_
  z-index: 999;_x000D_
  background-color: #000;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
/*This will work on every browser*/_x000D_
.table-fixed thead th {_x000D_
    position: sticky;_x000D_
    position: -webkit-sticky;_x000D_
    top: 0;_x000D_
    z-index: 999;_x000D_
    background-color: #000;_x000D_
    color: #fff;_x000D_
}
_x000D_
<table class="table-fixed">_x000D_
  <thead>_x000D_
    <tr>_x000D_
        <th>Table Header 1</th>_x000D_
        <th>Table Header 2</th>_x000D_
        <th>Table Header 3</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
        <td>Data</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Hook up Raspberry Pi via Ethernet to laptop without router?

It's a solution for Ubuntu (the idea also works for Windows or Mac) I just tried today and it works like a charm.

Material

  1. a cross-over Ethernet cable (the name is fancy but it's just a normal Ethernet cable)
  2. a laptop (ubuntu)
  3. a Raspberry Pi (I have the Pi2)

Prerequisites on your ubuntu

  1. Install network-manager

    $sudo apt-get install network-manager

  2. Install nmap

    $sudo apt-get install nmap

Edit Wired connection on your laptop (Ubuntu)

  1. Change IpV4 settings to "Share to other computers"
  2. Save the setting
  3. Reboot your laptop

Share WiFi connection of your laptop via Ethernet crossover cable

  1. Hook up your RPi with your laptop using the Ethernet cable

  2. Look up the broadcast address of the Ethernet connection (Laptop),

$/sbin/ifconfig eth1 | grep "Bcast" | awk -F: '{print $3}' | awk '{print $1}' 10.42.0.255

  1. Use this address to find out the IP address of your RPi, it's 10.42.0.96 in my case because 10.42.0.1 is my laptop

    $nmap -n -sP 10.42.0.255/24

  Starting Nmap 6.40 ( http://nmap.org ) at 2016-02-20 23:07 CET
  Nmap scan report for 10.42.0.1
  Host is up (0.00031s latency).
  Nmap scan report for 10.42.0.96
  Host is up (0.0023s latency).
  Nmap done: 256 IP addresses (2 hosts up) scanned in 2.71 seconds
  1. Login to your RPi from your laptop (-Y with X-forwarding)

    $ssh -Y [email protected]

  2. Lo and behold! Now your RPi is connected to your laptop and RPi can share the WiFi connection.

    pi@raspberrypi ~ $

Share display & keyboard of your laptop with RPi

  1. Install vncserver on Raspberry Pi

    $ sudo apt-get update

    $ sudo apt-get install tightvncserver

  2. Install vncviewer on your laptop by downloading RealVNC (it supports multiple platforms) http://www.realvnc.com/download/vnc/

  3. To be able to copy & paste from VNC server <--> VNC viewer, you need to install autocutsel on your RPi.

$sudo apt-get install autocutsel

If this site doesn't work, try to download the .deb directly from a mirror site, e.g. mirror.hmc.edu/debian/pool/main/a/autocutsel/autocutsel_0.10.0-1_armhf.deb
and install it

$sudo dpkg -i autocutsel_0.10.0-1_armhf.deb

  1. Start vncserver on your RPi (You have to restart vncserver after installing autocutsel, you can issue $vncserver -kill :1)

    $vncserver :1

  2. Add autocutsel -fork to /home/pi/.vnc/xstartup

 #!/bin/sh
 xrdb $HOME/.Xresources xsetroot -solid grey 
 autocutsel -fork
 #x-terminal-emulator -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" &
 #x-window-manager &
 # Fix to make GNOME work 
 export XKL_XMODMAP_DISABLE=1 
 /etc/X11/Xsession
  1. Start vncviewer on your laptop

    $vncviewer

  2. A vncviewer window will pop up and type in the IP address of your RPi (given by your laptop) followed by port 1, which is your VNC server. for example: 10.42.0.96:1 in my case.

  3. Connect it to the vncserver hosted on your RPi by typing in a password (set up a password yourself)

    12.Now you can see the desktop of RPi on your laptop, and I opened my browser to show the shared WiFi connection is working as well.

See Raspberry Pi desktop on your ubuntu

Measure execution time for a Java method

Check this: System.currentTimeMillis.

With this you can calculate the time of your method by doing:

long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;

Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--    

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
</head>
<body>

<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
Address:        <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form> 
</p>
</pre>
</body>
</html>

Mongoose query where value is not null

$ne

selects the documents where the value of the field is not equal to the specified value. This includes documents that do not contain the field.

User.find({ "username": { "$ne": 'admin' } })

$nin

$nin selects the documents where: the field value is not in the specified array or the field does not exist.

User.find({ "groups": { "$nin": ['admin', 'user'] } })

How to change indentation in Visual Studio Code?

Code Formatting Shortcut:

VSCode on Windows - Shift + Alt + F

VSCode on MacOS - Shift + Option + F

VSCode on Ubuntu - Ctrl + Shift + I

You can also customize this shortcut using preference setting if needed.

column selection with keyboard Ctrl + Shift + Alt + Arrow

PHP CURL DELETE request

My own class request with wsse authentication

class Request {

    protected $_url;
    protected $_username;
    protected $_apiKey;

    public function __construct($url, $username, $apiUserKey) {
        $this->_url = $url;     
        $this->_username = $username;
        $this->_apiKey = $apiUserKey;
    }

    public function getHeader() {
        $nonce = uniqid();
        $created = date('c');
        $digest = base64_encode(sha1(base64_decode($nonce) . $created . $this->_apiKey, true));

        $wsseHeader = "Authorization: WSSE profile=\"UsernameToken\"\n";
        $wsseHeader .= sprintf(
            'X-WSSE: UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"', $this->_username, $digest, $nonce, $created
        );

        return $wsseHeader;
    }

    public function curl_req($path, $verb=NULL, $data=array()) {                    

        $wsseHeader[] = "Accept: application/vnd.api+json";
        $wsseHeader[] = $this->getHeader();

        $options = array(
            CURLOPT_URL => $this->_url . $path,
            CURLOPT_HTTPHEADER => $wsseHeader,
            CURLOPT_RETURNTRANSFER => true, 
            CURLOPT_HEADER => false             
        );                  

        if( !empty($data) ) {
            $options += array(
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_SAFE_UPLOAD => true
            );                          
        }

        if( isset($verb) ) {
            $options += array(CURLOPT_CUSTOMREQUEST => $verb);                          
        }

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);                   

        if(false === $result ) {
            echo curl_error($ch);
        }
        curl_close($ch);

        return $result; 
    }
}

How do I import a specific version of a package using go get?

There's a go edit -replace command to append a specific commit (even from another forked repository) on top of the current version of a package. What's cool about this option, is that you don't need to know the exact pseudo version beforehand, just the commit hash id.

For example, I'm using the stable version of package "github.com/onsi/ginkgo v1.8.0".

Now I want - without modifying this line of required package in go.mod - to append a patch from my fork, on top of the ginkgo version:

$ GO111MODULE="on"  go mod edit -replace=github.com/onsi/ginkgo=github.com/manosnoam/ginkgo@d6423c2

After the first time you build or test your module, GO will try to pull the new version, and then generate the "replace" line with the correct pseudo version. For example in my case, it will add on the bottom of go.mod:

replace github.com/onsi/ginkgo => github.com/manosnoam/ginkgo v0.0.0-20190902135631-1995eead7451

Find child element in AngularJS directive

In your link function, do this:

// link function
function (scope, element, attrs) {
  var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}

Also, in your link function, don't name your scope variable using a $. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.

Commenting out code blocks in Atom

CTRL+/ on windows, no need to select whole line, Just use key combination on line which you want to comment out.

How can I store JavaScript variable output into a PHP variable?

If this is related to a form submission, use a hidden inputinside the form and change the hidden input value to this variable value. Then you can get that hidden input value in the php page and assign it to your php variable after form submission.

Update:

According to your edit, it seems you don't understand how javascript and php works. Javascript is a client side language, and php is a serverside language. Therefore you cannot execute javascript logic and use that variable value to a php variable when you execute relevant page in the server. You can run the relevant javascript logic after client browser process the web page returned from the web server (which has already executed the php code for the relevant page). After the execution of the javascript code and after assigning the relevant value to the relevant javascript variable, you can use form submission or ajax to send that javascript variable value to use by another php page (or a request to process and get the same php page).

How to open generated pdf using jspdf in new window

This solution working for me

window.open(doc.output('bloburl'))

Starting Docker as Daemon on Ubuntu

I had the same issue on 14.04 with docker 1.9.1.

The upstart service command did work when I used sudo, even though I was root:

$ whoami
root
$ service docker status
status: Unbekannter Auftrag: docker

$ sudo service docker status
docker start/running, process 7394

It seems to depend on the environment variables.

service docker status works when becoming root with su -, but not when only using su:

$ su
Password:
$ service docker status
status: unknown job: docker
$ exit
$ su -
Password:
$ service docker status
docker start/running, process 2342

How does Google calculate my location on a desktop?

Rejecting the WiFi networks idea!

Sorry folks... I don't see it. Using WiFi networks around you seems to be a highly inaccurate and ineffective method of collecting data. WiFi networks these days simply don't stay long in one place.

Think about it, the WiFi networks change every day. Not to mention MiFi and Adhoc networks which are "designed" to be mobile and travel with the users. Equipment breaks, network settings change, people move... Relying on "WiFi Networks" in your area seems highly inaccurate and in the end may not even offer a significant improvement in granularity over IP lookup.

I think the idea that iPhone users are "scanning and sending" the WiFi survey data back to google, and the wardriving, perhaps in conjunction with the Google Maps "Street View" mapping might seem like a very possible method of collecting this data however, in practicality, it does not work as a business model.

Oh and btw, I forgot to mention in my prior post... when I originally pulled my location the time I was pinpointed "precisely" on the map I was connecting to a router from my desktop over an ethernet connection. I don't have a WiFi card on my desktop.

So if that "nearby WiFi networks" theory was true... then I shouldn't have been able to pinpoint my location with such precision.

I'll call my ISP, SKyrim, and ask them as to whether they share their network topology to enable geolocation on their networks.

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

The best way to understand is to simply think from top to bottom ( Large Desktops to Mobile Phones)

Firstly, as B3 is mobile first so if you use xs then the columns will be same from Large desktops to xs ( i recommend using xs or sm as this will keep everything the way you want on every screen size )

Secondly if you want to give different width to columns on different devices or resolutions, than you can add multiple classes e.g

the above will change the width according to the screen resolutions, REMEMBER i am keeping the total columns in each class = 12

I hope my answer would help!

What is the best way to left align and right align two div tags?

use padding tags the above float tags didnt worked out, I used

padding left:5px; 



padding left :30px

If...Then...Else with multiple statements after Then

Multiple statements are to be separated by a new line:

If SkyIsBlue Then
  StartEngines
  Pollute
ElseIf SkyIsRed Then
  StopAttack
  Vent
ElseIf SkyIsYellow Then
  If Sunset Then
    Sleep
  ElseIf Sunrise or IsMorning Then
    Smoke
    GetCoffee
  Else
    Error
  End If
Else
  Joke
  Laugh
End If

Determine Pixel Length of String in Javascript/jQuery?

I don't believe you can do just a string, but if you put the string inside of a <span> with the correct attributes (size, font-weight, etc); you should then be able to use jQuery to get the width of the span.

<span id='string_span' style='font-weight: bold; font-size: 12'>Here is my string</span>
<script>
  $('#string_span').width();
</script>

How do I store data in local storage using Angularjs?

You can use localStorage for the purpose.

Steps:

  1. add ngStorage.min.js in your file
  2. add ngStorage dependency in your module
  3. add $localStorage module in your controller
  4. use $localStorage.key = value

How to describe table in SQL Server 2008?

You can use sp_columns, a stored procedure for describing the table.

exec sp_columns TableName

You can also use sp_help.

What is the "hasClass" function with plain JavaScript?

What do you think about this approach?

<body class="thatClass anotherClass"> </body>

var bodyClasses = document.querySelector('body').className;
var myClass = new RegExp("thatClass");
var trueOrFalse = myClass.test( bodyClasses );

https://jsfiddle.net/5sv30bhe/

Binding a Button's visibility to a bool value in ViewModel

Generally there are two ways to do it, a converter class or a property in the Viewmodel that essentially converts the value for you.

I tend to use the property approach if it is a one off conversion. If you want to reuse it, use the converter. Below, find an example of the converter:

<ValueConversion(GetType(Boolean), GetType(Visibility))> _
Public Class BoolToVisibilityConverter
    Implements IValueConverter

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert

        If value IsNot Nothing Then
            If value = True Then 
                Return Visibility.Visible
            Else
                Return Visibility.Collapsed
            End If
        Else
            Return Visibility.Collapsed
        End If
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException
    End Function
End Class

A ViewModel property method would just check the boolean property value, and return a visibility based on that. Be sure to implement INotifyPropertyChanged and call it on both the Boolean and Visibility properties to updated properly.

PHP date yesterday

How easy :)

date("F j, Y", strtotime( '-1 days' ) );

Example:

echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43

Output:

2018-07-17 07:02:43

Is key-value pair available in Typescript?

Not for the questioner, but for all others, which are interested: See: How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The solution is therefore:

let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;

Cheers!

Best Regular Expression for Email Validation in C#

Updated answer for 2019.

Regex object is thread-safe for Matching functions. Knowing that and there are some performance options or cultural / language issues, I propose this simple solution.

public static Regex _regex = new Regex(
    @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
    RegexOptions.CultureInvariant | RegexOptions.Singleline);

public static bool IsValidEmailFormat(string emailInput)
{
    return _regex.IsMatch(emailInput);
}

Alternative Configuration for Regex:

public static Regex _regex = new Regex(
    @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
    RegexOptions.CultureInvariant | RegexOptions.Compiled);

I find that compiled is only faster on big string matches, like book parsing for example. Simple email matching is faster just letting Regex interpret.

Thread Safety And Regex
Regex Best Practices

Including an anchor tag in an ASP.NET MVC Html.ActionLink

There are overloads of ActionLink which take a fragment parameter. Passing "section12" as your fragment will get you the behavior you're after.

For example, calling LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object):

<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>

Purpose of #!/usr/bin/python3 shebang

This line helps find the program executable that will run the script. This shebang notation is fairly standard across most scripting languages (at least as used on grown-up operating systems).

An important aspect of this line is specifying which interpreter will be used. On many development-centered Linux distributions, for example, it is normal to have several versions of python installed at the same time.

Python 2.x and Python 3 are not 100% compatible, so this difference can be very important. So #! /usr/bin/python and #! /usr/bin/python3 are not the same (and neither are quite the same as #! /usr/bin/env python3 as noted elsewhere on this page.

How to save select query results within temporary table?

In Sqlite:

CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

Increasing the maximum number of TCP/IP connections in Linux

There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.

More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:

  • Check if your TCP window setting is large enough. Linux defaults are good for everything except really fast inet link (hundreds of mbps) or fast satellite links. What is your bandwidth*delay product?
  • Check for packet loss using ping with large packets (ping -s 1472 ...)
  • Check for rate limiting. On Linux, this is configured with tc
  • Confirm that the bandwidth you think exists actually exists using e.g., iperf
  • Confirm that your protocol is sane. Remember latency.
  • If this is a gigabit+ LAN, can you use jumbo packets? Are you?

Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat or lsof). If that number is substantial, you might:

  • Have a lot of bandwidth, e.g., 100mbps+. In this case, you may actually need to up the ulimit -n. Still, ~1000 connections (default on my system) is quite a few.
  • Have network problems which are slowing down your connections (e.g., packet loss)
  • Have something else slowing you down, e.g., IO bandwidth, especially if you're seeking. Have you checked iostat -x?

Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.

I hope this provides some help. You're really asking a networking question.

Is it possible to print a variable's type in standard C++?

Very ugly but does the trick if you only want compile time info (e.g. for debugging):

auto testVar = std::make_tuple(1, 1.0, "abc");
decltype(testVar)::foo= 1;

Returns:

Compilation finished with errors:
source.cpp: In function 'int main()':
source.cpp:5:19: error: 'foo' is not a member of 'std::tuple<int, double, const char*>'

Create a File object in memory from a string in Java

Usually when a method accepts a file, there's another method nearby that accepts a stream. If this isn't the case, the API is badly coded. Otherwise, you can use temporary files, where permission is usually granted in many cases. If it's applet, you can request write permission.

An example:

try {
    // Create temp file.
    File temp = File.createTempFile("pattern", ".suffix");

    // Delete temp file when program exits.
    temp.deleteOnExit();

    // Write to temp file
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write("aString");
    out.close();
} catch (IOException e) {
}

Migrating from VMWARE to VirtualBox

After many attempts I was finally able to get this working. Essentially what I did was download and use the vmware converter to merge the two disks into one. After that I was able to attach the newly created disk to VitrualBox.

The steps involved are very simple:

BEFORE YOU DO ANYTHING!

1) MAKE A BACKUP!!! Even if you follow these instruction, you could screw things up, so make a backup. Just shutdown the VM and then make a copy of the directory where VM resides.

2) Uninstall VMware Tools from the VM that you are going to convert. If for some reason you forget this step, you can still uninstall it after getting everything running under VirtualBox by following these steps. Do yourself the favor and just do it now.

NOW THE FUN PART!!!

1) Download and install the VMware Converter. I used 5.0.1 build-875114, just use the latest.

2) Download and install VirtualBox

3) Fire up VMWare convertor:

Fire up VMWare convertor

4) Click on Convert machine

6) Browse to the .vmx for your VM and click Next.

Convert machine

7) Give the new VM a name and select the location where you want to put it. Click Next

Give the new VM a name and select the location

8) Click Next on the Options screen. You shouldn't have to change anything here.

Click <code>Next</code> on the <code>Options</code> screen.

9) Click Finish on the Summary screen to begin the conversion.

Click <code>Finish</code> on the <code>Summary</code> screen

10) The conversion should start. This will take a LOOONG time so be patient.

The conversion should start.

11) Hopefully all went well, if it did, you should see that the conversion is completed:

conversion is completed

12) Now open up VirtualBox and click New.

open up VirtualBox and click <code>New</code>

13) Give your VM a name and select what Type and Version it is. Click Next.

Give your VM a name and select what <code>Type</code> and <code>Version</code> it is.

14) Select the size of the memory you want to give it. Click Next.

Select the size of the memory you want to give it.

15) For the Hard Drive, click Use and existing hard drive file and select the newly converted .vmdk file.

Use and existing hard drive file

16) Now Click Settings and select the Storage menu. The issue is that by default VirtualBox will add the drive as an IDE. This won't work and we need as we need to put it on a SCSI controller.

put it on a SCSI controller

17) Select the IDE controller and the Remove Controller button.

Select the IDE controller and the <code>Remove Controller</code> button.

18) Now click the Add Controller button and select Add SCSI Controller

Add SCSI Controller

19) Click the Add Hard Disk button.

Add Hard Disk

20) Click Choose existing disk

Choose existing disk

21) Select your .vmdk file. Click OK

Select your <code>.vmdk</code> file.

22) Select the System menu.

Select the <code>System</code> menu.

23) Click Enable IO APIC. Then click OK

Click <code>Enable IO APIC</code>.

24) Congrats!!! Your VM is now confgiured! Click Start to startup the VM!

Click <code>Start</code> to startup the VM!

How to pass in parameters when use resource service?

I suggest you to use provider. Provide is good when you want to configure it first before to use (against Service/Factory)

Something like:

.provider('Magazines', function() {

    this.url = '/';
    this.urlArray = '/';
    this.organId = 'Default';

    this.$get = function() {
        var url = this.url;
        var urlArray = this.urlArray;
        var organId = this.organId;

        return {
            invoke: function() {
                return ......
            }
        }
    };

    this.setUrl  = function(url) {
        this.url = url;
    };

   this.setUrlArray  = function(urlArray) {
        this.urlArray = urlArray;
    };

    this.setOrganId  = function(organId) {
        this.organId = organId;
    };
});

.config(function(MagazinesProvider){
    MagazinesProvider.setUrl('...');
    MagazinesProvider.setUrlArray('...');
    MagazinesProvider.setOrganId('...');
});

And now controller:

function MyCtrl($scope, Magazines) {        

        Magazines.invoke();

       ....

}

Search input with an icon Bootstrap 4

Here is an input box with a search icon on the right.

  <div class="input-group">
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
      <div class="input-group-append">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
  </div>

Here is an input box with a search icon on the left.

  <div class="input-group">
      <div class="input-group-prepend">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
  </div>

Dynamically load JS inside JS

I need to do this frequently, so I use this:

var loadJS = function(url, implementationCode, location){
    //url is URL of external file, implementationCode is the code
    //to be called from the file, location is the location to 
    //insert the <script> element

    var scriptTag = document.createElement('script');
    scriptTag.src = url;

    scriptTag.onload = implementationCode;
    scriptTag.onreadystatechange = implementationCode;

    location.appendChild(scriptTag);
};
var yourCodeToBeCalled = function(){
//your code goes here
}
loadJS('yourcode.js', yourCodeToBeCalled, document.body);

For more information, see this site How do I include a JavaScript file in another JavaScript file?, which is the source of my function idea.

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

This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.

Set the table column width constant regardless of the amount of text in its cells?

If you don't want a fixed layout, specify a class for the column to be size appropriately.

CSS:

.special_column { width: 120px; }

HTML:

<td class="special_column">...</td>

Script parameters in Bash

In bash $1 is the first argument passed to the script, $2 second and so on

/usr/local/bin/abbyyocr9 -rl Swedish -if "$1" -of "$2" 2>&1

So you can use:

./your_script.sh some_source_file.png destination_file.txt

Explanation on double quotes;

consider three scripts:

# foo.sh
bash bar.sh $1

# cat foo2.sh
bash bar.sh "$1"

# bar.sh
echo "1-$1" "2-$2"

Now invoke:

$ bash foo.sh "a b"
1-a 2-b

$ bash foo2.sh "a b"
1-a b 2-

When you invoke foo.sh "a b" then it invokes bar.sh a b (two arguments), and with foo2.sh "a b" it invokes bar.sh "a b" (1 argument). Always have in mind how parameters are passed and expaned in bash, it will save you a lot of headache.

How to jQuery clone() and change id?

This is the simplest solution working for me.

$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");

How to POST request using RestSharp

My RestSharp POST method:

var client = new RestClient(ServiceUrl);

var request = new RestRequest("/resource/", Method.POST);

// Json to post.
string jsonToSend = JsonHelper.ToJson(json);

request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;

try
{
    client.ExecuteAsync(request, response =>
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // OK
        }
        else
        {
            // NOK
        }
    });
}
catch (Exception error)
{
    // Log
}

How to "properly" create a custom object in JavaScript?

Closure is versatile. bobince has well summarized the prototype vs. closure approaches when creating objects. However you can mimic some aspects of OOP using closure in a functional programming way. Remember functions are objects in JavaScript; so use function as object in a different way.

Here is an example of closure:

function outer(outerArg) {
    return inner(innerArg) {
        return innerArg + outerArg; //the scope chain is composed of innerArg and outerArg from the outer context 
    }
}

A while ago I came across the Mozilla's article on Closure. Here is what jump at my eyes: "A closure lets you associate some data (the environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods". It was the very first time I read a parallelism between closure and classic OOP with no reference to prototype.

How?

Suppose you want to calculate the VAT of some items. The VAT is likely to stay stable during the lifetime of an application. One way to do it in OOP (pseudo code):

public class Calculator {
    public property VAT { get; private set; }
    public Calculator(int vat) {
        this.VAT = vat;
    }
    public int Calculate(int price) {
        return price * this.VAT;
    }
}

Basically you pass a VAT value into your constructor and your calculate method can operate upon it via closure. Now instead of using a class/constructor, pass your VAT as an argument into a function. Because the only stuff you are interested in is the calculation itself, returns a new function, which is the calculate method:

function calculator(vat) {
    return function(item) {
        return item * vat;
    }
}
var calculate = calculator(1.10);
var jsBook = 100; //100$
calculate(jsBook); //110

In your project identify top-level values that are good candidate of what VAT is for calculation. As a rule of thumb whenever you pass the same arguments on and on, there is a way to improve it using closure. No need to create traditional objects.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

How can I get a resource content from a static context?

I am using API level 27 and found a best solution after struggling for around two days. If you want to read a xml file from a class which doesn't derive from Activity or Application then do the following.

  1. Put the testdata.xml file inside the assets directory.

  2. Write the following code to get the testdata document parsed.

        InputStream inputStream = this.getClass().getResourceAsStream("/assets/testdata.xml");
    
        // create a new DocumentBuilderFactory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // use the factory to create a documentbuilder
        DocumentBuilder builder = factory.newDocumentBuilder();
        // create a new document from input stream
        Document doc = builder.parse(inputStream);
    

Remove padding from columns in Bootstrap 3

Reducing just the padding on the columns won't make the trick, as you will extend the width of the page, making it uneven with the rest of your page, say navbar. You need to equally reduce the negative margin on the row. Taking @martinedwards' LESS example:

.row-no-padding {
  margin-left: 0;
  margin-right: 0;
  [class*="col-"] {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
}

C default arguments

Yes. :-) But not in a way you would expect.

int f1(int arg1, double arg2, char* name, char *opt);

int f2(int arg1, double arg2, char* name)
{
  return f1(arg1, arg2, name, "Some option");
}

Unfortunately, C doesn't allow you to overload methods so you'd end up with two different functions. Still, by calling f2, you'd actually be calling f1 with a default value. This is a "Don't Repeat Yourself" solution, which helps you to avoid copying/pasting existing code.

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

Automatically set appsettings.json for dev and release environments in asp.net core?

.vscode/launch.json file is only used by Visual Studio as well as /Properties/launchSettings.json file. Don't use these files in production.

The launchSettings.json file:

  1. Is only used on the local development machine.
  2. Is not deployed.
  3. contains profile settings.

    • Environment values set in launchSettings.json override values set in the system environment

To use a file 'appSettings.QA.json' for example. You can use 'ASPNETCORE_ENVIRONMENT'. Follow the steps below.

  1. Add a new Environment Variable on the host machine and call it 'ASPNETCORE_ENVIRONMENT'. Set its value to 'QA'.
  2. Create a file 'appSettings.QA.json' in your project. Add your configuration here.
  3. Deploy to the machine in step 1. Confirm 'appSettings.QA.json' is deployed.
  4. Load your website. Expect appSettings.QA.json to be used in here.

npm install hangs

Incase its useful to others, the following is what worked for me:

On my machine, although npm proxy was set correctly, npm install waits forever doing something like sill extract. Re-trying npm install waits forever on the same package again and again.

After waiting for a long timeout, npm install printed an error message implying that git was trying to fetch something.

The problem vanished after configuring git proxy using the below command:

git config --global http.proxy https://proxy-server:port

Note the https in the value of http.proxy without which the configuration did not take effect. Proxy server settings (http / https / port) might vary for users; hence its worth spending a bit of time experimenting with npm and git proxy server settings.

How can I get the current class of a div with jQuery?

<div  id="my_id" class="my_class"></div>

if that is the first div then address it like so:

document.write("div CSS class: " + document.getElementsByTagName('div')[0].className);

alternatively do this:

document.write("alternative way: " + document.getElementById('my_id').className);

It yields the following results:

div CSS class: my_class
alternative way: my_class

Twitter bootstrap hide element on small devices

<div class="small hidden-xs">
    Some Content Here
</div>

This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.

This answer satisfies the question in the OP title (which is how I found this Q/A).

How to convert datatype:object to float64 in python?

convert_objects is deprecated.

For pandas >= 0.17.0, use pd.to_numeric

df["2nd"] = pd.to_numeric(df["2nd"])

CSS centred header image

you don't need to set the width of header in css, just put the background image as center using this code:

background: url("images/logo.png") no-repeat top center;

or you can just use img tag and put align="center" in the div

Difference between spring @Controller and @RestController annotation

@Controller is used in legacy systems which use JSPs. it can return views. @RestController is to mark the controller is providing REST services with JSON response type. so it wraps @Controller and @ResponseBody annotations together.

Adding multiple columns AFTER a specific column in MySQL

ALTER TABLE `users` ADD COLUMN
`COLUMN NAME` DATATYPE(SIZE) AFTER `EXISTING COLUMN NAME`;

You can do it with this, working fine for me.

Undefined reference to main - collect2: ld returned 1 exit status

It means that es3.c does not define a main function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.

To compile only to an object file, use the -c option:

gcc es3.c -c
gcc es3.o main.c -o es3

The above compiles es3.c to an object file, then compiles a file main.c that would contain the main function, and the linker merges es3.o and main.o into an executable called es3.

How to call one shell script from another shell script?

There are a couple of ways you can do this. Terminal to execute the script:

#!/bin/bash
SCRIPT_PATH="/path/to/script.sh"

# Here you execute your script
"$SCRIPT_PATH"

# or
. "$SCRIPT_PATH"

# or
source "$SCRIPT_PATH"

# or
bash "$SCRIPT_PATH"

# or
eval '"$SCRIPT_PATH"'

# or
OUTPUT=$("$SCRIPT_PATH")
echo $OUTPUT

# or
OUTPUT=`"$SCRIPT_PATH"`
echo $OUTPUT

# or
("$SCRIPT_PATH")

# or
(exec "$SCRIPT_PATH")

All this is correct for the path with spaces!!!

How do you post to the wall on a facebook page (not profile)

This works for me:

try {
       $statusUpdate = $facebook->api('/me/feed', 'post',
                 array('name'=>'My APP on Facebook','message'=> 'I am here working',
                 'privacy'=> array('value'=>'CUSTOM','friends'=>'SELF'),
                 'description'=>'testing my description',
                 'picture'=>'https://fbcdn-photos-a.akamaihd.net/mypicture.gif',
                 'caption'=>'apps.facebook.com/myapp','link'=>'http://apps.facebook.com/myapp'));
 } catch (FacebookApiException $e) {
      d($e);
}

Verifying a specific parameter with Moq

Had one of these as well, but the parameter of the action was an interface with no public properties. Ended up using It.Is() with a seperate method and within this method had to do some mocking of the interface

public interface IQuery
{
    IQuery SetSomeFields(string info);
}

void DoSomeQuerying(Action<IQuery> queryThing);

mockedObject.Setup(m => m.DoSomeQuerying(It.Is<Action<IQuery>>(q => MyCheckingMethod(q)));

private bool MyCheckingMethod(Action<IQuery> queryAction)
{
    var mockQuery = new Mock<IQuery>();
    mockQuery.Setup(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition())
    queryAction.Invoke(mockQuery.Object);
    mockQuery.Verify(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition(), Times.Once)
    return true
}

Line Break in XML formatting?

Use \n for a line break and \t if you want to insert a tab.

You can also use some XML tags for basic formatting: <b> for bold text, <i> for italics, and <u> for underlined text.

Other formatting options are shown in this article on the Android Developers' site:
https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

Simple and fast method to compare images for similarity

If you want to compare image for similarity,I suggest you to used OpenCV. In OpenCV, there are few feature matching and template matching. For feature matching, there are SURF, SIFT, FAST and so on detector. You can use this to detect, describe and then match the image. After that, you can use the specific index to find number of match between the two images.

Using custom std::set comparator

std::less<> when using custom classes with operator<

If you are dealing with a set of your custom class that has operator< defined, then you can just use std::less<>.

As mentioned at http://en.cppreference.com/w/cpp/container/set/find C++14 has added two new find APIs:

template< class K > iterator find( const K& x );
template< class K > const_iterator find( const K& x ) const;

which allow you to do:

main.cpp

#include <cassert>
#include <set>

class Point {
    public:
        // Note that there is _no_ conversion constructor,
        // everything is done at the template level without
        // intermediate object creation.
        //Point(int x) : x(x) {}
        Point(int x, int y) : x(x), y(y) {}
        int x;
        int y;
};
bool operator<(const Point& c, int x) { return c.x < x; }
bool operator<(int x, const Point& c) { return x < c.x; }
bool operator<(const Point& c, const Point& d) {
    return c.x < d;
}

int main() {
    std::set<Point, std::less<>> s;
    s.insert(Point(1, -1));
    s.insert(Point(2, -2));
    s.insert(Point(0,  0));
    s.insert(Point(3, -3));
    assert(s.find(0)->y ==  0);
    assert(s.find(1)->y == -1);
    assert(s.find(2)->y == -2);
    assert(s.find(3)->y == -3);
    // Ignore 1234, find 1.
    assert(s.find(Point(1, 1234))->y == -1);
}

Compile and run:

g++ -std=c++14 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

More info about std::less<> can be found at: What are transparent comparators?

Tested on Ubuntu 16.10, g++ 6.2.0.

DateTime "null" value

Just be warned - When using a Nullable its obviously no longer a 'pure' datetime object, as such you cannot access the DateTime members directly. I'll try and explain.

By using Nullable<> you're basically wrapping DateTime in a container (thank you generics) of which is nullable - obviously its purpose. This container has its own properties which you can call that will provide access to the aforementioned DateTime object; after using the correct property - in this case Nullable.Value - you then have access to the standard DateTime members, properties etc.

So - now the issue comes to mind as to the best way to access the DateTime object. There are a few ways, number 1 is by FAR the best and 2 is "dude why".

  1. Using the Nullable.Value property,

    DateTime date = myNullableObject.Value.ToUniversalTime(); //Works

    DateTime date = myNullableObject.ToUniversalTime(); //Not a datetime object, fails

  2. Converting the nullable object to datetime using Convert.ToDateTime(),

    DateTime date = Convert.ToDateTime(myNullableObject).ToUniversalTime(); //works but why...

Although the answer is well documented at this point, I believe the usage of Nullable was probably worth posting about. Sorry if you disagree.

edit: Removed a third option as it was a bit overly specific and case dependent.

Detecting iOS orientation change instantly

@vimal answer did not provide solution for me. It seems the orientation is not the current orientation, but from previous orientation. To fix it, I use [[UIDevice currentDevice] orientation]

- (void)orientationChanged:(NSNotification *)notification{
    [self adjustViewsForOrientation:[[UIDevice currentDevice] orientation]];
}

Then

- (void) adjustViewsForOrientation:(UIDeviceOrientation) orientation { ... }

With this code I get the current orientation position.

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

Reset input value in angular 2

You can use the event.target.result to reset the input from a component directly.

event.target.value = ""