Programs & Examples On #Commonjs

CommonJS is a project whose goal is to move JavaScript outside the browser.

Node.js - use of module.exports as a constructor

The example code is:

in main

square(width,function (data)
{
   console.log(data.squareVal);
});

using the following may works

exports.square = function(width,callback)
{
     var aa = new Object();
     callback(aa.squareVal = width * width);    
}

Difference between "module.exports" and "exports" in the CommonJs Module System

Renee's answer is well explained. Addition to the answer with an example:

Node does a lot of things to your file and one of the important is WRAPPING your file. Inside nodejs source code "module.exports" is returned. Lets take a step back and understand the wrapper. Suppose you have

greet.js

var greet = function () {
   console.log('Hello World');
};

module.exports = greet;

the above code is wrapped as IIFE(Immediately Invoked Function Expression) inside nodejs source code as follows:

(function (exports, require, module, __filename, __dirname) { //add by node

      var greet = function () {
         console.log('Hello World');
      };

      module.exports = greet;

}).apply();                                                  //add by node

return module.exports;                                      //add by node

and the above function is invoked (.apply()) and returned module.exports. At this time module.exports and exports pointing to the same reference.

Now, imagine you re-write greet.js as

exports = function () {
   console.log('Hello World');
};
console.log(exports);
console.log(module.exports);

the output will be

[Function]
{}

the reason is : module.exports is an empty object. We did not set anything to module.exports rather we set exports = function()..... in new greet.js. So, module.exports is empty.

Technically exports and module.exports should point to same reference(thats correct!!). But we use "=" when assigning function().... to exports, which creates another object in the memory. So, module.exports and exports produce different results. When it comes to exports we can't override it.

Now, imagine you re-write (this is called Mutation) greet.js (referring to Renee answer) as

exports.a = function() {
    console.log("Hello");
}

console.log(exports);
console.log(module.exports);

the output will be

{ a: [Function] }
{ a: [Function] }

As you can see module.exports and exports are pointing to same reference which is a function. If you set a property on exports then it will be set on module.exports because in JS, objects are pass by reference.

Conclusion is always use module.exports to avoid confusion. Hope this helps. Happy coding :)

Field 'browser' doesn't contain a valid alias configuration

In my case, to the very end of the webpack.config.js, where I should exports the config, there was a typo: export(should be exports), which led to failure with loading webpack.config.js at all.

const path = require('path');

const config = {
    mode: 'development',
    entry: "./lib/components/Index.js",
    output: {
        path: path.resolve(__dirname, 'public'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: path.resolve(__dirname, "node_modules")
            }
        ]
    }
}

// pay attention to "export!s!" here
module.exports = config;

module.exports vs exports in Node.js

To understand the differences, you have to first understand what Node.js does to every module during runtime. Node.js creates a wrapper function for every module:

 (function(exports, require, module, __filename, __dirname) {

 })()

Notice the first param exports is an empty object, and the third param module is an object with many properties, and one of the properties is named exports. This is what exports comes from and what module.exports comes from. The former one is a variable object, and the latter one is a property of module object.

Within the module, Node.js automatically does this thing at the beginning: module.exports = exports, and ultimately returns module.exports.

So you can see that if you reassign some value to exports, it won't have any effect to module.exports. (Simply because exports points to another new object, but module.exports still holds the old exports)

let exports = {};
const module = {};
module.exports = exports;

exports = { a: 1 }
console.log(module.exports) // {}

But if you updates properties of exports, it will surely have effect on module.exports. Because they both point to the same object.

let exports = {};
const module = {};
module.exports = exports;

exports.a = 1;
module.exports.b = 2;
console.log(module.exports) // { a: 1, b: 2 }

Also notice that if you reassign another value to module.exports, then it seems meaningless for exports updates. Every updates on exports is ignored because module.exports points to another object.

let exports = {};
const module = {};
module.exports = exports;

exports.a = 1;
module.exports = {
  hello: () => console.log('hello')
}
console.log(module.exports) // { hello: () => console.log('hello')}

Relation between CommonJS, AMD and RequireJS?

AMD

  • introduced in JavaScript to scale JavaScript project into multiple files
  • mostly used in browser based application and libraries
  • popular implementation is RequireJS, Dojo Toolkit

CommonJS:

  • it is specification to handle large number of functions, files and modules of big project
  • initial name ServerJS introduced in January, 2009 by Mozilla
  • renamed in August, 2009 to CommonJS to show the broader applicability of the APIs
  • initially implementation were server, nodejs, desktop based libraries

Example

upper.js file

exports.uppercase = str => str.toUpperCase()

main.js file

const uppercaseModule = require('uppercase.js')
uppercaseModule.uppercase('test')

Summary

  • AMD – one of the most ancient module systems, initially implemented by the library require.js.
  • CommonJS – the module system created for Node.js server.
  • UMD – one more module system, suggested as a universal one, compatible with AMD and CommonJS.

Resources:

Check whether a value exists in JSON object

Check for a value single level

const hasValue = Object.values(json).includes("bar");

Check for a value multi-level

function hasValueDeep(json, findValue) {
    const values = Object.values(json);
    let hasValue = values.includes(findValue);
    values.forEach(function(value) {
        if (typeof value === "object") {
            hasValue = hasValue || hasValueDeep(value, findValue);
        }
    })
    return hasValue;
}

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Just one sentence to say Instruct Internet Explorer to use its latest rendering engine

<meta http-equiv="x-ua-compatible" content="ie=edge">

Moment.js - how do I get the number of years since a date, not rounded up?

I found that it would work to reset the month to January for both dates (the provided date and the present):

> moment("02/26/1978", "MM/DD/YYYY").month(0).from(moment().month(0))
"34 years ago"

React Router with optional path parameter

If you are looking to do an exact match, use the following syntax: (param)?.

Eg.

<Route path={`my/(exact)?/path`} component={MyComponent} />

The nice thing about this is that you'll have props.match to play with, and you don't need to worry about checking the value of the optional parameter:

{ props: { match: { "0": "exact" } } }

SSIS Connection not found in package

I received this error while attempting to open an SSDT 2010/SSIS 2012 project in VS with SSDT 2013. When it opened the project, it asked to migrate all the packages. When I allowed it to proceed, every package failed with this error and others. I found that bypassing the conversion and just opening each package individually, the package is upgraded upon opening, and it converted fine and successfully ran.

How to implement the --verbose or -v option into a script?

Use the logging module:

import logging as log
…
args = p.parse_args()
if args.verbose:
    log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
    log.info("Verbose output.")
else:
    log.basicConfig(format="%(levelname)s: %(message)s")

log.info("This should be verbose.")
log.warning("This is a warning.")
log.error("This is an error.")

All of these automatically go to stderr:

% python myprogram.py
WARNING: This is a warning.
ERROR: This is an error.

% python myprogram.py -v
INFO: Verbose output.
INFO: This should be verbose.
WARNING: This is a warning.
ERROR: This is an error.

For more info, see the Python Docs and the tutorials.

Why should text files end with a newline?

Some tools expect this. For example, wc expects this:

$ echo -n "Line not ending in a new line" | wc -l
0
$ echo "Line ending with a new line" | wc -l
1

Vertical line using XML drawable

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:bottom="-3dp"
        android:left="-3dp"
        android:top="-3dp">

        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimary" />
            <stroke
                android:width="2dp"
                android:color="#1fc78c" />
        </shape>

    </item>

</layer-list>

StringUtils.isBlank() vs String.isEmpty()

StringUtils.isBlank also returns true for just whitespace:

isBlank(String str)

Checks if a String is whitespace, empty ("") or null.

How to execute only one test spec with angular-cli

Just small change need in test.ts file inside src folder:

const context = require.context('./', true, /test-example\.spec\.ts$/);

Here, test-example is the exact file name which we need to run

In the same way, if you need to test the service file only you can replace the filename like "/test-example.service"

Regex pattern inside SQL Replace function?

i think this solution is faster and simple. i use always CTE/recursive beacuse WHILE is so slow on mssql. I use it in projects I work with and large databases.

/*
Function:           dbo.kSql_ReplaceRegExp
Create Date:        20.02.2021
Author:             Karcan Ozbal

Description:        The given string value will be replaced according to the given regexp/pattern.

Parameter(s):       @Value       : Value/Text to REPLACE.
                    @RegExp      : The regexp/pattern to be used for REPLACE operation.

Usage:              select dbo.kSql_ReplaceRegExp('2T3EST5','%[0-9]%')
Output:             'TEST'
*/
ALTER FUNCTION [dbo].[kSql_ReplaceRegExp](
    @Value nvarchar(max),
    @RegExp nvarchar(50)
)
RETURNS nvarchar(max)
AS
BEGIN
    DECLARE @Result nvarchar(max)

    ;WITH CTE AS (
        SELECT NUM = 1, VALUE = @Value, IDX = PATINDEX(@RegExp, @Value)
        UNION ALL
        SELECT NUM + 1, VALUE = REPLACE(VALUE, SUBSTRING(VALUE,IDX,1),''), IDX = PATINDEX(@RegExp, REPLACE(VALUE, SUBSTRING(VALUE,IDX,1),'')) 
        FROM CTE
        WHERE IDX > 0
    )
    SELECT TOP(1) @Result = VALUE 
    FROM CTE 
    ORDER BY NUM DESC
    OPTION (maxrecursion 0)

    RETURN @Result
END

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

I went to Preferences --> Java --> Installed JREs I did NOT see the JDK in here. I only saw the JRE here. So I added the JDK.

here we have to mandatory remove JRE instead of just unchecking.

jQuery .live() vs .on() method for adding a click event after loading dynamic html

$(document).on('click', '.selector', function() { /* do stuff */ });

EDIT: I'm providing a bit more information on how this works, because... words. With this example, you are placing a listener on the entire document.

When you click on any element(s) matching .selector, the event bubbles up to the main document -- so long as there's no other listeners that call event.stopPropagation() method -- which would top the bubbling of an event to parent elements.

Instead of binding to a specific element or set of elements, you are listening for any events coming from elements that match the specified selector. This means you can create one listener, one time, that will automatically match currently existing elements as well as any dynamically added elements.

This is smart for a few reasons, including performance and memory utilization (in large scale applications)

EDIT:

Obviously, the closest parent element you can listen on is better, and you can use any element in place of document as long as the children you want to monitor events for are within that parent element... but that really does not have anything to do with the question.

Finding Variable Type in JavaScript

Using type:

// Numbers
typeof 37                === 'number';
typeof 3.14              === 'number';
typeof Math.LN2          === 'number';
typeof Infinity          === 'number';
typeof NaN               === 'number'; // Despite being "Not-A-Number"
typeof Number(1)         === 'number'; // but never use this form!

// Strings
typeof ""                === 'string';
typeof "bla"             === 'string';
typeof (typeof 1)        === 'string'; // typeof always return a string
typeof String("abc")     === 'string'; // but never use this form!

// Booleans
typeof true              === 'boolean';
typeof false             === 'boolean';
typeof Boolean(true)     === 'boolean'; // but never use this form!

// Undefined
typeof undefined         === 'undefined';
typeof blabla            === 'undefined'; // an undefined variable

// Objects
typeof {a:1}             === 'object';
typeof [1, 2, 4]         === 'object'; // use Array.isArray or Object.prototype.toString.call to differentiate regular objects from arrays
typeof new Date()        === 'object';
typeof new Boolean(true) === 'object'; // this is confusing. Don't use!
typeof new Number(1)     === 'object'; // this is confusing. Don't use!
typeof new String("abc") === 'object';  // this is confusing. Don't use!

// Functions
typeof function(){}      === 'function';
typeof Math.sin          === 'function';

Escaping quotation marks in PHP

Use htmlspecialchars(). Then quote and less / greater than symbols don't break your HTML tags~

How to use Python to execute a cURL command?

import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json

maybe?

if you are trying to send a file

files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json

ahh thanks @LukasGraf now i better understand what his original code is doing

import requests,json
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
my_json_data = json.load(open("request.json"))
req = requests.post(url,data=my_json_data)
print req.text
print 
print req.json # maybe? 

Drop all tables whose names begin with a certain string

This worked for me.

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += '
DROP TABLE ' 
    + QUOTENAME(s.name)
    + '.' + QUOTENAME(t.name) + ';'
    FROM sys.tables AS t
    INNER JOIN sys.schemas AS s
    ON t.[schema_id] = s.[schema_id] 
    WHERE t.name LIKE 'something%';

PRINT @sql;
-- EXEC sp_executesql @sql;

Find the similarity metric between two strings

I think maybe you are looking for an algorithm describing the distance between strings. Here are some you may refer to:

  1. Hamming distance
  2. Levenshtein distance
  3. Damerau–Levenshtein distance
  4. Jaro–Winkler distance

addEventListener, "change" and option selection

You need a click listener which calls addActivityItem if less than 2 options exist:

var activities = document.getElementById("activitySelector");

activities.addEventListener("click", function() {
    var options = activities.querySelectorAll("option");
    var count = options.length;
    if(typeof(count) === "undefined" || count < 2)
    {
        addActivityItem();
    }
});

activities.addEventListener("change", function() {
    if(activities.value == "addNew")
    {
        addActivityItem();
    }
});

function addActivityItem() {
    // ... Code to add item here
}

A live demo is here on JSfiddle.

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

List of <p:ajax> events

I've got the list in debug mode; first I saw the point at which the error was thrown

javax.faces.view.facelets.TagException: /showcase/partial_submit.xhtml @26,36 Event:changed is not supported. org.primefaces.component.behavior.ajax.AjaxBehaviorHandler.applyAttachedObject(AjaxBehaviorHandler.java:179) org.primefaces.component.behavior.ajax.AjaxBehaviorHandler.apply(AjaxBehaviorHandler.java:157)

and then I debugged AjaxBehaviorHandler

enter image description here

so if you want discover the right list of supported event, you can generate an error (using an event name that is wrong), and follow this way

Using NSPredicate to filter an NSArray based on NSDictionary keys

It should work - as long as the data variable is actually an array containing a dictionary with the key SPORT

NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"foo" forKey:@"BAR"]];    
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(BAR == %@)", @"foo"]];

Filtered in this case contains the dictionary.

(the %@ does not have to be quoted, this is done when NSPredicate creates the object.)

Find index of last occurrence of a substring in a string

Use .rfind():

>>> s = 'hello'
>>> s.rfind('l')
3

Also don't use str as variable name or you'll shadow the built-in str().

Excel Reference To Current Cell

There is a better way that is safer and will not slow down your application. How Excel is set up, a cell can have either a value or a formula; the formula can not refer to its own cell. You end up with an infinite loop, since the new value would cause another calculation... . Use a helper column to calculate the value based on what you put in the other cell. For Example:

Column A is a True or False, Column B contains a monetary value, Column C contains the folowing formula: =B1

Now, to calculate that column B will be highlighted yellow in a conditional format only if Column A is True and Column B is greater than Zero...

=AND(A1=True,C1>0)

You can then choose to hide column C

How to count objects in PowerShell?

As short as @jumbo's answer is :-) you can do it even more tersely. This just returns the Count property of the array returned by the antecedent sub-expression:

@(Get-Alias).Count

A couple points to note:

  1. You can put an arbitrarily complex expression in place of Get-Alias, for example:

    @(Get-Process | ? { $_.ProcessName -eq "svchost" }).Count
    
  2. The initial at-sign (@) is necessary for a robust solution. As long as the answer is two or greater you will get an equivalent answer with or without the @, but when the answer is zero or one you will get no output unless you have the @ sign! (It forces the Count property to exist by forcing the output to be an array.)

2012.01.30 Update

The above is true for PowerShell V2. One of the new features of PowerShell V3 is that you do have a Count property even for singletons, so the at-sign becomes unimportant for this scenario.

How to use Checkbox inside Select Option

I started from @vitfo answer but I want to have <option> inside <select> instead of checkbox inputs so i put together all the answers to make this, there is my code, I hope it will help someone.

_x000D_
_x000D_
$(".multiple_select").mousedown(function(e) {_x000D_
    if (e.target.tagName == "OPTION") _x000D_
    {_x000D_
      return; //don't close dropdown if i select option_x000D_
    }_x000D_
    $(this).toggleClass('multiple_select_active'); //close dropdown if click inside <select> box_x000D_
});_x000D_
$(".multiple_select").on('blur', function(e) {_x000D_
    $(this).removeClass('multiple_select_active'); //close dropdown if click outside <select>_x000D_
});_x000D_
 _x000D_
$('.multiple_select option').mousedown(function(e) { //no ctrl to select multiple_x000D_
    e.preventDefault(); _x000D_
    $(this).prop('selected', $(this).prop('selected') ? false : true); //set selected options on click_x000D_
    $(this).parent().change(); //trigger change event_x000D_
});_x000D_
_x000D_
 _x000D_
 $("#myFilter").on('change', function() {_x000D_
      var selected = $("#myFilter").val().toString(); //here I get all options and convert to string_x000D_
      var document_style = document.documentElement.style;_x000D_
      if(selected !== "")_x000D_
        document_style.setProperty('--text', "'Selected: "+selected+"'");_x000D_
      else_x000D_
        document_style.setProperty('--text', "'Select values'");_x000D_
 });
_x000D_
:root_x000D_
{_x000D_
 --text: "Select values";_x000D_
}_x000D_
.multiple_select_x000D_
{_x000D_
 height: 18px;_x000D_
 width: 90%;_x000D_
 overflow: hidden;_x000D_
 -webkit-appearance: menulist;_x000D_
 position: relative;_x000D_
}_x000D_
.multiple_select::before_x000D_
{_x000D_
 content: var(--text);_x000D_
 display: block;_x000D_
  margin-left: 5px;_x000D_
  margin-bottom: 2px;_x000D_
}_x000D_
.multiple_select_active_x000D_
{_x000D_
 overflow: visible !important;_x000D_
}_x000D_
.multiple_select option_x000D_
{_x000D_
 display: none;_x000D_
    height: 18px;_x000D_
 background-color: white;_x000D_
}_x000D_
.multiple_select_active option_x000D_
{_x000D_
 display: block;_x000D_
}_x000D_
_x000D_
.multiple_select option::before {_x000D_
  content: "\2610";_x000D_
}_x000D_
.multiple_select option:checked::before {_x000D_
  content: "\2611";_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select id="myFilter" class="multiple_select" multiple>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
  <option>D</option>_x000D_
  <option>E</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to get the first item from an associative PHP array?

you can just use $array[0]. it will give you the first item always

How to replace a string in an existing file in Perl?

Anything wrong with a one-liner?

$ perl -pi.bak -e 's/blue/red/g' *_classification.dat

Explanation

  • -p processes, then prints <> line by line
  • -i activates in-place editing. Files are backed up using the .bak extension
  • The regex substitution acts on the implicit variable, which are the contents of the file, line-by-line

Compare if BigDecimal is greater than zero

This works too:

value > BigDecimal.ZERO

How do I measure the execution time of JavaScript code with callbacks?

There is a method that is designed for this. Check out process.hrtime(); .

So, I basically put this at the top of my app.

var start = process.hrtime();

var elapsed_time = function(note){
    var precision = 3; // 3 decimal places
    var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
    console.log(process.hrtime(start)[0] + " s, " + elapsed.toFixed(precision) + " ms - " + note); // print message + time
    start = process.hrtime(); // reset the timer
}

Then I use it to see how long functions take. Here's a basic example that prints the contents of a text file called "output.txt":

var debug = true;
http.createServer(function(request, response) {

    if(debug) console.log("----------------------------------");
    if(debug) elapsed_time("recieved request");

    var send_html = function(err, contents) {
        if(debug) elapsed_time("start send_html()");
        response.writeHead(200, {'Content-Type': 'text/html' } );
        response.end(contents);
        if(debug) elapsed_time("end send_html()");
    }

    if(debug) elapsed_time("start readFile()");
    fs.readFile('output.txt', send_html);
    if(debug) elapsed_time("end readFile()");

}).listen(8080);

Here's a quick test you can run in a terminal (BASH shell):

for i in {1..100}; do echo $i; curl http://localhost:8080/; done

Dynamically Add Images React Webpack

here is the code

    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './image.css';
    import Dropdown from 'react-dropdown';
    import axios from 'axios';

    let obj = {};

    class App extends Component {
      constructor(){
        super();
        this.state = {
          selectedFiles: []
        }
        this.fileUploadHandler = this.fileUploadHandler.bind(this);
      }

      fileUploadHandler(file){
        let selectedFiles_ = this.state.selectedFiles;
        selectedFiles_.push(file);
        this.setState({selectedFiles: selectedFiles_});
      }

      render() {
        let Images = this.state.selectedFiles.map(image => {
          <div className = "image_parent">

              <img src={require(image.src)}
              />
          </div>
        });

        return (
            <div className="image-upload images_main">

            <input type="file" onClick={this.fileUploadHandler}/>
            {Images}

            </div>
        );
      }
    }

    export default App;

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.

Source: http://www.albeesonline.com/blog/2008/11/29/warning-setpropertiesruleserverserviceenginehostcontext-setting-property/

What is the default font of Sublime Text?

To add to MattDMo's answer, you can get the exact font that's used on Linux like so (the example is from Xubuntu 14.04):

$ fc-match Monospace
DejaVuSansMono.ttf: "DejaVu Sans Mono" "Book"

How do I set up Vim autoindentation properly for editing Python files?

I use:

$ cat ~/.vimrc
syntax on
set showmatch
set ts=4
set sts=4
set sw=4
set autoindent
set smartindent
set smarttab
set expandtab
set number

But but I'm going to try Daren's entries

RecyclerView - How to smooth scroll to top of item on a certain position?

The easiest way I've found to scroll a RecyclerView is as follows:

// Define the Index we wish to scroll to.
final int lIndex = 0;
// Assign the RecyclerView's LayoutManager.
this.getRecyclerView().setLayoutManager(this.getLinearLayoutManager());
// Scroll the RecyclerView to the Index.
this.getLinearLayoutManager().smoothScrollToPosition(this.getRecyclerView(), new RecyclerView.State(), lIndex);

Jackson Vs. Gson

I did this research the last week and I ended up with the same 2 libraries. As I'm using Spring 3 (that adopts Jackson in its default Json view 'JacksonJsonView') it was more natural for me to do the same. The 2 lib are pretty much the same... at the end they simply map to a json file! :)

Anyway as you said Jackson has a + in performance and that's very important for me. The project is also quite active as you can see from their web page and that's a very good sign as well.

Change tab bar tint color on iOS 7

Try the below:

[[UITabBar appearance] setTintColor:[UIColor redColor]];
[[UITabBar appearance] setBarTintColor:[UIColor yellowColor]];

To tint the non active buttons, put the below code in your VC's viewDidLoad:

UITabBarItem *tabBarItem = [yourTabBarController.tabBar.items objectAtIndex:0];

UIImage *unselectedImage = [UIImage imageNamed:@"icon-unselected"];
UIImage *selectedImage = [UIImage imageNamed:@"icon-selected"];

[tabBarItem setImage: [unselectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[tabBarItem setSelectedImage: selectedImage];

You need to do this for all the tabBarItems, and yes I know it is ugly and hope there will be cleaner way to do this.

Swift:

UITabBar.appearance().tintColor = UIColor.red

tabBarItem.image = UIImage(named: "unselected")?.withRenderingMode(.alwaysOriginal)
tabBarItem.selectedImage = UIImage(named: "selected")?.withRenderingMode(.alwaysOriginal)

How to escape a JSON string to have it in a URL?

Answer given by Delan is perfect. Just adding to it - incase someone wants to name the parameters or pass multiple JSON strings separately - the below code could help!

JQuery

var valuesToPass = new Array(encodeURIComponent(VALUE_1), encodeURIComponent(VALUE_2), encodeURIComponent(VALUE_3), encodeURIComponent(VALUE_4));

data = {elements:JSON.stringify(valuesToPass)}

PHP

json_decode(urldecode($_POST('elements')));

Hope this helps!

Convert a float64 to an int in Go

If its simply from float64 to int, this should work

package main

import (
    "fmt"
)

func main() {
    nf := []float64{-1.9999, -2.0001, -2.0, 0, 1.9999, 2.0001, 2.0}

    //round
    fmt.Printf("Round : ")
    for _, f := range nf {
        fmt.Printf("%d ", round(f))
    }
    fmt.Printf("\n")

    //rounddown ie. math.floor
    fmt.Printf("RoundD: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundD(f))
    }
    fmt.Printf("\n")

    //roundup ie. math.ceil
    fmt.Printf("RoundU: ")
    for _, f := range nf {
        fmt.Printf("%d ", roundU(f)) 
    }
    fmt.Printf("\n")

}

func roundU(val float64) int {
    if val > 0 { return int(val+1.0) }
    return int(val)
}

func roundD(val float64) int {
    if val < 0 { return int(val-1.0) }
    return int(val)
}

func round(val float64) int {
    if val < 0 { return int(val-0.5) }
    return int(val+0.5)
}

Outputs:

Round : -2 -2 -2 0 2 2 2 
RoundD: -2 -3 -3 0 1 2 2 
RoundU: -1 -2 -2 0 2 3 3 

Here's the code in the playground - https://play.golang.org/p/HmFfM6Grqh

Spring - @Transactional - What happens in background?

The simplest answer is:

On whichever method you declare @Transactional the boundary of transaction starts and boundary ends when method completes.

If you are using JPA call then all commits are with in this transaction boundary.

Lets say you are saving entity1, entity2 and entity3. Now while saving entity3 an exception occur, then as enitiy1 and entity2 comes in same transaction so entity1 and entity2 will be rollback with entity3.

Transaction :

  1. entity1.save
  2. entity2.save
  3. entity3.save

Any exception will result in rollback of all JPA transactions with DB.Internally JPA transaction are used by Spring.

Remove files from Git commit

The following will unstage just the file you intended, which is what the OP asked.

git reset HEAD^ /path/to/file

You'll see something like the following...

Changes to be committed: (use "git reset HEAD ..." to unstage)

modified: /path/to/file

Changes not staged for commit: (use "git add ..." to update what will be committed) (use "git checkout -- ..." to discard changes in working directory)

modified: /path/to/file

  • "Changes to be committed" is the previous version of the file before the commit. This will look like a deletion if the file never existed. If you commit this change, there will be a revision that reverts the change to the file in your branch.
  • "Changes not staged for commit" is the change you committed, and the current state of the file

At this point, you can do whatever you like to the file, such as resetting to a different version.

When you're ready to commit:

git commit --amend -a

or (if you've got some other changes going on that you don't want to commit, yet)

git commit add /path/to/file
git commit --amend

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

Temporarily change current working directory in bash to run a command

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

Python dictionary get multiple values

Use a for loop:

keys = ['firstKey', 'secondKey', 'thirdKey']
for key in keys:
    myDictionary.get(key)

or a list comprehension:

[myDictionary.get(key) for key in keys]

Location of hibernate.cfg.xml in project?

For anyone interested: if you are using Intellj, just simply put hibernate.cfg.xml under src/main/resources.

Use component from another module

(Angular 2 - Angular 7)

Component can be declared in a single module only. In order to use a component from another module, you need to do two simple tasks:

  1. Export the component in the other module
  2. Import the other module, into the current module

1st Module:

Have a component (lets call it: "ImportantCopmonent"), we want to re-use in the 2nd Module's page.

@NgModule({
declarations: [
    FirstPage,
    ImportantCopmonent // <-- Enable using the component html tag in current module
],
imports: [
  IonicPageModule.forChild(NotImportantPage),
  TranslateModule.forChild(),
],
exports: [
    FirstPage,
    ImportantCopmonent // <--- Enable using the component in other modules
  ]
})
export class FirstPageModule { }

2nd Module:

Reuses the "ImportantCopmonent", by importing the FirstPageModule

@NgModule({
declarations: [
    SecondPage,
    Example2ndComponent,
    Example3rdComponent
],
imports: [
  IonicPageModule.forChild(SecondPage),
  TranslateModule.forChild(),
  FirstPageModule // <--- this Imports the source module, with its exports
], 
exports: [
    SecondPage,
]
})
export class SecondPageModule { }

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

Actually you can do this with:

ssl off; 

This solved my problem in using nginxvhosts; now I am able to use both SSL and plain HTTP. Works even with combined ports.

Update Jenkins from a war file

when you open the Jenkins panel it will show available package from their latest version. you can download it via wget command in the server.after download the latest package you should take .war backup file.

Eg-: wget http://updates.jenkins-ci.org/download/war/2.205/jenkins.war

Jenkins war file path for Ubuntu - /usr/share/jenkins/

Jenkins war file path for centos - /usr/lib/jenkins/

after taking backup overwrite the war file and restart the jenkins service.

Ubuntu - service jenkins restart , centos - systemctl restart jenkins.service

Docker - Cannot remove dead container

I have tried the suggestions above but didn't work.

Then

  1. I try : docker system prune -a, it didn't work the first time
  2. I reboot the system
  3. I try again docker system prune -a. This time it works. It will send a warning message and in the end ask "Are you sure you want to continue? y/n? . Ans:y . It will time a time and in the end the dead containers are gone.
  4. Verify with docker ps -a

IMPORTANT - this is the nuclear option as it destroys all containers + images

Connect Android to WiFi Enterprise network EAP(PEAP)

Thanks for enlightening us Cypawer.

I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi

and it worked flawlessly.

Leap Wifi Connector

Two versions of python on linux. how to make 2.7 the default

Enter the command

which python

//output:
/usr/bin/python

cd /usr/bin
ls -l

Here you can see something like this

lrwxrwxrwx 1 root   root            9 Mar  7 17:04  python -> python2.7

your default python2.7 is soft linked to the text 'python'

So remove the softlink python

sudo rm -r python

then retry the above command

ls -l

you can see the softlink is removed

-rwxr-xr-x 1 root   root      3670448 Nov 12 20:01  python2.7

Then create a new softlink for python3.6

ln -s /usr/bin/python3.6 python

Then try the command python in terminal

//output:
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux

Type help, copyright, credits or license for more information.

SQL query, if value is null then return 1

a) If you want 0 when value is null

SELECT isnull(PartNum,0) AS PartNumber, PartID
FROM Part

b) If you want 0 when value is null and otherwise 1

SELECT 
  (CASE
    WHEN PartNum IS NULL THEN 0
    ELSE 1
  END) AS PartNumber,
  PartID
FROM Part

Difference between "as $key => $value" and "as $value" in PHP foreach

Sample Array: Left ones are the keys, right one are my values

$array = array(
        'key-1' => 'value-1', 
        'key-2' => 'value-2',
        'key-3' => 'value-3',
        );

Example A: I want only the values of $array

foreach($array as $value) {    
    echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'     
}

Example B: I want each value AND key of $array

foreach($array as $key => $value) {                 
    echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'  

    echo $key; // Through $key I get access to 'key-1' then 'key-2' and finally 'key-3'    

    echo $array[$key]; // Accessing the value through $key = Same output as echo $value;
    $array[$key] = $value + 1; // Exmaple usage of $key: Change the value by increasing it by 1            
}

How do I close an Android alertdialog

I would try putting a

Log.e("SOMETAG", "dialog button was clicked");

before the dialog.dismiss() line in your code to see if it actually reaches that section.

How do I POST with multipart form data using fetch?

You're setting the Content-Type to be multipart/form-data, but then using JSON.stringify on the body data, which returns application/json. You have a content type mismatch.

You will need to encode your data as multipart/form-data instead of json. Usually multipart/form-data is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded (which is the default for HTML forms).

The specification for multipart/form-data can be found in RFC 1867.

For a guide on how to submit that kind of data via javascript, see here.

The basic idea is to use the FormData object (not supported in IE < 10):

async function sendData(url, data) {
  const formData  = new FormData();

  for(const name in data) {
    formData.append(name, data[name]);
  }

  const response = await fetch(url, {
    method: 'POST',
    body: formData
  });

  // ...
}

Per this article make sure not to set the Content-Type header. The browser will set it for you, including the boundary parameter.

How do you remove a specific revision in the git history?

Per this comment (and I checked that this is true), rado's answer is very close but leaves git in a detached head state. Instead, remove HEAD and use this to remove <commit-id> from the branch you're on:

git rebase --onto <commit-id>^ <commit-id>

Aggregate a dataframe on a given column and display another column

To add to Gavin's answer: prior to the merge, it is possible to get aggregate to use proper names when not using the formula interface:

aggregate(data[,"score", drop=F], list(group=data$group), mean) 

How do I access previous promise results in a .then() chain?

Another answer, using babel-node version <6

Using async - await

npm install -g [email protected]

example.js:

async function getExample(){

  let response = await returnPromise();

  let response2 = await returnPromise2();

  console.log(response, response2)

}

getExample()

Then, run babel-node example.js and voila!

How do I detect IE 8 with jQuery?

You can use $.browser to detect the browser name. possible values are :

  • webkit (as of jQuery 1.4)
  • safari (deprecated)
  • opera
  • msie
  • mozilla

or get a boolean flag: $.browser.msie will be true if the browser is MSIE.

as for the version number, if you are only interested in the major release number - you can use parseInt($.browser.version, 10). no need to parse the $.browser.version string yourself.

Anyway, The $.support property is available for detection of support for particular features rather than relying on $.browser.

How can I trigger a Bootstrap modal programmatically?

The following code useful to open modal on openModal() function and close on closeModal() :

      function openModal() {
          $(document).ready(function(){
             $("#myModal").modal();
          });
      }

     function closeModal () {
          $(document).ready(function(){
             $("#myModal").modal('hide');
          });  
      }

/* #myModal is the id of modal popup */

How do I bind onchange event of a TextBox using JQuery?

Combination of keyup and change is not necessarily enough (browser's autocomplete and paste using mouse also changes the contents of a text box, but doesn't fire either of these events):

jquery change not working incase of dynamic value change

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

I've found a hard-coded solution, I hope i will help somebody:

public static class MIMEAssistant
{
  private static readonly Dictionary<string, string> MIMETypesDictionary = new Dictionary<string, string>
  {
    {"ai", "application/postscript"},
    {"aif", "audio/x-aiff"},
    {"aifc", "audio/x-aiff"},
    {"aiff", "audio/x-aiff"},
    {"asc", "text/plain"},
    {"atom", "application/atom+xml"},
    {"au", "audio/basic"},
    {"avi", "video/x-msvideo"},
    {"bcpio", "application/x-bcpio"},
    {"bin", "application/octet-stream"},
    {"bmp", "image/bmp"},
    {"cdf", "application/x-netcdf"},
    {"cgm", "image/cgm"},
    {"class", "application/octet-stream"},
    {"cpio", "application/x-cpio"},
    {"cpt", "application/mac-compactpro"},
    {"csh", "application/x-csh"},
    {"css", "text/css"},
    {"dcr", "application/x-director"},
    {"dif", "video/x-dv"},
    {"dir", "application/x-director"},
    {"djv", "image/vnd.djvu"},
    {"djvu", "image/vnd.djvu"},
    {"dll", "application/octet-stream"},
    {"dmg", "application/octet-stream"},
    {"dms", "application/octet-stream"},
    {"doc", "application/msword"},
    {"docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
    {"docm","application/vnd.ms-word.document.macroEnabled.12"},
    {"dotm","application/vnd.ms-word.template.macroEnabled.12"},
    {"dtd", "application/xml-dtd"},
    {"dv", "video/x-dv"},
    {"dvi", "application/x-dvi"},
    {"dxr", "application/x-director"},
    {"eps", "application/postscript"},
    {"etx", "text/x-setext"},
    {"exe", "application/octet-stream"},
    {"ez", "application/andrew-inset"},
    {"gif", "image/gif"},
    {"gram", "application/srgs"},
    {"grxml", "application/srgs+xml"},
    {"gtar", "application/x-gtar"},
    {"hdf", "application/x-hdf"},
    {"hqx", "application/mac-binhex40"},
    {"htm", "text/html"},
    {"html", "text/html"},
    {"ice", "x-conference/x-cooltalk"},
    {"ico", "image/x-icon"},
    {"ics", "text/calendar"},
    {"ief", "image/ief"},
    {"ifb", "text/calendar"},
    {"iges", "model/iges"},
    {"igs", "model/iges"},
    {"jnlp", "application/x-java-jnlp-file"},
    {"jp2", "image/jp2"},
    {"jpe", "image/jpeg"},
    {"jpeg", "image/jpeg"},
    {"jpg", "image/jpeg"},
    {"js", "application/x-javascript"},
    {"kar", "audio/midi"},
    {"latex", "application/x-latex"},
    {"lha", "application/octet-stream"},
    {"lzh", "application/octet-stream"},
    {"m3u", "audio/x-mpegurl"},
    {"m4a", "audio/mp4a-latm"},
    {"m4b", "audio/mp4a-latm"},
    {"m4p", "audio/mp4a-latm"},
    {"m4u", "video/vnd.mpegurl"},
    {"m4v", "video/x-m4v"},
    {"mac", "image/x-macpaint"},
    {"man", "application/x-troff-man"},
    {"mathml", "application/mathml+xml"},
    {"me", "application/x-troff-me"},
    {"mesh", "model/mesh"},
    {"mid", "audio/midi"},
    {"midi", "audio/midi"},
    {"mif", "application/vnd.mif"},
    {"mov", "video/quicktime"},
    {"movie", "video/x-sgi-movie"},
    {"mp2", "audio/mpeg"},
    {"mp3", "audio/mpeg"},
    {"mp4", "video/mp4"},
    {"mpe", "video/mpeg"},
    {"mpeg", "video/mpeg"},
    {"mpg", "video/mpeg"},
    {"mpga", "audio/mpeg"},
    {"ms", "application/x-troff-ms"},
    {"msh", "model/mesh"},
    {"mxu", "video/vnd.mpegurl"},
    {"nc", "application/x-netcdf"},
    {"oda", "application/oda"},
    {"ogg", "application/ogg"},
    {"pbm", "image/x-portable-bitmap"},
    {"pct", "image/pict"},
    {"pdb", "chemical/x-pdb"},
    {"pdf", "application/pdf"},
    {"pgm", "image/x-portable-graymap"},
    {"pgn", "application/x-chess-pgn"},
    {"pic", "image/pict"},
    {"pict", "image/pict"},
    {"png", "image/png"}, 
    {"pnm", "image/x-portable-anymap"},
    {"pnt", "image/x-macpaint"},
    {"pntg", "image/x-macpaint"},
    {"ppm", "image/x-portable-pixmap"},
    {"ppt", "application/vnd.ms-powerpoint"},
    {"pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {"potx","application/vnd.openxmlformats-officedocument.presentationml.template"},
    {"ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
    {"ppam","application/vnd.ms-powerpoint.addin.macroEnabled.12"},
    {"pptm","application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
    {"potm","application/vnd.ms-powerpoint.template.macroEnabled.12"},
    {"ppsm","application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
    {"ps", "application/postscript"},
    {"qt", "video/quicktime"},
    {"qti", "image/x-quicktime"},
    {"qtif", "image/x-quicktime"},
    {"ra", "audio/x-pn-realaudio"},
    {"ram", "audio/x-pn-realaudio"},
    {"ras", "image/x-cmu-raster"},
    {"rdf", "application/rdf+xml"},
    {"rgb", "image/x-rgb"},
    {"rm", "application/vnd.rn-realmedia"},
    {"roff", "application/x-troff"},
    {"rtf", "text/rtf"},
    {"rtx", "text/richtext"},
    {"sgm", "text/sgml"},
    {"sgml", "text/sgml"},
    {"sh", "application/x-sh"},
    {"shar", "application/x-shar"},
    {"silo", "model/mesh"},
    {"sit", "application/x-stuffit"},
    {"skd", "application/x-koan"},
    {"skm", "application/x-koan"},
    {"skp", "application/x-koan"},
    {"skt", "application/x-koan"},
    {"smi", "application/smil"},
    {"smil", "application/smil"},
    {"snd", "audio/basic"},
    {"so", "application/octet-stream"},
    {"spl", "application/x-futuresplash"},
    {"src", "application/x-wais-source"},
    {"sv4cpio", "application/x-sv4cpio"},
    {"sv4crc", "application/x-sv4crc"},
    {"svg", "image/svg+xml"},
    {"swf", "application/x-shockwave-flash"},
    {"t", "application/x-troff"},
    {"tar", "application/x-tar"},
    {"tcl", "application/x-tcl"},
    {"tex", "application/x-tex"},
    {"texi", "application/x-texinfo"},
    {"texinfo", "application/x-texinfo"},
    {"tif", "image/tiff"},
    {"tiff", "image/tiff"},
    {"tr", "application/x-troff"},
    {"tsv", "text/tab-separated-values"},
    {"txt", "text/plain"},
    {"ustar", "application/x-ustar"},
    {"vcd", "application/x-cdlink"},
    {"vrml", "model/vrml"},
    {"vxml", "application/voicexml+xml"},
    {"wav", "audio/x-wav"},
    {"wbmp", "image/vnd.wap.wbmp"},
    {"wbmxl", "application/vnd.wap.wbxml"},
    {"wml", "text/vnd.wap.wml"},
    {"wmlc", "application/vnd.wap.wmlc"},
    {"wmls", "text/vnd.wap.wmlscript"},
    {"wmlsc", "application/vnd.wap.wmlscriptc"},
    {"wrl", "model/vrml"},
    {"xbm", "image/x-xbitmap"},
    {"xht", "application/xhtml+xml"},
    {"xhtml", "application/xhtml+xml"},
    {"xls", "application/vnd.ms-excel"},                        
    {"xml", "application/xml"},
    {"xpm", "image/x-xpixmap"},
    {"xsl", "application/xml"},
    {"xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {"xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
    {"xlsm","application/vnd.ms-excel.sheet.macroEnabled.12"},
    {"xltm","application/vnd.ms-excel.template.macroEnabled.12"},
    {"xlam","application/vnd.ms-excel.addin.macroEnabled.12"},
    {"xlsb","application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
    {"xslt", "application/xslt+xml"},
    {"xul", "application/vnd.mozilla.xul+xml"},
    {"xwd", "image/x-xwindowdump"},
    {"xyz", "chemical/x-xyz"},
    {"zip", "application/zip"}
  };

  public static string GetMIMEType(string fileName)
  {
    //get file extension
    string extension = Path.GetExtension(fileName).ToLowerInvariant();

    if (extension.Length > 0 && 
        MIMETypesDictionary.ContainsKey(extension.Remove(0, 1)))
    {
      return MIMETypesDictionary[extension.Remove(0, 1)];
    }
    return "unknown/unknown";
  }
}

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

Capture screenshot of active window?

You can use the code from this question: How can I save a screenshot directly to a file in Windows?

Just change WIN32_API.GetDesktopWindow() to the Handle property of the window you want to capture.

How to implement Enums in Ruby?

Another solution is using OpenStruct. Its pretty straight forward and clean.

https://ruby-doc.org/stdlib-2.3.1/libdoc/ostruct/rdoc/OpenStruct.html

Example:

# bar.rb
require 'ostruct' # not needed when using Rails

# by patching Array you have a simple way of creating a ENUM-style
class Array
   def to_enum(base=0)
      OpenStruct.new(map.with_index(base).to_h)
   end
end

class Bar

    MY_ENUM = OpenStruct.new(ONE: 1, TWO: 2, THREE: 3)
    MY_ENUM2 = %w[ONE TWO THREE].to_enum

    def use_enum (value)
        case value
        when MY_ENUM.ONE
            puts "Hello, this is ENUM 1"
        when MY_ENUM.TWO
            puts "Hello, this is ENUM 2"
        when MY_ENUM.THREE
            puts "Hello, this is ENUM 3"
        else
            puts "#{value} not found in ENUM"
        end
    end

end

# usage
foo = Bar.new    
foo.use_enum 1
foo.use_enum 2
foo.use_enum 9


# put this code in a file 'bar.rb', start IRB and type: load 'bar.rb'

How to get client IP address in Laravel 5+

Add namespace

use Request;

Then call the function

Request::ip();

How to read a file in Groovy into a string?

String fileContents = new File('/path/to/file').text

If you need to specify the character encoding, use the following instead:

String fileContents = new File('/path/to/file').getText('UTF-8')

git status shows modifications, git checkout -- <file> doesn't remove them

There are multiple problems the can cause this behaviour:

Line ending normalization

I've had these kinds of problems too. It comes down to git automatically converting crlf to lf. This is typically caused by mixed line endings in a single file. The file gets normalized in the index, but when git then denormalizes it again to diff it against the file in the working tree, the result is different.

But if you want to fix this, you should disable core.autocrlf, change all line endings to lf, and then enable it again. Or you can disable it altogether by doing:

git config --global core.autocrlf false

Instead of core.autocrlf, you can also consider using .gitattribute files. This way, you can make sure everyone using the repo uses the same normalization rules, preventing mixed line endings getting into the repository.

Also consider setting core.safecrlf to warn if you want git to warn you when a non-reversible normalization would be performed.

The git manpages say this:

CRLF conversion bears a slight chance of corrupting data. autocrlf=true will convert CRLF to LF during commit and LF to CRLF during checkout. A file that contains a mixture of LF and CRLF before the commit cannot be recreated by git. For text files this is the right thing to do: it corrects line endings such that we have only LF line endings in the repository. But for binary files that are accidentally classified as text the conversion can corrupt data.

Case-insensitive file systems

On case-insensitive filesystems, when the same filename with different casing is in the repository, git tries to checkout both, but only one ends up on the file system. When git tries to compare the second one, it would compare it to the wrong file.

The solution would either be switching to a non-case insensitive filesystem, but this in most cases is not feasible or renaming and committing one of the files on another filesystem.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

How to convert int[] to Integer[] in Java?

Convert int[] to Integer[]:

    import java.util.Arrays;
    ...

    int[] aint = {1,2,3,4,5,6,7,8,9,10};
    Integer[] aInt = new Integer[aint.length];

    Arrays.setAll(aInt, i -> aint[i]);

Formatting a Date String in React Native

The Date constructor is very picky about what it allows. The string you pass in must be supported by Date.parse(), and if it is unsupported, it will return NaN. Different versions of JavaScript do support different formats, if those formats deviate from the official ISO documentation.

See the examples here for what is supported: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Run local python script on remote server

You can do it via ssh.

ssh [email protected] "python ./hello.py"

You can also edit the script in ssh using a textual editor or X11 forwarding.

R: Break for loop

your break statement should break out of the for (in in 1:n).

Personally I am always wary with break statements and double check it by printing to the console to double check that I am in fact breaking out of the right loop. So before you test add the following statement, which will let you know if you break before it reaches the end. However, I have no idea how you are handling the variable n so I don't know if it would be helpful to you. Make a n some test value where you know before hand if it is supposed to break out or not before reaching n.

for (in in 1:n)
{
    if (in == n)         #add this statement
    {
        "sorry but the loop did not break"
    }

    id_novo <- new_table_df$ID[in]
    if(id_velho==id_novo)
    {
        break
    }
    else if(in == n)
    {
        sold_df <- rbind(sold_df,old_table_df[out,])
    }
}

WPF Button with Image

This should do the job, no?

<Button Content="Test">
    <Button.Background>
        <ImageBrush ImageSource="folder/file.PNG"/>
    </Button.Background>
</Button>

How to dockerize maven project? and how many ways to accomplish it?

Create a Dockerfile
#
# Build stage
#

FROM maven:3.6.3-jdk-11-slim AS build

WORKDIR usr/src/app

COPY . ./

RUN mvn clean package

#
# Package stage
#

FROM openjdk:11-jre-slim

ARG JAR_NAME="project-name"

WORKDIR /usr/src/app

EXPOSE ${HTTP_PORT}

COPY --from=build /usr/src/app/target/${JAR_NAME}.jar ./app.jar

CMD ["java","-jar", "./app.jar"]

How to compare strings in an "if" statement?

if(strcmp(aString, bString) == 0){
    //strings are the same
}

godspeed

What is the difference between OFFLINE and ONLINE index rebuild in SQL Server?

The main differences are:

1) OFFLINE index rebuild is faster than ONLINE rebuild.

2) Extra disk space required during SQL Server online index rebuilds.

3) SQL Server locks acquired with SQL Server online index rebuilds.

  • This schema modification lock blocks all other concurrent access to the table, but it is only held for a very short period of time while the old index is dropped and the statistics updated.

Hibernate Auto Increment ID

Do it as follows :-

@Id
@GenericGenerator(name="kaugen" , strategy="increment")
@GeneratedValue(generator="kaugen")
@Column(name="proj_id")
  public Integer getId() {
    return id;
 }

You can use any arbitrary name instead of kaugen. It worked well, I could see below queries on console

Hibernate: select max(proj_id) from javaproj
Hibernate: insert into javaproj (AUTH_email, AUTH_firstName, AUTH_lastName, projname,         proj_id) values (?, ?, ?, ?, ?)

How to change a field name in JSON using Jackson

There is one more option to rename field:

Jackson MixIns.

Useful if you deal with third party classes, which you are not able to annotate, or you just do not want to pollute the class with Jackson specific annotations.

The Jackson documentation for Mixins is outdated, so this example can provide more clarity. In essence: you create mixin class which does the serialization in the way you want. Then register it to the ObjectMapper:

objectMapper.addMixIn(ThirdParty.class, MyMixIn.class);

Convert object of any type to JObject with Json.NET

If you have an object and wish to become JObject you can use:

JObject o = (JObject)JToken.FromObject(miObjetoEspecial);

like this :

Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,
};

JObject o = (JObject)JToken.FromObject(pocionDeVida);
Console.WriteLine(o.ToString());
// {"tipo": "vida", "duracion": 32,}

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Xcode 6.1 - How to uninstall command line tools?

You can simply delete this folder

/Library/Developer/CommandLineTools

Please note: This is the root /Library, not user's ~/Library).

SQL, Postgres OIDs, What are they and why are they useful?

OID's are still in use for Postgres with large objects (though some people would argue large objects are not generally useful anyway). They are also used extensively by system tables. They are used for instance by TOAST which stores larger than 8KB BYTEA's (etc.) off to a separate storage area (transparently) which is used by default by all tables. Their direct use associated with "normal" user tables is basically deprecated.

The oid type is currently implemented as an unsigned four-byte integer. Therefore, it is not large enough to provide database-wide uniqueness in large databases, or even in large individual tables. So, using a user-created table's OID column as a primary key is discouraged. OIDs are best used only for references to system tables.

Apparently the OID sequence "does" wrap if it exceeds 4B 6. So in essence it's a global counter that can wrap. If it does wrap, some slowdown may start occurring when it's used and "searched" for unique values, etc.

See also https://wiki.postgresql.org/wiki/FAQ#What_is_an_OID.3F

Errno 13 Permission denied Python

Your user don't have the right permissions to read the file, since you used open() without specifying a mode.

Since you're using Windows, you should read a little more about File and Folder Permissions.

Also, if you want to play with your file permissions, you should right-click it, choose Properties and select Security tab.

Or if you want to be a little more hardcore, you can run your script as admin.

SO Related Questions:

Printing string variable in Java

You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,

Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);

Please read the tutorial on how to use it as it will explain all.

Edit
Please look here: Scanner tutorial

Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.

TypeError: Image data can not convert to float

I was also getting this error, and the answers given above says that we should upload them first and then use their name instead of a path - but for Kaggle dataset, this is not possible.

Hence the solution I figure out is by reading the the individual image in a loop in mpimg format. Here we can use the path and not just the image name.

I hope it will help you guys.

import matplotlib.image as mpimg
for img in os.listdir("/content/train"): 
  image = mpimg.imread(path)
  plt.imshow(image)
  plt.show()

How to edit my Excel dropdown list?

The answers above will work for changing the values.

If you want to change the number of cells in your list (e.g. I have a list called 'revisions' which has 4 items, I now need 7 items) you will find that you can't simply select your list and amend it on the sheet, So:

go to your 'Formulas' tab

choose "Name Manager"

a pop up box will show what is available for editing. Your list should be in it. Select your list and edit the range.

Why does dividing two int not yield the right value when assigned to double?

The important thing is one of the elements of calculation be a float-double type. Then to get a double result you need to cast this element like shown below:

c = static_cast<double>(a) / b;

or c = a / static_cast(b);

Or you can create it directly::

c = 7.0 / 3;

Note that one of elements of calculation must have the '.0' to indicate a division of a float-double type by an integer. Otherwise, despite the c variable be a double, the result will be zero too (an integer).

How do I download the Android SDK without downloading Android Studio?

Command-line approach

mkdir android-sdk
cd android-sdk
wget https://dl.google.com/android/repository/sdk-tools-linux-*.zip
unzip sdk-tools-linux-*.zip
tools/bin/sdkmanager --update

When executing the above commands, make sure that you replace * with an appropriate version number which you could find in the download page.

Installing packages

You can also use the sdkmanager to list and to install any specific packages needed.

tools/bin/sdkmanager --list
tools/bin/sdkmanager "platform-tools" "platforms;android–27" "build-tools;27.0.3"

FYI

sdk-tools-linux-*.zip only includes the command-line tools. This extracts content to a single directory named tools, like:

+- android-sdk
    +- tools

To get the SDK packages we could run:

tools/bin/sdkmanager --update

The sdkmanager accepts the following flag:

--sdk_root=<sdkRootPath>: Use the specified SDK root instead of the SDK 
                          containing this tool

But if we omit this flag, it assumes parent directory of tools directory as the sdk root, here in our case android-sdk directory.

If you check the android-sdk folder after running tools/bin/sdkmanager --update it will be like:

+- android-sdk
    +- tools
    +- emulator  
    +- platforms  
    +- platform-tool

If needed, also set ANDROID_HOME environment variable like:

export ANDROID_HOME=/path/to/android-sdk

Change image onmouseover

here's a native javascript inline code to change image onmouseover & onmouseout:

<a href="#" id="name">
    <img title="Hello" src="/ico/view.png" onmouseover="this.src='/ico/view.hover.png'" onmouseout="this.src='/ico/view.png'" />
</a>

Pandas read_csv low_memory and dtype options

I was facing a similar issue when processing a huge csv file (6 million rows). I had three issues:

  1. the file contained strange characters (fixed using encoding)
  2. the datatype was not specified (fixed using dtype property)
  3. Using the above I still faced an issue which was related with the file_format that could not be defined based on the filename (fixed using try .. except..)
    df = pd.read_csv(csv_file,sep=';', encoding = 'ISO-8859-1',
                     names=['permission','owner_name','group_name','size','ctime','mtime','atime','filename','full_filename'],
                     dtype={'permission':str,'owner_name':str,'group_name':str,'size':str,'ctime':object,'mtime':object,'atime':object,'filename':str,'full_filename':str,'first_date':object,'last_date':object})
    
    try:
        df['file_format'] = [Path(f).suffix[1:] for f in df.filename.tolist()]
    except:
        df['file_format'] = ''

How to add a new audio (not mixing) into a video using ffmpeg?

None of these solutions quite worked for me. My original audio was being overwritten, or I was getting an error like "failed to map memory" with the more complex 'amerge' example. It seems I needed -filter_complex amix.

ffmpeg -i videowithaudioyouwanttokeep.mp4 -i audiotooverlay.mp3 -vcodec copy -filter_complex amix -map 0:v -map 0:a -map 1:a -shortest -b:a 144k out.mkv

How many bytes is unsigned long long?

Use the operator sizeof, it will give you the size of a type expressed in byte. One byte is eight bits. See the following program:

#include <iostream>

int main(int,char**)
{
 std::cout << "unsigned long long " << sizeof(unsigned long long) << "\n";
 std::cout << "unsigned long long int " << sizeof(unsigned long long int) << "\n";
 return 0;
}

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

String.contains in Java

I will answer your question using a math analogy:

In this instance, the number 0 will represent no value. If you pick a random number, say 15, how many times can 0 be subtracted from 15? Infinite times because 0 has no value, thus you are taking nothing out of 15. Do you have difficulty accepting that 15 - 0 = 15 instead of ERROR? So if we switch this analogy back to Java coding, the String "" represents no value. Pick a random string, say "hello world", how many times can "" be subtracted from "hello world"?

Batch file to copy files from one folder to another folder

Look at rsync based Windows tool NASBackup. It will be a bonus if you are acquainted with rsync commands.

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

Convert .pfx to .cer

Might be irrelevant for OP's Q, but I've tried all openssl statements with all the different flags, while trying to connect with PHP \SoapClient(...) and after 3 days I finally found a solution that worked for me.

GitBash

$ cd path/to/certificate/
$ openssl pkcs12 -in personal_certificate.pfx -out public_key.pem -clcerts

First you have to enter YOUR_CERT_PASSWORD once, then DIFFERENT_PASSWORD! twice. The latter will possibly be available to everyone with access to code.

PHP

<?php

$wsdlUrl   = "https://example.com/service.svc?singlewsdl";
$publicKey = "rel/path/to/certificate/public_key.pem";
$password  = "DIFFERENT_PASSWORD!";

$params = [
    'local_cert' => $publicKey,
    'passphrase' => $password,
    'trace' => 1,
    'exceptions' => 0
];

$soapClient = new \SoapClient($wsdlUrl, $params);

var_dump($soapClient->__getFunctions());

How do you access the value of an SQL count () query in a Java program

It's similar to above but you can try like

public Integer count(String tableName) throws CrateException {
        String query = String.format("Select count(*) as size from %s", tableName);
        try (Statement s = connection.createStatement()) {
            try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
                Preconditions.checkArgument(resultSet.next(), "Result set is empty");
                return resultSet.getInt("size");
            }
        } catch (SQLException e) {
            throw new CrateException(e);
        }
    }
}

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

You can first insert data into blob field and then copy to text field with the folloing function

CREATE OR REPLACE FUNCTION blob2text() RETURNS void AS $$
Declare
    ref record;
    i integer;
Begin
    FOR ref IN SELECT id, blob_field FROM table LOOP

          --  find 0x00 and replace with space    
      i := position(E'\\000'::bytea in ref.blob_field);
      WHILE i > 0 LOOP
        ref.bob_field := set_byte(ref.blob_field, i-1, 20);
        i := position(E'\\000'::bytea in ref.blobl_field);
      END LOOP

    UPDATE table SET field = encode(ref.blob_field, 'escape') WHERE id = ref.id;
    END LOOP;

End; $$ LANGUAGE plpgsql; 

--

SELECT blob2text();

How to solve '...is a 'type', which is not valid in the given context'? (C#)

Change

private void Form1_Load(object sender, EventArgs e) 
    { 
        CERas.CERAS = new CERas.CERAS(); 
    } 

to

private void Form1_Load(object sender, EventArgs e) 
    { 
        CERas.CERAS c = new CERas.CERAS(); 
    } 

Or if you wish to use it later again

change it to

using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace WinApp_WMI2 
{ 
    public partial class Form1 : Form 
    { 
        CERas.CERAS m_CERAS;

        public Form1() 
        { 
            InitializeComponent(); 
        } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
        m_CERAS = new CERas.CERAS(); 
    } 
} 


}

How to find the minimum value in an ArrayList, along with the index number? (Java)

Here's what I do. I find the minimum first then after the minimum is found, it is removed from ArrayList.

ArrayList<Integer> a = new ArrayList<>();
a.add(3);
a.add(6);
a.add(2);
a.add(5);

while (a.size() > 0) {
    int min = 1000;
    for (int b:a) {
        if (b < min)
            min = b;
    }
    System.out.println("minimum: " + min);
    System.out.println("index of min: " + a.indexOf((Integer) min));
    a.remove((Integer) min);
}

How can one grab a stack trace in C?

For Windows check the StackWalk64() API (also on 32bit Windows). For UNIX you should use the OS' native way to do it, or fallback to glibc's backtrace(), if availabe.

Note however that taking a Stacktrace in native code is rarely a good idea - not because it is not possible, but because you're usally trying to achieve the wrong thing.

Most of the time people try to get a stacktrace in, say, an exceptional circumstance, like when an exception is caught, an assert fails or - worst and most wrong of them all - when you get a fatal "exception" or signal like a segmentation violation.

Considering the last issue, most of the APIs will require you to explicitly allocate memory or may do it internally. Doing so in the fragile state in which your program may be currently in, may acutally make things even worse. For example, the crash report (or coredump) will not reflect the actual cause of the problem, but your failed attempt to handle it).

I assume you're trying to achive that fatal-error-handling thing, as most people seem to try that when it comes to getting a stacktrace. If so, I would rely on the debugger (during development) and letting the process coredump in production (or mini-dump on windows). Together with proper symbol-management, you should have no trouble figuring the causing instruction post-mortem.

Most efficient way to check if a file is empty in Java on Windows

I combined the two best solutions to cover all the possibilities:

BufferedReader br = new BufferedReader(new FileReader(fileName));     
File file = new File(fileName);
if (br.readLine() == null && file.length() == 0)
{
    System.out.println("No errors, and file empty");
}                
else
{
    System.out.println("File contains something");
}

How to restrict the selectable date ranges in Bootstrap Datepicker?

The Bootstrap datepicker is able to set date-range. But it is not available in the initial release/Master Branch. Check the branch as 'range' there (or just see at https://github.com/eternicode/bootstrap-datepicker), you can do it simply with startDate and endDate.

Example:

$('#datepicker').datepicker({
    startDate: '-2m',
    endDate: '+2d'
});

Check line for unprintable characters while reading text file

How about below:

 FileReader fileReader = new FileReader(new File("test.txt"));

 BufferedReader br = new BufferedReader(fileReader);

 String line = null;
 // if no more lines the readLine() returns null
 while ((line = br.readLine()) != null) {
      // reading lines until the end of the file

 }

Source: http://devmain.blogspot.co.uk/2013/10/java-quick-way-to-read-or-write-to-file.html

"Insert if not exists" statement in SQLite

If you have a table called memos that has two columns id and text you should be able to do like this:

INSERT INTO memos(id,text) 
SELECT 5, 'text to insert' 
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');

If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.

I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.

I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer below.

An URL to a Windows shared folder

File protocol URIs are like this

file://[HOST]/[PATH]

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

So if the host is server01, you want

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

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

How do you use window.postMessage across domains?

Here is an example that works on Chrome 5.0.375.125.

The page B (iframe content):

<html>
    <head></head>
    <body>
        <script>
            top.postMessage('hello', 'A');
        </script>
    </body>
</html>

Note the use of top.postMessage or parent.postMessage not window.postMessage here

The page A:

<html>
<head></head>
<body>
    <iframe src="B"></iframe>
    <script>
        window.addEventListener( "message",
          function (e) {
                if(e.origin !== 'B'){ return; } 
                alert(e.data);
          },
          false);
    </script>
</body>
</html>

A and B must be something like http://domain.com

EDIT:

From another question, it looks the domains(A and B here) must have a / for the postMessage to work properly.

Hidden property of a button in HTML

It also works without jQuery if you do the following changes:

  1. Add type="button" to the edit button in order not to trigger submission of the form.

  2. Change the name of your function from change() to anything else.

  3. Don't use hidden="hidden", use CSS instead: style="display: none;".

The following code works for me:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">

<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
    <img src="dba_images/textfield_key.png" alt=""/>
    Edit
</button>

<button type="submit" class="positive" name="save" id="save" style="display:none;">
    <img src="dba_images/apply2.png" alt=""/>
    Save
</button>

<button class="regular" name="change" id="change" style="display:none;">
    <img src="dba_images/textfield_key.png" alt=""/>
    change
</button>

    <button class="negative" name="cancel" id="cancel" style="display:none;">
        <img src="dba_images/cross.png" alt=""/>
        Cancel
    </button>
</div>
</form>
</body>
</html>

Vue.js - How to properly watch for nested data

VueJs deep watch in child objects

new Vue({
    el: "#myElement",
    data: {
        entity: {
            properties: []
        }
    },
    watch: {
        'entity.properties': {
            handler: function (after, before) {
                // Changes detected. Do work...     
            },
            deep: true
        }
    }
});

Proper use cases for Android UserManager.isUserAGoat()?

As of API 21 (the first Android 5.0/Lollipop SDK), this detects whether the Goat Simulator app is installed:

/**
 * Used to determine whether the user making this call is subject to
 * teleportations.
 *
 * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
 * now automatically identify goats using advanced goat recognition technology.</p>
 *
 * @return Returns true if the user making this call is a goat.
 */
public boolean isUserAGoat() {
    return mContext.getPackageManager()
            .isPackageAvailable("com.coffeestainstudios.goatsimulator");
}

This should make it clear that djechlin's suggestion of using it as a warning-free if (false) is a potentially disastrous strategy. What previously returned false for every device now returns a seemingly random value: if this was buried deep enough in your code it could take a long time to figure out where your new bugs are coming from.

Bottom line: if you don't control the implementation of a method and decide to use it for purposes other than stated in the API documentation, you're heading for trouble.

Setting width and height

You can override the canvas style width !important ...

canvas{

  width:1000px !important;
  height:600px !important;

}

also

specify responsive:true, property under options..

options: {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero:true
            }
        }]
    }
}

update under options added : maintainAspectRatio: false,

link : http://codepen.io/theConstructor/pen/KMpqvo

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Defining array with multiple types in TypeScript

If you are interested in getting an array of either numbers or strings, you could define a type that will take an array of either

type Tuple = Array<number | string>
const example: Tuple = [1, "message"]
const example2: Tuple = ["message", 1]

If you expect an array of a specific order (i.e. number and a string)

type Tuple = [number, string]
const example: Tuple = [1, "message"]
const example2: Tuple = ["messsage", 1] // Type 'string' is not assignable to type 'number'.

Rendering an array.map() in React

Add up to Dmitry's answer, if you don't want to handle unique key IDs manually, you can use React.Children.toArray as proposed in the React documentation

React.Children.toArray

Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.

Note:

React.Children.toArray() changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.

 <div>
    <ul>
      {
        React.Children.toArray(
          this.state.data.map((item, i) => <li>Test</li>)
        )
      }
    </ul>
  </div>

Capturing URL parameters in request.GET

When a URL is like domain/search/?q=haha, you would use request.GET.get('q', '').

q is the parameter you want, and '' is the default value if q isn't found.

However, if you are instead just configuring your URLconf**, then your captures from the regex are passed to the function as arguments (or named arguments).

Such as:

(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),

Then in your views.py you would have

def profile_page(request, username):
    # Rest of the method

How to replace multiple strings in a file using PowerShell

One option is to chain the -replace operations together. The ` at the end of each line escapes the newline, causing PowerShell to continue parsing the expression on the next line:

$original_file = 'path\filename.abc'
$destination_file =  'path\filename.abc.new'
(Get-Content $original_file) | Foreach-Object {
    $_ -replace 'something1', 'something1aa' `
       -replace 'something2', 'something2bb' `
       -replace 'something3', 'something3cc' `
       -replace 'something4', 'something4dd' `
       -replace 'something5', 'something5dsf' `
       -replace 'something6', 'something6dfsfds'
    } | Set-Content $destination_file

Another option would be to assign an intermediate variable:

$x = $_ -replace 'something1', 'something1aa'
$x = $x -replace 'something2', 'something2bb'
...
$x

Underline text in UIlabel

You can use this my custom label! You can also use interface builder to set

import UIKit


class  YHYAttributedLabel : UILabel{
    
    
    @IBInspectable
    var underlineText : String = ""{
        
        didSet{

            self.attributedText = NSAttributedString(string: underlineText,
            attributes: [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue])
        }
        
        
    }

}

FB OpenGraph og:image not pulling images (possibly https?)

tl;dr – be patient

I ended up here because I was seeing blank images served from a https site. The problem was quite a different one though:

When content is shared for the first time, the Facebook crawler will scrape and cache the metadata from the URL shared. The crawler has to see an image at least once before it can be rendered. This means that the first person who shares a piece of content won't see a rendered image

[https://developers.facebook.com/docs/sharing/best-practices/#precaching]

While testing, it took facebook around 10 minutes to finally show the rendered image. So while I was scratching my head and throwing random og tags at facebook (and suspecting the https problem mentioned here), all I had to do was wait.

As this might really stop people from sharing your links for the first time, FB suggests two ways to circumvent this behavior: a) running the OG Debugger on all your links: the image will be cached and ready for sharing after ~10 minutes or b) specifying og:image:width and og:image:height. (Read more in the above link)

Still wondering though what takes them so long ...

how to use substr() function in jquery?

Extract characters from a string:

var str = "Hello world!";
var res = str.substring(1,4);

The result of res will be:

ell

http://www.w3schools.com/jsref/jsref_substring.asp

$('.dep_buttons').mouseover(function(){
    $(this).text().substring(0,25);
    if($(this).text().length > 30) {
        $(this).stop().animate({height:"150px"},150);
    }
    $(".dep_buttons").mouseout(function(){
        $(this).stop().animate({height:"40px"},150);
    });
});

Sql query to insert datetime in SQL Server

A more language-independent choice for string literals is the international standard ISO 8601 format "YYYY-MM-DDThh:mm:ss". I used the SQL query below to test the format, and it does indeed work in all SQL languages in sys.syslanguages:

declare @sql nvarchar(4000)

declare @LangID smallint
declare @Alias sysname

declare @MaxLangID smallint
select @MaxLangID = max(langid) from sys.syslanguages

set @LangID = 0

while @LangID <= @MaxLangID
begin

    select @Alias = alias
    from sys.syslanguages
    where langid = @LangID

    if @Alias is not null
    begin

        begin try
            set @sql = N'declare @TestLang table (langdate datetime)
    set language ''' + @alias + N''';
    insert into @TestLang (langdate)
    values (''2012-06-18T10:34:09'')'
            print 'Testing ' + @Alias

            exec sp_executesql @sql
        end try
        begin catch
            print 'Error in language ' + @Alias
            print ERROR_MESSAGE()
        end catch
    end

    select @LangID = min(langid)
    from sys.syslanguages
    where langid > @LangID
end

According to the String Literal Date and Time Formats section in Microsoft TechNet, the standard ANSI Standard SQL date format "YYYY-MM-DD hh:mm:ss" is supposed to be "multi-language". However, using the same query, the ANSI format does not work in all SQL languages.

For example, in Danish, you will many errors like the following:

Error in language Danish The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

If you want to build a query in C# to run on SQL Server, and you need to pass a date in the ISO 8601 format, use the Sortable "s" format specifier:

string.Format("select convert(datetime2, '{0:s}'", DateTime.Now);

How do I install cURL on cygwin?

From the documentation:

Installing and Updating Cygwin for 64-bit versions of Windows

Run setup-x86_64.exe any time you want to update or install a Cygwin package for 64-bit windows. The signature for setup-x86_64.exe can be used to verify the validity of this binary using this public key.

https://cygwin.com/install.html

String formatting in Python 3

That line works as-is in Python 3.

>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'

How can I read command line parameters from an R script?

A few points:

  1. Command-line parameters are accessible via commandArgs(), so see help(commandArgs) for an overview.

  2. You can use Rscript.exe on all platforms, including Windows. It will support commandArgs(). littler could be ported to Windows but lives right now only on OS X and Linux.

  3. There are two add-on packages on CRAN -- getopt and optparse -- which were both written for command-line parsing.

Edit in Nov 2015: New alternatives have appeared and I wholeheartedly recommend docopt.

SyntaxError: multiple statements found while compiling a single statement

A (partial) practical work-around is to put things into a throw-away function.

Pasting

x = 1
x += 1
print(x)

results in

>>> x = 1
x += 1
print(x)
  File "<stdin>", line 1
    x += 1
print(x)

    ^
SyntaxError: multiple statements found while compiling a single statement
>>>

However, pasting

def abc():
  x = 1
  x += 1
  print(x)

works:

>>> def abc():
  x = 1
  x += 1
  print(x)
>>> abc()
2
>>>

Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython / jupyter qtconsole is probably the next simplest option.

Powershell folder size of folders without listing Subdirectories

Interesting how powerful yet how helpless PS can be in the same time, coming from a Nix learning PS. after install crgwin/gitbash, you can do any combination in one commands:

size of current folder: du -sk .

size of all files and folders under current directory du -sk *

size of all subfolders (including current folders) find ./ -type d -exec du -sk {} \;

Load a WPF BitmapImage from a System.Drawing.Bitmap

It took me some time to get the conversion working both ways, so here are the two extension methods I came up with:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;

public static class BitmapConversion {

    public static Bitmap ToWinFormsBitmap(this BitmapSource bitmapsource) {
        using (MemoryStream stream = new MemoryStream()) {
            BitmapEncoder enc = new BmpBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(bitmapsource));
            enc.Save(stream);

            using (var tempBitmap = new Bitmap(stream)) {
                // According to MSDN, one "must keep the stream open for the lifetime of the Bitmap."
                // So we return a copy of the new bitmap, allowing us to dispose both the bitmap and the stream.
                return new Bitmap(tempBitmap);
            }
        }
    }

    public static BitmapSource ToWpfBitmap(this Bitmap bitmap) {
        using (MemoryStream stream = new MemoryStream()) {
            bitmap.Save(stream, ImageFormat.Bmp);

            stream.Position = 0;
            BitmapImage result = new BitmapImage();
            result.BeginInit();
            // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
            // Force the bitmap to load right now so we can dispose the stream.
            result.CacheOption = BitmapCacheOption.OnLoad;
            result.StreamSource = stream;
            result.EndInit();
            result.Freeze();
            return result;
        }
    }
}

Object creation on the stack/heap?

C++ offers three different ways to create objects:

  1. Stack-based such as temporary objects
  2. Heap-based by using new
  3. Static memory allocation such as global variables and namespace-scope objects

Consider your case,

Object* o;
o = new Object();

and:

Object* o = new Object();

Both forms are the same. This means that a pointer variable o is created on the stack (assume your variables does not belong to the 3 category above) and it points to a memory in the heap, which contains the object.

Cannot perform runtime binding on a null reference, But it is NOT a null reference

Set

 Dictionary<int, string> states = new Dictionary<int, string>()

as a property outside the function and inside the function insert the entries, it should work.

Re-enabling window.alert in Chrome

I can see that this only for actually turning the dialogs back on. But if you are a web dev and you would like to see a way to possibly have some form of notification when these are off...in the case that you are using native alerts/confirms for validation or whatever. Check this solution to detect and notify the user https://stackoverflow.com/a/23697435/1248536

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

How to set xampp open localhost:8080 instead of just localhost

Open XAMPP look below the X to close the program there is a Config option click it then click service and port settings then under Apache change your main port to whatever you changed it to in the config file then click save and your good to go.

Calling Web API from MVC controller

From my HomeController I want to call this Method and convert Json response to List

No you don't. You really don't want to add the overhead of an HTTP call and (de)serialization when the code is within reach. It's even in the same assembly!

Your ApiController goes against (my preferred) convention anyway. Let it return a concrete type:

public IEnumerable<QDocumentRecord> GetAllRecords()
{
    listOfFiles = ...
    return listOfFiles;
}

If you don't want that and you're absolutely sure you need to return HttpResponseMessage, then still there's absolutely no need to bother with calling JsonConvert.SerializeObject() yourself:

return Request.CreateResponse<List<QDocumentRecord>>(HttpStatusCode.OK, listOfFiles);

Then again, you don't want business logic in a controller, so you extract that into a class that does the work for you:

public class FileListGetter
{
    public IEnumerable<QDocumentRecord> GetAllRecords()
    {
        listOfFiles = ...
        return listOfFiles;
    }
}

Either way, then you can call this class or the ApiController directly from your MVC controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var listOfFiles = new DocumentsController().GetAllRecords();
        // OR
        var listOfFiles = new FileListGetter().GetAllRecords();

        return View(listOfFiles);
    }
}

But if you really, really must do an HTTP request, you can use HttpWebRequest, WebClient, HttpClient or RestSharp, for all of which plenty of tutorials exist.

How to get URI from an asset File?

Yeah you can't access your drive folder from you android phone or emulator because your computer and android are two different OS.I would go for res folder of android because it has good resources management methods. Until and unless you have very good reason to put you file in assets folder. Instead You can do this

try {
      Resources res = getResources();
      InputStream in_s = res.openRawResource(R.raw.yourfile);

      byte[] b = new byte[in_s.available()];
      in_s.read(b);
      String str = new String(b);
    } catch (Exception e) {
      Log.e(LOG_TAG, "File Reading Error", e);
 }

JUnit 4 compare Sets

Apache commons to the rescue again.

assertTrue(CollectionUtils.isEqualCollection(coll1, coll2));

Works like a charm. I don't know why but I found that with collections the following assertEquals(coll1, coll2) doesn't always work. In the case where it failed for me I had two collections backed by Sets. Neither hamcrest nor junit would say the collections were equal even though I knew for sure that they were. Using CollectionUtils it works perfectly.

Fix Access denied for user 'root'@'localhost' for phpMyAdmin

I had the same problem after i had changed the passwords in the database.. what i did was the editing of the updated password i had changed earlier and i didn't update in the config.inc.php and the same username under D:\xamp\phpMyAdmin\config.inc

$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = **'root'**;
$cfg['Servers'][$i]['password'] = **'epufhy**';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';

Subtracting two lists in Python

Python 2.7+ and 3.0 have collections.Counter (a.k.a. multiset). The documentation links to Recipe 576611: Counter class for Python 2.5:

from operator import itemgetter
from heapq import nlargest
from itertools import repeat, ifilter

class Counter(dict):
    '''Dict subclass for counting hashable objects.  Sometimes called a bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are stored as dictionary values.

    >>> Counter('zyzygy')
    Counter({'y': 3, 'z': 2, 'g': 1})

    '''

    def __init__(self, iterable=None, **kwds):
        '''Create a new, empty Counter object.  And if given, count elements
        from an input iterable.  Or, initialize the count from another mapping
        of elements to their counts.

        >>> c = Counter()                           # a new, empty counter
        >>> c = Counter('gallahad')                 # a new counter from an iterable
        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
        >>> c = Counter(a=4, b=2)                   # a new counter from keyword args

        '''        
        self.update(iterable, **kwds)

    def __missing__(self, key):
        return 0

    def most_common(self, n=None):
        '''List the n most common elements and their counts from the most
        common to the least.  If n is None, then list all element counts.

        >>> Counter('abracadabra').most_common(3)
        [('a', 5), ('r', 2), ('b', 2)]

        '''        
        if n is None:
            return sorted(self.iteritems(), key=itemgetter(1), reverse=True)
        return nlargest(n, self.iteritems(), key=itemgetter(1))

    def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        If an element's count has been set to zero or is a negative number,
        elements() will ignore it.

        '''
        for elem, count in self.iteritems():
            for _ in repeat(None, count):
                yield elem

    # Override dict methods where the meaning changes for Counter objects.

    @classmethod
    def fromkeys(cls, iterable, v=None):
        raise NotImplementedError(
            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

    def update(self, iterable=None, **kwds):
        '''Like dict.update() but add counts instead of replacing them.

        Source can be an iterable, a dictionary, or another Counter instance.

        >>> c = Counter('which')
        >>> c.update('witch')           # add elements from another iterable
        >>> d = Counter('watch')
        >>> c.update(d)                 # add elements from another counter
        >>> c['h']                      # four 'h' in which, witch, and watch
        4

        '''        
        if iterable is not None:
            if hasattr(iterable, 'iteritems'):
                if self:
                    self_get = self.get
                    for elem, count in iterable.iteritems():
                        self[elem] = self_get(elem, 0) + count
                else:
                    dict.update(self, iterable) # fast path when counter is empty
            else:
                self_get = self.get
                for elem in iterable:
                    self[elem] = self_get(elem, 0) + 1
        if kwds:
            self.update(kwds)

    def copy(self):
        'Like dict.copy() but returns a Counter instance instead of a dict.'
        return Counter(self)

    def __delitem__(self, elem):
        'Like dict.__delitem__() but does not raise KeyError for missing values.'
        if elem in self:
            dict.__delitem__(self, elem)

    def __repr__(self):
        if not self:
            return '%s()' % self.__class__.__name__
        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
        return '%s({%s})' % (self.__class__.__name__, items)

    # Multiset-style mathematical operations discussed in:
    #       Knuth TAOCP Volume II section 4.6.3 exercise 19
    #       and at http://en.wikipedia.org/wiki/Multiset
    #
    # Outputs guaranteed to only include positive counts.
    #
    # To strip negative and zero counts, add-in an empty counter:
    #       c += Counter()

    def __add__(self, other):
        '''Add counts from two counters.

        >>> Counter('abbb') + Counter('bcc')
        Counter({'b': 4, 'c': 2, 'a': 1})


        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem in set(self) | set(other):
            newcount = self[elem] + other[elem]
            if newcount > 0:
                result[elem] = newcount
        return result

    def __sub__(self, other):
        ''' Subtract count, but keep only results with positive counts.

        >>> Counter('abbbc') - Counter('bccd')
        Counter({'b': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem in set(self) | set(other):
            newcount = self[elem] - other[elem]
            if newcount > 0:
                result[elem] = newcount
        return result

    def __or__(self, other):
        '''Union is the maximum of value in either of the input counters.

        >>> Counter('abbb') | Counter('bcc')
        Counter({'b': 3, 'c': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        _max = max
        result = Counter()
        for elem in set(self) | set(other):
            newcount = _max(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result

    def __and__(self, other):
        ''' Intersection is the minimum of corresponding counts.

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        _min = min
        result = Counter()
        if len(self) < len(other):
            self, other = other, self
        for elem in ifilter(self.__contains__, other):
            newcount = _min(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result


if __name__ == '__main__':
    import doctest
    print doctest.testmod()

Then you can write

 a = Counter([0,1,2,1,0])
 b = Counter([0, 1, 1])
 c = a - b
 print list(c.elements())  # [0, 2]

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

how to show calendar on text box click in html

What you need is a jQuery UI Datepicker

Check out the demo and the source code.

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

React-Redux: Actions must be plain objects. Use custom middleware for async actions

Action Definition

const selectSlice = () => {
  return {
    type: 'SELECT_SLICE'
  }
};

Action Dispatch

store.dispatch({
  type:'SELECT_SLICE'
});

Make sure the object structure of action defined is same as action dispatched. In my case, while dispatching action, type was not assigned to property type.

Invalid self signed SSL cert - "Subject Alternative Name Missing"

Here is a very simple way to create an IP certificate that Chrome will trust.

The ssl.conf file...

[ req ]
default_bits       = 4096
distinguished_name = req_distinguished_name
req_extensions     = req_ext
prompt             = no

[ req_distinguished_name ]
commonName                  = 192.168.1.10

[ req_ext ]
subjectAltName = IP:192.168.1.10

Where, of course 192.168.1.10 is the local network IP we want Chrome to trust.

Create the certificate:

openssl genrsa -out key1.pem
openssl req -new -key key1.pem -out csr1.pem -config ssl.conf
openssl x509 -req -days 9999 -in csr1.pem -signkey key1.pem -out cert1.pem -extensions req_ext -extfile ssl.conf
rm csr1.pem

On Windows import the certificate into the Trusted Root Certificate Store on all client machines. On Android Phone or Tablet download the certificate to install it. Now Chrome will trust the certificate on windows and Android.

On windows dev box the best place to get openssl.exe is from "c:\Program Files\Git\usr\bin\openssl.exe"

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

wget is an invaluable resource and something I use myself. However sometimes there are characters in the address that wget identifies as syntax errors. I'm sure there is a fix for that, but as this question did not ask specifically about wget I thought I would offer an alternative for those people who will undoubtedly stumble upon this page looking for a quick fix with no learning curve required.

There are a few browser extensions that can do this, but most require installing download managers, which aren't always free, tend to be an eyesore, and use a lot of resources. Heres one that has none of these drawbacks:

"Download Master" is an extension for Google Chrome that works great for downloading from directories. You can choose to filter which file-types to download, or download the entire directory.

https://chrome.google.com/webstore/detail/download-master/dljdacfojgikogldjffnkdcielnklkce

For an up-to-date feature list and other information, visit the project page on the developer's blog:

http://monadownloadmaster.blogspot.com/

Spring @Autowired and @Qualifier

You can use @Qualifier along with @Autowired. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier

For Example in following case it is necessary provide a qualifier

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

EDIT:

In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
@RequiredArgsConstructor
public Payroll {
   @Qualifier("employee") private final Person person;
}

provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):

# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier

This was recently introduced in latest lombok 1.18.4.

NOTE

If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)

public Payroll {
   @Autowired @Qualifier("employee") private final Person person;
}

or

public Payroll {
   private final Person person;
   @Autowired
   @Qualifier("employee")
   public void setPerson(Person person) {
     this.person = person;
   } 
}

If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -

public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

INFO: No Spring WebApplicationInitializer types detected on classpath

I also had the same problem. My maven had tomcat7 plugin but the JRE environment was 1.6. I changed my tomcat7 to tomcat6 and the error was gone.

How can I toggle word wrap in Visual Studio?

In VS Code === Version: 1.52.1

  1. Open VS Code settings

  2. From the settings find the settings.json file and open it

  3. add this code - "editor.accessibilitySupport": "off"

If you already added "editor.accessibilitySupport" with the value "on" before then simply turn it to "off". This is the code worked for me when I faced the same problem while working with one of my JS Project.

How do I add a simple jQuery script to WordPress?

Beside putting the script in through functions you can "just" include a link ( a link rel tag that is) in the header, the footer, in any template, where ever. You just need to make sure the path is correct. I suggest using something like this (assuming you are in your theme's directory).

<script type="javascript" href="<?php echo get_template_directory_uri();?>/your-file.js"></script>

A good practice is to include this right before the closing body tag or at least just prior to your footer. You can also use php includes, or several other methods of pulling this file in.

<script type="javascript"><?php include('your-file.js');?></script>

Exception: Can't bind to 'ngFor' since it isn't a known native property

In angular 7 got this fixed by adding these lines to .module.ts file:

import { CommonModule } from '@angular/common'; imports: [CommonModule]

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

I want to delete all bin and obj folders to force all projects to rebuild everything

For the solution in batch. I am using the following command:

FOR /D /R %%G in (obj,bin) DO @IF EXIST %%G IF %%~aG geq d RMDIR /S /Q "%%G"


The reason not using DIR /S /AD /B xxx
1. DIR /S /AD /B obj will return empty list (at least on my Windows10) enter image description here
2. DIR /S /AD /B *obj will contain the result which is not expected (tobj folder) enter image description here

Simple way to create matrix of random numbers

You can drop the range(len()):

weights_h = [[random.random() for e in inputs[0]] for e in range(hiden_neurons)]

But really, you should probably use numpy.

In [9]: numpy.random.random((3, 3))
Out[9]:
array([[ 0.37052381,  0.03463207,  0.10669077],
       [ 0.05862909,  0.8515325 ,  0.79809676],
       [ 0.43203632,  0.54633635,  0.09076408]])

Perl: function to trim string leading and trailing whitespace

No, but you can use the s/// substitution operator and the \s whitespace assertion to get the same result.

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

I have a similar question here: Writting in sub-ndarray of a ndarray in the most pythonian way. Python 2 .

Following the solution of previous post for your case the solution looks like:

columns_to_keep = [1,3] 
rows_to_keep = [1,3]

An using ix_:

x[np.ix_(rows_to_keep, columns_to_keep)] 

Which is:

array([[ 5,  7],
       [13, 15]])

Pretty printing XML in Python

I had some problems with minidom's pretty print. I'd get a UnicodeError whenever I tried pretty-printing a document with characters outside the given encoding, eg if I had a ß in a document and I tried doc.toprettyxml(encoding='latin-1'). Here's my workaround for it:

def toprettyxml(doc, encoding):
    """Return a pretty-printed XML document in a given encoding."""
    unistr = doc.toprettyxml().replace(u'<?xml version="1.0" ?>',
                          u'<?xml version="1.0" encoding="%s"?>' % encoding)
    return unistr.encode(encoding, 'xmlcharrefreplace')

ASP.NET MVC DropDownListFor with model of type List<string>

To make a dropdown list you need two properties:

  1. a property to which you will bind to (usually a scalar property of type integer or string)
  2. a list of items containing two properties (one for the values and one for the text)

In your case you only have a list of string which cannot be exploited to create a usable drop down list.

While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:

@model List<string>
@Html.DropDownList(
    "Foo", 
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),
        "Value",
        "Text"
    )
)

where Foo will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:

<select name="Foo" id="Foo">
    <option value="item 1">item 1</option>
    <option value="item 2">item 2</option>
    <option value="item 3">item 3</option>
    ...
</select>

This being said a far better view model for a drop down list is the following:

public class MyListModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

and then:

@model MyListModel
@Html.DropDownListFor(
    x => x.SelectedItemId,
    new SelectList(Model.Items, "Value", "Text")
)

and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId property of this view model to the corresponding Value of some element in the Items collection.

Simplest way to have a configuration file in a Windows Forms C# application

Use:

System.Configuration.ConfigurationSettings.AppSettings["MyKey"];

AppSettings has been deprecated and is now considered obsolete (link).

In addition, the appSettings section of the app.config has been replaced by the applicationSettings section.

As someone else mentioned, you should be using System.Configuration.ConfigurationManager (link) which is new for .NET 2.0.

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

Classic mode (the only mode in IIS6 and below) is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. In fact, in this mode, ASP.NET is just an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). IIS just treats ASP.NET as an external plugin implemented in ISAPI and works with it like a black box (and only when it's needs to give out the request to ASP.NET). In this mode, ASP.NET is not much different from PHP or other technologies for IIS.

Integrated mode, on the other hand, is a new mode in IIS7 where IIS pipeline is tightly integrated (i.e. is just the same) as ASP.NET request pipeline. ASP.NET can see every request it wants to and manipulate things along the way. ASP.NET is no longer treated as an external plugin. It's completely blended and integrated in IIS. In this mode, ASP.NET HttpModules basically have nearly as much power as an ISAPI filter would have had and ASP.NET HttpHandlers can have nearly equivalent capability as an ISAPI extension could have. In this mode, ASP.NET is basically a part of IIS.

How to change credentials for SVN repository in Eclipse?

I'm using svn+ssh protocol to access SVN. What I had to do to fix a similar issue, was to open Putty and reconfigure it so that it did not have wrong_user_name@myserver but correct_user_name@myserver in the saved sessions.

How to initialize a vector of vectors on a struct?

You use new to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.

You have no reason to use new, since A is an automatic variable. You can simply initialise A using its constructor:

vector<vector<int> > A(dimension, vector<int>(dimension));

How to read a file into a variable in shell?

this works for me: v=$(cat <file_path>) echo $v

How to read from stdin line by line in Node

// Work on POSIX and Windows
var fs = require("fs");
var stdinBuffer = fs.readFileSync(0); // STDIN_FILENO = 0
console.log(stdinBuffer.toString());

Difference between sh and bash

Shell is an interface between a user and OS to access to an operating system's services. It can be either GUI or CLI (Command Line interface).

sh (Bourne shell) is a shell command-line interpreter, for Unix/Unix-like operating systems. It provides some built-in commands. In scripting language we denote interpreter as #!/bin/sh. It was one most widely supported by other shells like bash (free/open), kash (not free).

Bash (Bourne again shell) is a shell replacement for the Bourne shell. Bash is superset of sh. Bash supports sh. POSIX is a set of standards defining how POSIX-compliant systems should work. Bash is not actually a POSIX compliant shell. In a scripting language we denote the interpreter as #!/bin/bash.

Analogy:

  • Shell is like an interface or specifications or API.
  • sh is a class which implements the Shell interface.
  • Bash is a subclass of the sh.

enter image description here

Get div to take up 100% body height, minus fixed-height header and footer

Here's a solution that doesn't use negative margins or calc. Run the snippet below to see the final result.

Explanation

We give the header and the footer a fixed height of 30px and position them absolutely at the top and bottom, respectively. To prevent the content from falling underneath, we use two classes: below-header and above-footer to pad the div above and below with 30px.

All of the content is wrapped in a position: relative div so that the header and footer are at the top/bottom of the content and not the window.

We use the classes fit-to-parent and min-fit-to-parent to make the content fill out the page. This gives us a sticky footer which is at least as low as the window, but hidden if the content is longer than the window.

Inside the header and footer, we use the display: table and display: table-cell styles to give the header and footer some vertical padding without disrupting the shrink-wrap quality of the page. (Giving them real padding can cause the total height of the page to be more than 100%, which causes a scroll bar to appear when it isn't really needed.)

_x000D_
_x000D_
.fit-parent {_x000D_
    height: 100%;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
.min-fit-parent {_x000D_
    min-height: 100%;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
.below-header {_x000D_
    padding-top: 30px;_x000D_
}_x000D_
.above-footer {_x000D_
    padding-bottom: 30px;_x000D_
}_x000D_
.header {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    height: 30px;_x000D_
    width: 100%;_x000D_
}_x000D_
.footer {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
    height: 30px;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
/* helper classes */_x000D_
_x000D_
.padding-lr-small {_x000D_
    padding: 0 5px;_x000D_
}_x000D_
.relative {_x000D_
    position: relative;_x000D_
}_x000D_
.auto-scroll {_x000D_
  overflow: auto;_x000D_
}_x000D_
/* these two classes work together to create vertical centering */_x000D_
.valign-outer {_x000D_
    display: table;_x000D_
}_x000D_
.valign-inner {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<html class='fit-parent'>_x000D_
  <body class='fit-parent'>_x000D_
<div class='min-fit-parent auto-scroll relative' style='background-color: lightblue'>_x000D_
<div class='header valign-outer' style='background-color: black; color: white;'>_x000D_
        <div class='valign-inner padding-lr-small'>_x000D_
            My webpage_x000D_
        </div>_x000D_
    </div>_x000D_
    <div class='fit-parent above-footer below-header'>_x000D_
        <div class='fit-parent' id='main-inner'>_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
        </div>_x000D_
    </div>_x000D_
    <div class='footer valign-outer' style='background-color: white'>_x000D_
        <div class='valign-inner padding-lr-small'>_x000D_
            &copy; 2005 Old Web Design_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
    </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

How to correctly represent a whitespace character

Which whitespace character? The empty string is pretty unambiguous - it's a sequence of 0 characters. However, " ", "\t" and "\n" are all strings containing a single character which is characterized as whitespace.

If you just mean a space, use a space. If you mean some other whitespace character, there may well be a custom escape sequence for it (e.g. "\t" for tab) or you can use a Unicode escape sequence ("\uxxxx"). I would discourage you from including non-ASCII characters in your source code, particularly whitespace ones.

EDIT: Now that you've explained what you want to do (which should have been in your question to start with) you'd be better off using Regex.Split with a regular expression of \s which represents whitespace:

Regex regex = new Regex(@"\s");
string[] bits = regex.Split(text.ToLower());

See the Regex Character Classes documentation for more information on other character classes.

Create ArrayList from array

If you use :

new ArrayList<T>(Arrays.asList(myArray));

you may create and fill two lists ! Filling twice a big list is exactly what you don't want to do because it will create another Object[] array each time the capacity needs to be extended.

Fortunately the JDK implementation is fast and Arrays.asList(a[]) is very well done. It create a kind of ArrayList named Arrays.ArrayList where the Object[] data points directly to the array.

// in Arrays
@SafeVarargs
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}
//still in Arrays, creating a private unseen class
private static class ArrayList<E>

    private final E[] a;    
    ArrayList(E[] array) {
        a = array; // you point to the previous array
    }
    ....
}

The dangerous side is that if you change the initial array, you change the List ! Are you sure you want that ? Maybe yes, maybe not.

If not, the most understandable way is to do this :

ArrayList<Element> list = new ArrayList<Element>(myArray.length); // you know the initial capacity
for (Element element : myArray) {
    list.add(element);
}

Or as said @glglgl, you can create another independant ArrayList with :

new ArrayList<T>(Arrays.asList(myArray));

I love to use Collections, Arrays, or Guava. But if it don't fit, or you don't feel it, just write another inelegant line instead.

Websocket onerror - how to read error description?

Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).

you will almost never get these codes in practice so this code is pretty much pointless

var websocket;
if ("WebSocket" in window)
{
    websocket = new WebSocket("ws://yourDomainNameHere.org/");

    websocket.onopen = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
    };
    websocket.onclose = function (event) {
        var reason;
        alert(event.code);
        // See http://tools.ietf.org/html/rfc6455#section-7.4.1
        if (event.code == 1000)
            reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
        else if(event.code == 1001)
            reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
        else if(event.code == 1002)
            reason = "An endpoint is terminating the connection due to a protocol error";
        else if(event.code == 1003)
            reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
        else if(event.code == 1004)
            reason = "Reserved. The specific meaning might be defined in the future.";
        else if(event.code == 1005)
            reason = "No status code was actually present.";
        else if(event.code == 1006)
           reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
        else if(event.code == 1007)
            reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
        else if(event.code == 1008)
            reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
        else if(event.code == 1009)
           reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
        else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
            reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
        else if(event.code == 1011)
            reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
        else if(event.code == 1015)
            reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
        else
            reason = "Unknown reason";

        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
    };
    websocket.onmessage = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
    };
    websocket.onerror = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
    };
}
else
{
    alert("Websocket is not supported by your browser");
    return;
}

websocket.send("Yo wazzup");

websocket.close();

See http://jsfiddle.net/gr0bhrqr/

Multiple IF statements between number ranges

Shorter than accepted A, easily extensible and addresses 0 and below:

=if(or(A2<=0,A2>2000),"?",if(A2<500,"Less than 500","Between "&500*int(A2/500)&" and "&500*(int(A2/500)+1))) 

MySQL update CASE WHEN/THEN/ELSE

That's because you missed ELSE.

"Returns the result for the first condition that is true. If there was no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part." (http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case)

Force div element to stay in same place, when page is scrolled

There is something wrong with your code.

position : absolute makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll

This can be solved with position : fixed This property will make the element position fixed and still relative to the scroll.

Or

You can check it out Here

How to solve "The specified service has been marked for deletion" error

This can also be caused by leaving the Services console open. Windows won't actually delete the service until it is closed.

SELECTING with multiple WHERE conditions on same column

You can either use GROUP BY and HAVING COUNT(*) = _:

SELECT contact_id
FROM your_table
WHERE flag IN ('Volunteer', 'Uploaded', ...)
GROUP BY contact_id
HAVING COUNT(*) = 2 -- // must match number in the WHERE flag IN (...) list

(assuming contact_id, flag is unique).

Or use joins:

SELECT T1.contact_id
FROM your_table T1
JOIN your_table T2 ON T1.contact_id = T2.contact_id AND T2.flag = 'Uploaded'
-- // more joins if necessary
WHERE T1.flag = 'Volunteer'

If the list of flags is very long and there are lots of matches the first is probably faster. If the list of flags is short and there are few matches, you will probably find that the second is faster. If performance is a concern try testing both on your data to see which works best.

Setting Icon for wpf application (VS 08)

@742's answer works pretty well, but as outlined in the comments when running from the VS debugger the generic icon is still shown.

If you want to have your icon even when you're pressing F5, you can add in the Main Window:

<Window x:Class="myClass"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Icon="./Resources/Icon/myIcon.png">

where you indicate the path to your icon (the icon can be *.png, *.ico.)

(Note you will still need to set the Application Icon or it'll still be the default in Explorer).

Fastest way to flatten / un-flatten nested JSON objects

I wrote two functions to flatten and unflatten a JSON object.


Flatten a JSON object:

var flatten = (function (isArray, wrapped) {
    return function (table) {
        return reduce("", {}, table);
    };

    function reduce(path, accumulator, table) {
        if (isArray(table)) {
            var length = table.length;

            if (length) {
                var index = 0;

                while (index < length) {
                    var property = path + "[" + index + "]", item = table[index++];
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            } else accumulator[path] = table;
        } else {
            var empty = true;

            if (path) {
                for (var property in table) {
                    var item = table[property], property = path + "." + property, empty = false;
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            } else {
                for (var property in table) {
                    var item = table[property], empty = false;
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            }

            if (empty) accumulator[path] = table;
        }

        return accumulator;
    }
}(Array.isArray, Object));

Performance:

  1. It's faster than the current solution in Opera. The current solution is 26% slower in Opera.
  2. It's faster than the current solution in Firefox. The current solution is 9% slower in Firefox.
  3. It's faster than the current solution in Chrome. The current solution is 29% slower in Chrome.

Unflatten a JSON object:

function unflatten(table) {
    var result = {};

    for (var path in table) {
        var cursor = result, length = path.length, property = "", index = 0;

        while (index < length) {
            var char = path.charAt(index);

            if (char === "[") {
                var start = index + 1,
                    end = path.indexOf("]", start),
                    cursor = cursor[property] = cursor[property] || [],
                    property = path.slice(start, end),
                    index = end + 1;
            } else {
                var cursor = cursor[property] = cursor[property] || {},
                    start = char === "." ? index + 1 : index,
                    bracket = path.indexOf("[", start),
                    dot = path.indexOf(".", start);

                if (bracket < 0 && dot < 0) var end = index = length;
                else if (bracket < 0) var end = index = dot;
                else if (dot < 0) var end = index = bracket;
                else var end = index = bracket < dot ? bracket : dot;

                var property = path.slice(start, end);
            }
        }

        cursor[property] = table[path];
    }

    return result[""];
}

Performance:

  1. It's faster than the current solution in Opera. The current solution is 5% slower in Opera.
  2. It's slower than the current solution in Firefox. My solution is 26% slower in Firefox.
  3. It's slower than the current solution in Chrome. My solution is 6% slower in Chrome.

Flatten and unflatten a JSON object:

Overall my solution performs either equally well or even better than the current solution.

Performance:

  1. It's faster than the current solution in Opera. The current solution is 21% slower in Opera.
  2. It's as fast as the current solution in Firefox.
  3. It's faster than the current solution in Firefox. The current solution is 20% slower in Chrome.

Output format:

A flattened object uses the dot notation for object properties and the bracket notation for array indices:

  1. {foo:{bar:false}} => {"foo.bar":false}
  2. {a:[{b:["c","d"]}]} => {"a[0].b[0]":"c","a[0].b[1]":"d"}
  3. [1,[2,[3,4],5],6] => {"[0]":1,"[1][0]":2,"[1][1][0]":3,"[1][1][1]":4,"[1][2]":5,"[2]":6}

In my opinion this format is better than only using the dot notation:

  1. {foo:{bar:false}} => {"foo.bar":false}
  2. {a:[{b:["c","d"]}]} => {"a.0.b.0":"c","a.0.b.1":"d"}
  3. [1,[2,[3,4],5],6] => {"0":1,"1.0":2,"1.1.0":3,"1.1.1":4,"1.2":5,"2":6}

Advantages:

  1. Flattening an object is faster than the current solution.
  2. Flattening and unflattening an object is as fast as or faster than the current solution.
  3. Flattened objects use both the dot notation and the bracket notation for readability.

Disadvantages:

  1. Unflattening an object is slower than the current solution in most (but not all) cases.

The current JSFiddle demo gave the following values as output:

Nested : 132175 : 63
Flattened : 132175 : 564
Nested : 132175 : 54
Flattened : 132175 : 508

My updated JSFiddle demo gave the following values as output:

Nested : 132175 : 59
Flattened : 132175 : 514
Nested : 132175 : 60
Flattened : 132175 : 451

I'm not really sure what that means, so I'll stick with the jsPerf results. After all jsPerf is a performance benchmarking utility. JSFiddle is not.

Passing variable number of arguments around

You can use inline assembly for the function call. (in this code I assume the arguments are characters).

void format_string(char *fmt, ...);
void debug_print(int dbg_level, int numOfArgs, char *fmt, ...)
    {
        va_list argumentsToPass;
        va_start(argumentsToPass, fmt);
        char *list = new char[numOfArgs];
        for(int n = 0; n < numOfArgs; n++)
            list[n] = va_arg(argumentsToPass, char);
        va_end(argumentsToPass);
        for(int n = numOfArgs - 1; n >= 0; n--)
        {
            char next;
            next = list[n];
            __asm push next;
        }
        __asm push fmt;
        __asm call format_string;
        fprintf(stdout, fmt);
    }

Pointer to a string in C?

The very same. A C string is nothing but an array of characters, so a pointer to a string is a pointer to an array of characters. And a pointer to an array is the very same as a pointer to its first element.

ORA-00972 identifier is too long alias column name

As others have referred, names in Oracle SQL must be less or equal to 30 characters. I would add that this rule applies not only to table names but to field names as well. So there you have it.

T-sql - determine if value is integer

With sqlserver 2005 and later you can use regex-like character classes with LIKE operator. See here.

To check if a string is a non-negative integer (it is a sequence of decimal digits) you can test that it doesn't contain other characters.

SELECT numstr
  FROM table
 WHERE numstr NOT LIKE '%[^0-9]%'

Note1: This will return empty strings too.

Note2: Using LIKE '%[0-9]%' will return any string that contains at least a digit.

See fiddle

How to escape double quotes in a title attribute

It may work with any character from the HTML Escape character list, but I had the same problem with a Java project. I used StringEscapeUtils.escapeHTML("Testing \" <br> <p>") and the title was <a href=".." title="Test&quot; &lt;br&gt; &lt;p&gt;">Testing</a>.

It only worked for me when I changed the StringEscapeUtils to StringEscapeUtils.escapeJavascript("Testing \" <br> <p>") and it worked in every browser.

Android Studio rendering problems

Make sure your designer version and targetSdkVersion both is same. Example : If your targetSdkVersion is 22 then change your designer version also 22, so this problem do not occur.

Android Stop Emulator from Command Line

The other answer didn't work for me (on Windows 7). But this worked:

telnet localhost 5554
kill

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

I followed all the instructions in the anwers here, and I still couldn't get it to work. It seems WhatsApp also requires the extension for it to display the image.

So for a tag pointing to a jpeg:

<meta property="og:image" itemprop="image" content="https://example.com/someimageid"/>

Change the API to allow the extension and use:

<meta property="og:image" itemprop="image" content="https://example.com/someimageid.jpeg"/>

and it then seems to work...

Tuple unpacking in for loops

[i for i in enumerate(['a','b','c'])]

Result:

[(0, 'a'), (1, 'b'), (2, 'c')]

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

Check if there is anything to delete with :

ipcs -a | grep `whoami`

On linux delete them all via :

ipcs | nawk -v u=`whoami` '/Shared/,/^$/{ if($6==0&&$3==u) print "ipcrm shm",$2,";"}/Semaphore/,/^$/{ if($3==u) print "ipcrm sem",$2,";"}' | /bin/sh

For sun it would be :

ipcs -a | nawk -v u=`whoami` '$5==u &&(($1=="m" && $9==0)||($1=="s")){print "ipcrm -"$1,$2,";"}' | /bin/sh

courtsesy of di.uoa.gr

Check again if all is ok

For deleting your sems/shared mem - supposing you are a user in a workstation with no admin rights

add column to mysql table if it does not exist

Just tried the stored procedure script. Seems the problem is the ' marks around the delimiters. The MySQL Docs show that delimiter characters do not need the single quotes.

So you want:

delimiter //

Instead of:

delimiter '//'

Works for me :)

How to delete all files older than 3 days when "Argument list too long"?

To delete all files and directories within the current directory:

find . -mtime +3 | xargs rm -Rf

Or alternatively, more in line with the OP's original command:

find . -mtime +3 -exec rm -Rf -- {} \;

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

Python MYSQL update statement

Here is the correct way:

import MySQLdb

if __name__ == '__main__':
    connect = MySQLdb.connect(host="localhost", port=3306,
                              user="xxx", passwd="xxx", db='xxx', charset='utf8')

    cursor = connect.cursor()

    cursor.execute("""
       UPDATE tblTableName
       SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
       WHERE Server=%s
    """, (Year, Month, Day, Hour, Minute, ServerID))

    connect.commit()
    connect.close()

P.S. Don't forget connect.commit(), or it won't work

Sound alarm when code finishes

Kuchi's answer didn't work for me on OS X Yosemite (10.10.1). I did find the afplay command (here), which you can just call from Python. This works regardless of whether the Terminal audible bell is enabled and without a third-party library.

import os
os.system('afplay /System/Library/Sounds/Sosumi.aiff')

Sublime Text 2 Code Formatting

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

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

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

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


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

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

(as per comment by @Supr below)

How to upgrade pip3?

pip3 install --upgrade pip worked for me

Error: TypeError: $(...).dialog is not a function

I had a similar problem and in my case, the issue was different (I am using Django templates).

The order of JS was incorrect (I know that's the first thing you check but I was almost sure that that was not the case, but it was). The js calling the dialog was called before jqueryUI library was called.

I am using Django, so was inheriting a template and using {{super.block}} to inherit code from the block as well to the template. I had to move {{super.block}} at the end of the block which solved the issue. The js calling the dialog was declared in the Media class in Django's admin.py. I spent more than an hour to figure it out. Hope this helps someone.

How to import functions from different js file in a Vue+webpack+vue-loader project

I like the answer of Anacrust, though, by the fact "console.log" is executed twice, I would like to do a small update for src/mylib.js:

let test = {
  foo () { return 'foo' },
  bar () { return 'bar' },
  baz () { return 'baz' }
}

export default test

All other code remains the same...

Open File in Another Directory (Python)

Its a very old question but I think it will help newbies line me who are learning python. If you have Python 3.4 or above, the pathlib library comes with the default distribution.

To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest. To indicate that the path is a raw string, put r in front of the string with your actual path.

For example,

from pathlib import Path

dataFolder = Path(r'D:\Desktop dump\example.txt')

Source: The easy way to deal with file paths on Windows, Mac and Linux

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

How do I install SciPy on 64 bit Windows?

Try to install Python 2.6.3 over your 2.6.2 (this should also add correct Registry entry), or to register your existing installation using this script. Installer should work after that.

Building SciPy requires a Fortran compiler and libraries - BLAS and LAPACK.