Programs & Examples On #Mex bindings

How can I implement prepend and append with regular JavaScript?

In order to simplify your life you can extend the HTMLElement object. It might not work for older browsers, but definitely makes your life easier:

HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;

HTMLElement.prototype.prepend = function(element) {
    if (this.firstChild) {
        return this.insertBefore(element, this.firstChild);
    } else {
        return this.appendChild(element);
    }
};

So next time you can do this:

document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);

What's the regular expression that matches a square bracket?

If you're looking to find both variations of the square brackets at the same time, you can use the following pattern which defines a range of either the [ sign or the ] sign: /[\[\]]/

Python dictionary: are keys() and values() always the same order?

Found this:

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

On 2.x documentation and 3.x documentation.

How to compare two dates?

For calculating days in two dates difference, can be done like below:

import datetime
import math

issuedate = datetime(2019,5,9)   #calculate the issue datetime
current_date = datetime.datetime.now() #calculate the current datetime
diff_date = current_date - issuedate #//calculate the date difference with time also
amount = fine  #you want change

if diff_date.total_seconds() > 0.0:   #its matching your condition
    days = math.ceil(diff_date.total_seconds()/86400)  #calculate days (in 
    one day 86400 seconds)
    deductable_amount = round(amount,2)*days #calclulated fine for all days

Becuase if one second is more with the due date then we have to charge

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Vertical divider doesn't work in Bootstrap 3

may be this will help also:

.navbar .divider-vertical {
    margin-top: 14px;
    height: 24px;
    border-left: 1px solid #f2f2f2;
    border-image: linear-gradient(to bottom, gray, rgba(0, 0, 0, 0)) 1 100%;
}

MySQL, Concatenate two columns

In php, we have two option to concatenate table columns.

First Option using Query

In query, CONCAT keyword used to concatenate two columns

SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;

Second Option using symbol ( . )

After fetch the data from database table, assign the values to variable, then using ( . ) Symbol and concatenate the values

$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;

Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc

Unable to import path from django.urls

Use url instead of path.

from django.conf.urls import url

urlpatterns = [
    url('', views.homepageview, name='home')
]

How to get image width and height in OpenCV?

You can use rows and cols:

cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;

or size():

cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;

Iterating through a list to render multiple widgets in Flutter?

when you return some thing, the code exits out of the loop with what ever you are returning.so, in your code, in the first iteration, name is "one". so, as soon as it reaches return new Text(name), code exits the loop with return new Text("one"). so, try to print it or use asynchronous returns.

How do I read an attribute on a class at runtime?

public string GetDomainName<T>()
{
    var dnAttribute = typeof(T).GetCustomAttributes(
        typeof(DomainNameAttribute), true
    ).FirstOrDefault() as DomainNameAttribute;
    if (dnAttribute != null)
    {
        return dnAttribute.Name;
    }
    return null;
}

UPDATE:

This method could be further generalized to work with any attribute:

public static class AttributeExtensions
{
    public static TValue GetAttributeValue<TAttribute, TValue>(
        this Type type, 
        Func<TAttribute, TValue> valueSelector) 
        where TAttribute : Attribute
    {
        var att = type.GetCustomAttributes(
            typeof(TAttribute), true
        ).FirstOrDefault() as TAttribute;
        if (att != null)
        {
            return valueSelector(att);
        }
        return default(TValue);
    }
}

and use like this:

string name = typeof(MyClass)
    .GetAttributeValue((DomainNameAttribute dna) => dna.Name);

Replace multiple strings at once

You could use the replace method of the String object with a function in the second parameter:

First Method (using a find and replace Object)

var findreplace = {"<" : "&lt;", ">" : "&gt;", "\n" : "<br/>"};

textarea = textarea.replace(new RegExp("(" + Object.keys(findreplace).map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return findreplace[s]});

jsfiddle

Second method (using two arrays, find and replace)

var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];

textarea = textarea.replace(new RegExp("(" + find.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return replace[find.indexOf(s)]});

jsfiddle

Desired function:

function str_replace($f, $r, $s){
   return $s.replace(new RegExp("(" + $f.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return $r[$f.indexOf(s)]});
}

$textarea = str_replace($find, $replace, $textarea);

EDIT

This function admits a String or an Array as parameters:

function str_replace($f, $r, $s){
    return $s.replace(new RegExp("(" + (typeof($f) === "string" ? $f.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&") : $f.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|")) + ")", "g"), typeof($r) === "string" ? $r : typeof($f) === "string" ? $r[0] : function(i){ return $r[$f.indexOf(i)]});
}

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

This could, and probably should, be handled using refs:

"... you can use ReactDOM.findDOMNode as an "escape hatch" but we don't recommend it since it breaks encapsulation and in almost every case there's a clearer way to structure your code within the React model."

Example code:

class MyComponent extends React.Component {
    componentDidMount() {
        this._div.scrollTop = 0
    }

    render() {
        return <div ref={(ref) => this._div = ref} />
    }
}

git index.lock File exists when I try to commit, but cannot delete the file

On Linux, Unix, Git Bash, or Cygwin, try:

rm -f .git/index.lock

On Windows Command Prompt, try:

del .git\index.lock


For Windows:

  • From a PowerShell console opened as administrator, try

    rm -Force ./.git/index.lock
    
  • If that does not work, you must kill all git.exe processes

    taskkill /F /IM git.exe
    

    SUCCESS: The process "git.exe" with PID 20448 has been terminated.
    SUCCESS: The process "git.exe" with PID 11312 has been terminated.
    SUCCESS: The process "git.exe" with PID 23868 has been terminated.
    SUCCESS: The process "git.exe" with PID 27496 has been terminated.
    SUCCESS: The process "git.exe" with PID 33480 has been terminated.
    SUCCESS: The process "git.exe" with PID 28036 has been terminated. \

    rm -Force ./.git/index.lock
    

Can you remove elements from a std::list while iterating through it?

If you think of the std::list like a queue, then you can dequeue and enqueue all the items that you want to keep, but only dequeue (and not enqueue) the item you want to remove. Here's an example where I want to remove 5 from a list containing the numbers 1-10...

std::list<int> myList;

int size = myList.size(); // The size needs to be saved to iterate through the whole thing

for (int i = 0; i < size; ++i)
{
    int val = myList.back()
    myList.pop_back() // dequeue
    if (val != 5)
    {
         myList.push_front(val) // enqueue if not 5
    }
}

myList will now only have numbers 1-4 and 6-10.

Call php function from JavaScript

This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.

After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.

You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .

Plain Javascript

In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.

The javascript

// handles the click event for link 1, sends the query
function getOutput() {
  getRequest(
      'myAjax.php', // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  return false;
}  
// handles drawing an error message
function drawError() {
    var container = document.getElementById('output');
    container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return false;
            }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req.readyState == 4) {
            return req.status === 200 ? 
                success(req.responseText) : error(req.status);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}

The HTML

<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>

The PHP

// file myAjax.php
<?php
  echo 'hello world!';
?>

Try it out: http://jsfiddle.net/GRMule/m8CTk/


With a javascript library (jQuery et al)

Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.

Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:

// handles the click event, sends the query
function getOutput() {
   $.ajax({
      url:'myAjax.php',
      complete: function (response) {
          $('#output').html(response.responseText);
      },
      error: function () {
          $('#output').html('Bummer: there was an error!');
      }
  });
  return false;
}

Try it out: http://jsfiddle.net/GRMule/WQXXT/

Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.

If this is all you need to do, write the plain javascript once and you're done.

Documentation

Returning value from called function in a shell script

You are working way too hard. Your entire script should be:

if mkdir "$lockdir" 2> /dev/null; then 
  echo lock acquired
else
  echo could not acquire lock >&2
fi

but even that is probably too verbose. I would code it:

mkdir "$lockdir" || exit 1

but the resulting error message is a bit obscure.

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

The symptom of this problem is usually that the build works fine from the command line (which means your build.gradle file is set up right) but you get syntax highlighting errors in the IDE. Follow This Steps To Solve The Problem: Click on Tools from the toolbar usually at the top part of your IDE, and then navigate to Android then navigate to Sync Project with Gradle Files button. We realize it's less than ideal that the IDE can't just take care of itself instead of forcing you to manually sync at the right time; we're tracking progress on this in https://code.google.com/p/android/issues/detail?id=63151

Using CSS to insert text

The answer using jQuery that everyone seems to like has a major flaw, which is it is not scalable (at least as it is written). I think Martin Hansen has the right idea, which is to use HTML5 data-* attributes. And you can even use the apostrophe correctly:

html:

<div class="task" data-task-owner="Joe">mop kitchen</div>
<div class="task" data-task-owner="Charles" data-apos="1">vacuum hallway</div>

css:

div.task:before { content: attr(data-task-owner)"'s task - " ; }
div.task[data-apos]:before { content: attr(data-task-owner)"' task - " ; }

output:

Joe's task - mop kitchen
Charles' task - vacuum hallway

Meaning of tilde in Linux bash (not home directory)

Are they the home directories of users in /etc/passwd? Services like postgres, sendmail, apache, etc., create system users that have home directories just like normal users.

How do I `jsonify` a list in Flask?

This is working for me. Which version of Flask are you using?

from flask import jsonify

...

@app.route('/test/json')
def test_json():
    list = [
            {'a': 1, 'b': 2},
            {'a': 5, 'b': 10}
           ]
    return jsonify(results = list)

JSON and XML comparison

Before answering when to use which one, a little background:

edit: I should mention that this comparison is really from the perspective of using them in a browser with JavaScript. It's not the way either data format has to be used, and there are plenty of good parsers which will change the details to make what I'm saying not quite valid.

JSON is both more compact and (in my view) more readable - in transmission it can be "faster" simply because less data is transferred.

In parsing, it depends on your parser. A parser turning the code (be it JSON or XML) into a data structure (like a map) may benefit from the strict nature of XML (XML Schemas disambiguate the data structure nicely) - however in JSON the type of an item (String/Number/Nested JSON Object) can be inferred syntactically, e.g:

myJSON = {"age" : 12,
          "name" : "Danielle"}

The parser doesn't need to be intelligent enough to realise that 12 represents a number, (and Danielle is a string like any other). So in javascript we can do:

anObject = JSON.parse(myJSON);
anObject.age === 12 // True
anObject.name == "Danielle" // True
anObject.age === "12" // False

In XML we'd have to do something like the following:

<person>
    <age>12</age>
    <name>Danielle</name>
</person>

(as an aside, this illustrates the point that XML is rather more verbose; a concern for data transmission). To use this data, we'd run it through a parser, then we'd have to call something like:

myObject = parseThatXMLPlease();
thePeople = myObject.getChildren("person");
thePerson = thePeople[0];
thePerson.getChildren("name")[0].value() == "Danielle" // True
thePerson.getChildren("age")[0].value() == "12" // True

Actually, a good parser might well type the age for you (on the other hand, you might well not want it to). What's going on when we access this data is - instead of doing an attribute lookup like in the JSON example above - we're doing a map lookup on the key name. It might be more intuitive to form the XML like this:

<person name="Danielle" age="12" />

But we'd still have to do map lookups to access our data:

myObject = parseThatXMLPlease();
age = myObject.getChildren("person")[0].getAttr("age");

EDIT: Original:

In most programming languages (not all, by any stretch) a map lookup such as this will be more costly than an attribute lookup (like we got above when we parsed the JSON).

This is misleading: remember that in JavaScript (and other dynamic languages) there's no difference between a map lookup and a field lookup. In fact, a field lookup is just a map lookup.

If you want a really worthwhile comparison, the best is to benchmark it - do the benchmarks in the context where you plan to use the data.

As I have been typing, Felix Kling has already put up a fairly succinct answer comparing them in terms of when to use each one, so I won't go on any further.

Why is it said that "HTTP is a stateless protocol"?

What is stateless??

Once the request is made and the response is rendered back to the client the connection will be dropped or terminated. The server will forget all about the requester.

Why stateless??

The web chooses to go for the stateless protocol. It was a genius choice because the original goal of the web was to allow documents(web pages) to be served to extremely large no. of people using very basic hardware for the server.

Maintaining a long-running connection would have been extremely resource-intensive.

If the web were chosen the stateful protocol then the load on the server would have been increased to maintain the visitor's connection.

Comments in Markdown

If you are using Jekyll or octopress following will also work.

{% comment %} 
    These commments will not include inside the source.
{% endcomment %}

The Liquid tags {% comment %} are parsed first and removed before the MarkDown processor even gets to it. Visitors will not see when they try to view source from their browser.

Align labels in form next to input

You can also try using flex-box

<head><style>
body {
    color:white;
    font-family:arial;
    font-size:1.2em;
}
form {
    margin:0 auto;
    padding:20px;
    background:#444;
}
.input-group {
    margin-top:10px;
    width:60%;
    display:flex;
    justify-content:space-between;
    flex-wrap:wrap;
}
label, input {
    flex-basis:100px;
}
</style></head>
<body>

<form>
    <div class="wrapper">
        <div class="input-group">
            <label for="user_name">name:</label>
            <input type="text" id="user_name">
        </div>
        <div class="input-group">
            <label for="user_pass">Password:</label>
            <input type="password" id="user_pass">
        </div>
    </div>
</form>

</body>
</html>

remove attribute display:none; so the item will be visible

The removeAttr() function only removes HTML attributes. The display is not a HTML attribute, it's a CSS property. You'd like to use css() function instead to manage CSS properties.

But jQuery offers a show() function which does exactly what you want in a concise call:

$("span").show();

Capture Signature using HTML5 and iPad

The options already listed are very good, however here a few more on this topic that I've researched and came across.

1) http://perfectionkills.com/exploring-canvas-drawing-techniques/
2) http://mcc.id.au/2010/signature.html
3) https://zipso.net/a-simple-touchscreen-sketchpad-using-javascript-and-html5/

And as always you may want to save the canvas to image:
http://www.html5canvastutorials.com/advanced/html5-canvas-save-drawing-as-an-image/

good luck and happy signing

How to find if a native DLL file is compiled as x64 or x86?

Apparently you can find it in the header of the portable executable. The corflags.exe utility is able to show you whether or not it targets x64. Hopefully this helps you find more information about it.

How to export and import environment variables in windows?

A PowerShell script based on @Mithrl's answer

# export_env.ps1
$Date = Get-Date
$DateStr = '{0:dd-MM-yyyy}' -f $Date

mkdir -Force $PWD\env_exports | Out-Null

regedit /e "$PWD\env_exports\user_env_variables[$DateStr].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "$PWD\env_exports\global_env_variables[$DateStr].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

How can I use Helvetica Neue Condensed Bold in CSS?

After a lot of fiddling, got it working (only tested in Webkit) using:

font-family: "HelveticaNeue-CondensedBold";

font-stretch was dropped between CSS2 and 2.1, though is back in CSS3, but is only supported in IE9 (never thought I'd be able to say that about any CSS prop!)

This works because I'm using the postscript name (find the font in Font Book, hit cmd+I), which is non-standard behaviour. It's probably worth using:

font-family: "HelveticaNeue-CondensedBold", "Helvetica Neue";

As a fallback, else other browsers might default to serif if they can't work it out.

Demo: http://jsfiddle.net/ndFTL/12/

Java String encoding (UTF-8)

This could be complicated way of doing

String newString = new String(oldString);

This shortens the String is the underlying char[] used is much longer.

However more specifically it will be checking that every character can be UTF-8 encoded.

There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?

Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'

String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));

prints

false

How do I use a file grep comparison inside a bash if/else statement?

just use bash

while read -r line
do
  case "$line" in
    *MYSQL_ROLE=master*)
       echo "do your stuff";;
    *) echo "doesn't exist";;      
  esac
done <"/etc/aws/hosts.conf"

jQuery iframe load() event?

You may use the jquery's Contents method to get the content of the iframe.

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

when you are in El Capitan, will get error: ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted need to close the "System Integrity Protection".

first, reboot and hold on cmd + R to enter the Recovery mode, then launch the terminal and type the command: csrutil disable, now you can reboot and try again.

Embed HTML5 YouTube video without iframe?

Here is a example of embedding without an iFrame:

_x000D_
_x000D_
<div style="width: 560px; height: 315px; float: none; clear: both; margin: 2px auto;">
  <embed
    src="https://www.youtube.com/embed/J---aiyznGQ?autohide=1&autoplay=1"
    wmode="transparent"
    type="video/mp4"
    width="100%" height="100%"
    allow="autoplay; encrypted-media; picture-in-picture"
    allowfullscreen
    title="Keyboard Cat"
  >
</div>
_x000D_
_x000D_
_x000D_

compare to regular iframe "embed" code from YouTube:

_x000D_
_x000D_
<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/J---aiyznGQ?autoplay=1"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen>
</iframe>
_x000D_
_x000D_
_x000D_

and as far as HTML5 goes, use <object> tag like so (corrected):

_x000D_
_x000D_
<object
  style="width: 820px; height: 461.25px; float: none; clear: both; margin: 2px auto;"
  data="http://www.youtube.com/embed/J---aiyznGQ?autoplay=1">
</object>
_x000D_
_x000D_
_x000D_

How does C compute sin() and other math functions?

Yes, there are software algorithms for calculating sin too. Basically, calculating these kind of stuff with a digital computer is usually done using numerical methods like approximating the Taylor series representing the function.

Numerical methods can approximate functions to an arbitrary amount of accuracy and since the amount of accuracy you have in a floating number is finite, they suit these tasks pretty well.

How to pad a string to a fixed length with spaces in Python?

Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.

def format_string(str, min_length):
    while len(str) < min_length:
        str += " "
    return str

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

I had to be logged into Ubuntu as root in order to access Mariadb as root. It may have something to do with that "Harden ..." that it prompts you to do when you first install. So:

$ sudo su
[sudo] password for user: yourubunturootpassword
# mysql -r root -p
Enter password: yourmariadbrootpassword

and you're in.

Importing a long list of constants to a Python file

Try to look Create constants using a "settings" module? and Can I prevent modifying an object in Python?

Another one useful link: http://code.activestate.com/recipes/65207-constants-in-python/ tells us about the following option:

from copy import deepcopy

class const(object):

    def __setattr__(self, name, value):
        if self.__dict__.has_key(name):
            print 'NO WAY this is a const' # put here anything you want(throw exc and etc)
            return deepcopy(self.__dict__[name])
        self.__dict__[name] = value

    def __getattr__(self, name, value):
        if self.__dict__.has_key(name):
            return deepcopy(self.__dict__[name])

    def __delattr__(self, item):
        if self.__dict__.has_key(item):
            print 'NOOOOO' # throw exception if needed

CONST = const()
CONST.Constant1 = 111
CONST.Constant1 = 12
print a.Constant1 # 111
CONST.Constant2 = 'tst'
CONST.Constant2 = 'tst1'
print a.Constant2 # 'tst'

So you could create a class like this and then import it from you contants.py module. This will allow you to be sure that value would not be changed, deleted.

python: get directory two levels up

Very easy:

Here is what you want:

import os.path as path

two_up =  path.abspath(path.join(__file__ ,"../.."))

iOS: How to store username/password within an app?

To update this question:

For those using Swift checkout this drag and drop swift implementation by Mihai Costea supporting access groups:

https://github.com/macostea/KeychainItemWrapper.swift/blob/master/KeychainItemWrapper.swift

Before using the keychain: consider twice before storing passwords. In many cases storing an authentication token (such as a persistence session id) and the email or account name might be enough. You can easily invalidate authentication tokens to block unauthorized access, requiring the user to login again on the compromised device but not requiring reset password and having to login again on all devices (we are not only using Apple are we?).

MySQL DELETE FROM with subquery as condition

For others that find this question looking to delete while using a subquery, I leave you this example for outsmarting MySQL (even if some people seem to think it cannot be done):

DELETE e.*
FROM tableE e
WHERE id IN (SELECT id
             FROM tableE
             WHERE arg = 1 AND foo = 'bar');

will give you an error:

ERROR 1093 (HY000): You can't specify target table 'e' for update in FROM clause

However this query:

DELETE e.*
FROM tableE e
WHERE id IN (SELECT id
             FROM (SELECT id
                   FROM tableE
                   WHERE arg = 1 AND foo = 'bar') x);

will work just fine:

Query OK, 1 row affected (3.91 sec)

Wrap your subquery up in an additional subquery (here named x) and MySQL will happily do what you ask.

How does DHT in torrents work?

DHT nodes have unique identifiers, termed, Node ID. Node IDs are chosen at random from the same 160-bit space as BitTorrent info-hashes. Closeness is measured by comparing Node ID's routing tables, the closer the Node, the more detailed, resulting in optimal

What then makes them more optimal than it's predecessor "Kademlia" which used simple unsigned integers: distance(A,B) = |A xor B| Smaller values are closer. XOR. Besides not being secure, its logic was flawed.

If your client supports DHT, there are 8-bytes reserved in which contains 0x09 followed by a 2-byte payload with the UDP Port and DHT node. If the handshake is successful the above will continue.

How to delete all the rows in a table using Eloquent?

I wanted to add another option for those getting to this thread via Google. I needed to accomplish this, but wanted to retain my auto-increment value which truncate() resets. I also didn't want to use DB:: anything because I wanted to operate directly off of the model object. So, I went with this:

Model::whereNotNull('id')->delete();

Obviously the column will have to actually exists, but in a standard, out-of-the-box Eloquent model, the id column exists and is never null. I don't know if this is the best choice, but it works for my purposes.

How to get scrollbar position with Javascript?

I did this for a <div> on Chrome.

element.scrollTop - is the pixels hidden in top due to the scroll. With no scroll its value is 0.

element.scrollHeight - is the pixels of the whole div.

element.clientHeight - is the pixels that you see in your browser.

var a = element.scrollTop;

will be the position.

var b = element.scrollHeight - element.clientHeight;

will be the maximum value for scrollTop.

var c = a / b;

will be the percent of scroll [from 0 to 1].

How to echo text during SQL script execution in SQLPLUS

You can use SET ECHO ON in the beginning of your script to achieve that, however, you have to specify your script using @ instead of < (also had to add EXIT at the end):

test.sql

SET ECHO ON

SELECT COUNT(1) FROM dual;

SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

EXIT

terminal

sqlplus hr/oracle@orcl @/tmp/test.sql > /tmp/test.log

test.log

SQL> 
SQL> SELECT COUNT(1) FROM dual;

  COUNT(1)
----------
     1

SQL> 
SQL> SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

  COUNT(1)
----------
     2

SQL> 
SQL> EXIT

YouTube iframe API: how do I control an iframe player that's already in the HTML?

Thank you Rob W for your answer.

I have been using this within a Cordova application to avoid having to load the API and so that I can easily control iframes which are loaded dynamically.

I always wanted the ability to be able to extract information from the iframe, such as the state (getPlayerState) and the time (getCurrentTime).

Rob W helped highlight how the API works using postMessage, but of course this only sends information in one direction, from our web page into the iframe. Accessing the getters requires us to listen for messages posted back to us from the iframe.

It took me some time to figure out how to tweak Rob W's answer to activate and listen to the messages returned by the iframe. I basically searched through the source code within the YouTube iframe until I found the code responsible for sending and receiving messages.

The key was changing the 'event' to 'listening', this basically gave access to all the methods which were designed to return values.

Below is my solution, please note that I have switched to 'listening' only when getters are requested, you can tweak the condition to include extra methods.

Note further that you can view all messages sent from the iframe by adding a console.log(e) to the window.onmessage. You will notice that once listening is activated you will receive constant updates which include the current time of the video. Calling getters such as getPlayerState will activate these constant updates but will only send a message involving the video state when the state has changed.

function callPlayer(iframe, func, args) {
    iframe=document.getElementById(iframe);
    var event = "command";
    if(func.indexOf('get')>-1){
        event = "listening";
    }

    if ( iframe&&iframe.src.indexOf('youtube.com/embed') !== -1) {
      iframe.contentWindow.postMessage( JSON.stringify({
          'event': event,
          'func': func,
          'args': args || []
      }), '*');
    }
}
window.onmessage = function(e){
    var data = JSON.parse(e.data);
    data = data.info;
    if(data.currentTime){
        console.log("The current time is "+data.currentTime);
    }
    if(data.playerState){
        console.log("The player state is "+data.playerState);
    }
}

How to create an executable .exe file from a .m file

It used to be possible to compile Matlab to C with older versions of Matlab. Check out other tools that Matlab comes with.

Newest Matlab code can be exported as a Java's jar or a .Net Dll, etc. You can then write an executable against that library - it will be obfuscated by the way. The users will have to install a freely available Matlab Runtime.

Like others mentioned, mcc / mcc.exe is what you want to convert matlab code to C code.

SQL Server insert if not exists best practice

Additionally, if you have multiple columns to insert and want to check if they exists or not use the following code

Insert Into [Competitors] (cName, cCity, cState)
Select cName, cCity, cState from 
(
    select new.* from 
    (
        select distinct cName, cCity, cState 
        from [Competitors] s, [City] c, [State] s
    ) new
    left join 
    (   
        select distinct cName, cCity, cState 
        from [Competitors] s
    ) existing
    on new.cName = existing.cName and new.City = existing.City and new.State = existing.State
    where existing.Name is null  or existing.City is null or existing.State is null
)

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Where is SQL Server Management Studio 2012?

I found it here: http://www.microsoft.com/en-us/download/details.aspx?id=29062

This did not require any TechNet rigamarole or the use of their horrible Java 7 based download manager.

Responsive design with media query : screen size?

Take a look at this... http://getbootstrap.com/

For big websites I use Bootstrap and sometimes (for simple websites) I create all the style with some @mediaqueries. It's very simple, just think all the code in percentage.

.container {
max-width: 1200px;
width: 100%;
margin: 0 auto;
}

Inside the container, your structure must have widths in percentage like this...

.col-1 {
width: 40%;
float: left;
}

.col-2 {
width: 60%;
float: left;
}

@media screen and (max-width: 320px) {
.col-1, .col-2 { width: 100%; }
}

In some simple interfaces, if you start to develop the project in this way, you will have great chances to have a fully responsive site using break points only to adjust the flow of objects.

How to update-alternatives to Python 3 without breaking apt?

Per Debian policy, python refers to Python 2 and python3 refers to Python 3. Don't try to change this system-wide or you are in for the sort of trouble you already discovered.

Virtual environments allow you to run an isolated Python installation with whatever version of Python and whatever libraries you need without messing with the system Python install.

With recent Python 3, venv is part of the standard library; with older versions, you might need to install python3-venv or a similar package.

$HOME~$ python --version
Python 2.7.11

$HOME~$ python3 -m venv myenv
... stuff happens ...

$HOME~$ . ./myenv/bin/activate

(myenv) $HOME~$ type python   # "type" is preferred over which; see POSIX
python is /home/you/myenv/bin/python

(myenv) $HOME~$ python --version
Python 3.5.1

A common practice is to have a separate environment for each project you work on, anyway; but if you want this to look like it's effectively system-wide for your own login, you could add the activation stanza to your .profile or similar.

What is the difference between up-casting and down-casting with respect to class variable

Upcasting is casting to a supertype, while downcasting is casting to a subtype. Upcasting is always allowed, but downcasting involves a type check and can throw a ClassCastException.

In your case, a cast from a Dog to an Animal is an upcast, because a Dog is-a Animal. In general, you can upcast whenever there is an is-a relationship between two classes.

Downcasting would be something like this:

Animal animal = new Dog();
Dog castedDog = (Dog) animal;

Basically what you're doing is telling the compiler that you know what the runtime type of the object really is. The compiler will allow the conversion, but will still insert a runtime sanity check to make sure that the conversion makes sense. In this case, the cast is possible because at runtime animal is actually a Dog even though the static type of animal is Animal.

However, if you were to do this:

Animal animal = new Animal();
Dog notADog = (Dog) animal;

You'd get a ClassCastException. The reason why is because animal's runtime type is Animal, and so when you tell the runtime to perform the cast it sees that animal isn't really a Dog and so throws a ClassCastException.

To call a superclass's method you can do super.method() or by performing the upcast.

To call a subclass's method you have to do a downcast. As shown above, you normally risk a ClassCastException by doing this; however, you can use the instanceof operator to check the runtime type of the object before performing the cast, which allows you to prevent ClassCastExceptions:

Animal animal = getAnimal(); // Maybe a Dog? Maybe a Cat? Maybe an Animal?
if (animal instanceof Dog) {
    // Guaranteed to succeed, barring classloader shenanigans
    Dog castedDog = (Dog) animal;
}

C - The %x format specifier

The format string attack on printf you mentioned isn't specific to the "%x" formatting - in any case where printf has more formatting parameters than passed variables, it will read values from the stack that do not belong to it. You will get the same issue with %d for example. %x is useful when you want to see those values as hex.

As explained in previous answers, %08x will produce a 8 digits hex number, padded by preceding zeros.

Using the formatting in your code example in printf, with no additional parameters:

printf ("%08x %08x %08x %08x");

Will fetch 4 parameters from the stack and display them as 8-digits padded hex numbers.

What is <=> (the 'Spaceship' Operator) in PHP 7?

According to the RFC that introduced the operator, $a <=> $b evaluates to:

  • 0 if $a == $b
  • -1 if $a < $b
  • 1 if $a > $b

which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b will return

an integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b

Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort (and the similar uasort and uksort).

usort takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:

an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

The spaceship operator makes this succinct and convenient:

$things = [
    [
        'foo' => 5.5,
        'bar' => 'abc'
    ],
    [
        'foo' => 7.7,
        'bar' => 'xyz'
    ],
    [
        'foo' => 2.2,
        'bar' => 'efg'
    ]
];

// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
    return $a['foo'] <=> $b['foo'];
});

// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
    return $b['bar'] <=> $a['bar'];
});

More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.

How can you program if you're blind?

This blog post has some information about how the Visual Studio team is making their product accessible:

Visual Studio Core Team's Accessibility Lab Tour Activity

Many programmers use Emacspeak:

Emacspeak --The Complete Audio Desktop

How do I generate random number for each row in a TSQL Select?

It's as easy as:

DECLARE @rv FLOAT;
SELECT @rv = rand();

And this will put a random number between 0-99 into a table:

CREATE TABLE R
(
    Number int
)

DECLARE @rv FLOAT;
SELECT @rv = rand();

INSERT INTO dbo.R
(Number)
    values((@rv * 100));

SELECT * FROM R

How to find an object in an ArrayList by property

Here is a solution using Guava

private User findUserByName(List<User> userList, final String name) {
    Optional<User> userOptional =
            FluentIterable.from(userList).firstMatch(new Predicate<User>() {
                @Override
                public boolean apply(@Nullable User input) {
                    return input.getName().equals(name);
                }
            });
    return userOptional.isPresent() ? userOptional.get() : null; // return user if found otherwise return null if user name don't exist in user list
}

Unfinished Stubbing Detected in Mockito

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.

For mocking of void methods try out below:

//Kotlin Syntax

 Mockito.`when`(voidMethodCall())
           .then {
                Unit //Do Nothing
            }

How to install both Python 2.x and Python 3.x in Windows

I actually just thought of an interesting solution. While Windows will not allow you to easily alias programs, you can instead create renamed batch files that will call the current program.

Instead of renaming the executable which will break a lot of thing including pip, create the file python2.bat in the same directory as the python2.exe. Then add the following line:

%~dp0python %*

What does this archaic syntax mean? Well, it's a batch script, (Windows version of bash). %~dp0 gets the current directory and %* will just pass all the arguments to python that were passed to the script.

Repeat for python3.bat

You can also do the same for pip and other utilities, just replace the word python in the file with pip or whathever the filename. The alias will be whatever the file is named.

Best of all, when added to the PATH, Windows ignores the extension so running

python3

Will launch the python3 version and and the command python2 will launch the python2 version.

BTW, this is the same technique Spyder uses to add itself to the path on Windows. :)

Xamarin.Forms ListView: Set the highlight color of a tapped item

iOS

Solution:

Within a custom ViewCellRenderer you can set the SelectedBackgroundView. Simply create a new UIView with a background color of your choice and you're set.

public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
    var cell =  base.GetCell(item, reusableCell, tv);

    cell.SelectedBackgroundView = new UIView {
        BackgroundColor = UIColor.DarkGray,
    };

    return cell;
}

Result:

Note:

With Xamarin.Forms it seems to be important to create a new UIView rather than just setting the background color of the current one.


Android

Solution:

The solution I found on Android is a bit more complicated:

  1. Create a new drawable ViewCellBackground.xml within the Resources>drawable folder:

    <?xml version="1.0" encoding="UTF-8" ?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true" >
            <shape android:shape="rectangle">
                <solid android:color="#333333" />
            </shape>
        </item>
        <item>
            <shape android:shape="rectangle">
                <solid android:color="#000000" />
            </shape>
        </item>
    </selector>
    

    It defines solid shapes with different colors for the default state and the "pressed" state of a UI element.

  2. Use a inherited class for the View of your ViewCell, e.g.:

    public class TouchableStackLayout: StackLayout
    {
    }
    
  3. Implement a custom renderer for this class setting the background resource:

    public class ElementRenderer: VisualElementRenderer<Xamarin.Forms.View>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
        {
            SetBackgroundResource(Resource.Drawable.ViewCellBackground);
    
            base.OnElementChanged(e);
        }
    }
    

Result:

How to use sys.exit() in Python

Using 2.7:

from functools import partial
from random import randint

for roll in iter(partial(randint, 1, 8), 1):
    print 'you rolled: {}'.format(roll)
print 'oops you rolled a 1!'

you rolled: 7
you rolled: 7
you rolled: 8
you rolled: 6
you rolled: 8
you rolled: 5
oops you rolled a 1!

Then change the "oops" print to a raise SystemExit

Can I add jars to maven 2 build classpath without installing them?

You may create local repository on your project

For example if you have libs folder in project structure

  • In libs folder you should create directory structure like: /groupId/artifactId/version/artifactId-version.jar

  • In your pom.xml you should register repository

    <repository>
        <id>ProjectRepo</id>
        <name>ProjectRepo</name>
        <url>file://${project.basedir}/libs</url>
    </repository>
    
  • and add dependency as usual

    <dependency>
        <groupId>groupId</groupId>
        <artifactId>artifactId</artifactId>
        <version>version</version>
    </dependency>
    

That is all.

For detailed information: How to add external libraries in Maven

Getting Python error "from: can't read /var/mail/Bio"

I got same error because I was trying to run on

XXX-Macmini:Python-Project XXX.XXX$ from classDemo import MyClass

from: can't read /var/mail/classDemo

To solve this, type command python and when you get these >>> then run any python commands

>>>from classDemo import MyClass
>>>f = MyClass()

Mongoose: Get full list of users

My Solution

User.find()
        .exec()
        .then(users => {
            const response = {
                count: users.length,
                users: users.map(user => {

                    return {
                        _id: user._id,
                        // other property
                    }

                })

            };
            res.status(200).json(response);
        }).catch(err => {
        console.log(err);
        res.status(500).json({
            success: false
        })
    })

How to convert java.lang.Object to ArrayList?

The conversion fails (java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList) because you have surely some objects that are not ArrayList. verify the types of your different objects.

Find nginx version?

It seems that your nginx hasn't been installed correctly. Pay attention to the output of the installation commands:

sudo apt-get install nginx

To check the nginx version, you can use this command:

$ nginx -v
nginx version: nginx/0.8.54

$ nginx -V
nginx version: nginx/0.8.54
TLS SNI support enabled
configure arguments: --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-log-path=/var/log/nginx/access.log --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-debug --with-http_addition_module --with-http_dav_module --with-http_geoip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_realip_module --with-http_stub_status_module --with-http_ssl_module --with-http_sub_module --with-http_xslt_module --with-ipv6 --with-sha1=/usr/include/openssl --with-md5=/usr/include/openssl --with-mail --with-mail_ssl_module --add-module=/build/buildd/nginx-0.8.54/debian/modules/nginx-upstream-fair

For more information: http://nginxlibrary.com/check-nginx-version/

You can use -v parameter to display the Nginx version only, or use the -V parameter to display the version, along with the compiler version and configuration parameters.

How do I find all files containing specific text on Linux?

The below command will work fine for this approach:

find ./ -name "file_pattern_name"  -exec grep -r "pattern" {} \;

Matplotlib: Specify format of floats for tick labels

If you are directly working with matplotlib's pyplot (plt) and if you are more familiar with the new-style format string, you can try this:

from matplotlib.ticker import StrMethodFormatter
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal places
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places

From the documentation:

class matplotlib.ticker.StrMethodFormatter(fmt)

Use a new-style format string (as used by str.format()) to format the tick.

The field used for the value must be labeled x and the field used for the position must be labeled pos.

Addition for BigDecimal

It's actually rather easy. Just do this:

BigDecimal test = new BigDecimal(0);
System.out.println(test);
test = test.add(new BigDecimal(30));
System.out.println(test);
test = test.add(new BigDecimal(45));
System.out.println(test);

See also: BigDecimal#add(java.math.BigDecimal)

Java: Integer equals vs. ==

The JVM is caching Integer values. Hence the comparison with == only works for numbers between -128 and 127.

Refer: #Immutable_Objects_.2F_Wrapper_Class_Caching

getActivity() returns null in Fragment function

The other answers that suggest keeping a reference to the activity in onAttach are just suggesting a bandaid to the real problem. When getActivity returns null it means that the Fragment is not attached to the Activity. Most commonly this happens when the Activity has gone away due to rotation or the Activity being finished but the Fragment still has some kind of callback listener registered. When the listener gets called if you need to do something with the Activity but the Activity is gone there isn't much you can do. In your code you should just check getActivity() != null and if it's not there then don't do anything. If you keep a reference to the Activity that is gone you are preventing the Activity from being garbage collected. Any UI things you might try to do won't be seen by the user. I can imagine some situations where in the callback listener you want to have a Context for something non-UI related, in those cases it probably makes more sense to get the Application context. Note that the only reason that the onAttach trick isn't a big memory leak is because normally after the callback listener executes it won't be needed anymore and can be garbage collected along with the Fragment, all its View's and the Activity context. If you setRetainInstance(true) there is a bigger chance of a memory leak because the Activity field will also be retained but after rotation that could be the previous Activity not the current one.

How can I check if char* variable points to empty string?

Give it a chance:

Try getting string via function gets(string) then check condition as if(string[0] == '\0')

splitting a string into an array in C++ without using vector

#include <iostream>
#include <sstream>
#include <iterator>
#include <string>

using namespace std;

template <size_t N>
void splitString(string (&arr)[N], string str)
{
    int n = 0;
    istringstream iss(str);
    for (auto it = istream_iterator<string>(iss); it != istream_iterator<string>() && n < N; ++it, ++n)
        arr[n] = *it;
}

int main()
{
    string line = "test one two three.";
    string arr[4];

    splitString(arr, line);

    for (int i = 0; i < 4; i++)
       cout << arr[i] << endl;
}

What are .NET Assemblies?

Wikipedia has to say:

In the Microsoft .NET framework, an assembly is a partially compiled code library for use in deployment, versioning and security. There are two types: process assemblies (EXE) and library assemblies (DLL). A process assembly represents a process which will use classes defined in library assemblies. .NET assemblies contain code in CIL, which is usually generated from a CLI language, and then compiled into machine language at runtime by the CLR just-in-time compiler. An assembly can consist of one or more files. Code files are called modules. An assembly can contain more than one code module and since it is possible to use different languages to create code modules it is technically possible to use several different languages to create an assembly. Visual Studio however does not support using different languages in one assembly.

If you really did browse it would help if you'd clarify what you don't understand

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

TL;DR: Install Chocolatey, Node (and NPM)

Install Chocolatey

NOTE: You might want to copy the exact command from their install page since it might change over time.

  1. Open your standard Windows command line
  2. @powershell -NoProfile -ExecutionPolicy unrestricted -Command "(iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))) >$null 2>&1" && SET PATH="%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
  3. Restart console
  4. Done!

Install Node (and NPM)

  1. Because Chocolatey installs a directory different from the MSI installation, go to your system configuration and delete your previous node installation (if you have one)
  2. Install Chocolatey as described above
  3. choco install nodejs

    NOTE I used nodejs. I am not even sure what node is, but having had my fair share of troubles with node already being taken by something else in other systems, I thought, nodejs would be the safer bet right away

  4. Restart your console
  5. Beware: node -v works!
    • And npm -v also works! Awesome.

After this, I was able to install firebase-tools without problems (which I was not able to do previously), so something must have gone terribly right! :)

My rather complete story the first time around

"Chocolatey installs in seconds"

If you don't care about sarcasm or lamenting engineers on a Sunday afternoon, skip ahead to the installation instructions in the TL;DR section below.

For everyone else: I want to amend this answer which recommends using (what seems to be the hottest package management solution for Windows right now): Chocolatey

It gets the job done nice and quick. However, when I gave it a first try, it took me a while to make sense of the install instructions which are kinda convoluted. The install instructions go a bit like this (complete with what went through my head while going through it):

  • NOTE:
  • NOTE:
  • NOTE:

    three big-ass NOTEs before even knowing the basics... this makes me anxious... how wrong could things go!?

  • Installing With Restricted TLS

    not even sure what TLS is... Oh it's a good friend of SSL - Shouldn't this just be the default and just work out of the box? My browser can do HTTPS, NO PROBLEM! (just kidding... I know that SSL and TSL frequently cause a lot of pain in environments that have high security needs)

  • Option 1
  • Option 2

    eeh... great... Can't I just install?

  • Installing Behind a Proxy?

    Just... no...

  • Requirements

    uh boi...

  • Why does Chocolatey install where it does by default?

    Seriously!?!

  • Before You Install

    sad
    (source: clipartbest.com)

  • Can I install with a proxy?

    again with the proxy...

  • Can I install a particular version of Chocolatey?

    just any version would be fine, thank you...

  • Can I use Windows built-in compression instead of downloading 7zip?

    7zip?! Why do you even mention this?!

  • Non-Administrative Install
  • Now that sounds great!

    • "NOTE: This option should be a last resort and is considered to be an advanced scenario."
      • Sh$%!@T.

  • Alternative Installation Options

    giddy

  • Command Line
    • "This really is the easiest method because it requires no configuration of PowerShell prior to executing it."

      And there you go!

While I really appreciate the fact that pitfalls and their possible solutions are discussed so extensively, maybe re-organizing them as such, and putting the Chocolatey installs in seconds promise to work by putting the "easiest method" first would be just awesome!

Log4Net configuring log level

you can use log4net.Filter.LevelMatchFilter. other options can be found at log4net tutorial - filters

in ur appender section add

<filter type="log4net.Filter.LevelMatchFilter">
    <levelToMatch value="Info" />
    <acceptOnMatch value="true" />
</filter>

the accept on match default is true so u can leave it out but if u set it to false u can filter out log4net filters

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

SQL Server 2017 does introduce a new aggregate function

STRING_AGG ( expression, separator).

Concatenates the values of string expressions and places separator values between them. The separator is not added at the end of string.

The concatenated elements can be ordered by appending WITHIN GROUP (ORDER BY some_expression)

For versions 2005-2016 I typically use the XML method in the accepted answer.

This can fail in some circumstances however. e.g. if the data to be concatenated contains CHAR(29) you see

FOR XML could not serialize the data ... because it contains a character (0x001D) which is not allowed in XML.

A more robust method that can deal with all characters would be to use a CLR aggregate. However applying an ordering to the concatenated elements is more difficult with this approach.

The method of assigning to a variable is not guaranteed and should be avoided in production code.

When to use Task.Delay, when to use Thread.Sleep?

My opinion,

Task.Delay() is asynchronous. It doesn't block the current thread. You can still do other operations within current thread. It returns a Task return type (Thread.Sleep() doesn't return anything ). You can check if this task is completed(use Task.IsCompleted property) later after another time-consuming process.

Thread.Sleep() doesn't have a return type. It's synchronous. In the thread, you can't really do anything other than waiting for the delay to finish.

As for real-life usage, I have been programming for 15 years. I have never used Thread.Sleep() in production code. I couldn't find any use case for it. Maybe that's because I mostly do web application development.

Can Console.Clear be used to only clear a line instead of whole console?

I think I found why there are a few varying answers for this question. When the window has been resized such that it has a horizontal scroll bar (because the buffer is larger than the window) Console.CursorTop seems to return the wrong line. The following code works for me, regardless of window size or cursor position.

public static void ClearLine()
{
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, Console.CursorTop - (Console.WindowWidth >= Console.BufferWidth ? 1 : 0));
}

Without the (Console.WindowWidth >= Console.BufferWidth ? 1 : 0), the code may either move the cursor up or down, depending on which version you use from this page, and the state of the window.

numpy get index where value is true

You can use nonzero function. it returns the nonzero indices of the given input.

Easy Way

>>> (e > 15).nonzero()

(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

to see the indices more cleaner, use transpose method:

>>> numpy.transpose((e>15).nonzero())

[[1 6]
 [1 7]
 [1 8]
 [1 9]
 [2 0]
 ...

Not Bad Way

>>> numpy.nonzero(e > 15)

(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

or the clean way:

>>> numpy.transpose(numpy.nonzero(e > 15))

[[1 6]
 [1 7]
 [1 8]
 [1 9]
 [2 0]
 ...

How to post a file from a form with Axios

This works for me, I hope helps to someone.

var frm = $('#frm');
let formData = new FormData(frm[0]);
axios.post('your-url', formData)
    .then(res => {
        console.log({res});
    }).catch(err => {
        console.error({err});
    });

Best way to check that element is not present using Selenium WebDriver with java

Instead of doing findElement, do findElements and check the length of the returned elements is 0. This is how I'm doing using WebdriverJS and I expect the same will work in Java

Calculating time difference between 2 dates in minutes

ROUND(time_to_sec((TIMEDIFF(NOW(), "2015-06-10 20:15:00"))) / 60);

How do I make XAML DataGridColumns fill the entire DataGrid?

For those looking for a C# workaround:

If you need for some reason to have the "AutoGeneratedColumns" enabled, one thing you can do is to specify all the columns's width except the ones you want to be auto resized (it will not take the remaining space, but it will resize to the cell's content).

Example (dgShopppingCart is my DataGrid):

dgShoppingCart.Columns[0].Visibility = Visibility.Hidden; 
dgShoppingCart.Columns[1].Header = "Qty";
dgShoppingCart.Columns[1].Width = 100;
dgShoppingCart.Columns[2].Header = "Product Name"; /*This will be resized to cell content*/
dgShoppingCart.Columns[3].Header = "Price";
dgShoppingCart.Columns[3].Width = 100;
dgShoppingCart.Columns[4].Visibility = Visibility.Hidden; 

For me it works as a workaround because I needed to have the DataGrid resized when the user maximize the Window.

Python Decimals format

Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks.

So, I would use what Justin is suggesting:

>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'

Having the output of a console application in Visual Studio instead of the console

Instead, you can collect the output in a test result.

You can't supply input, but you can easily provide several tests with different command line arguments, each test collecting the output.

If your goal is debugging, this is a low effort way of offering a repeatable debugging scenario.

namespace Commandline.Test
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class CommandlineTests
    {
        [TestMethod]
        public void RunNoArguments()
        {
            Commandline.Program.Main(new string[0]);
        }
    }
}

How to show x and y axes in a MATLAB graph?

Inspired by @Luisa's answer, I made a function, axes0

x = linspace(-2,2,101);
plot(x,2*x.^3-3*x+1);
axes0

Example output for axes0

You can follow the link above to download the function and get more details on usage

How to check what version of jQuery is loaded?

// My original 'goto' means to get the version
$.fn.jquery

// Another *similar* option
$().jQuery

// If there is concern that there may be multiple implementations of `$` then:
jQuery.fn.jquery

Recently I have had issues using $.fn.jquery/$().jQuery on a few sites so I wanted to note a third simple command to pull the jQuery version.

If you get back a version number -- usually as a string -- then jQuery is loaded and that is what version you're working with. If not loaded then you should get back undefined or maybe even an error.

Pretty old question and I've seen a few people that have already mentioned my answer in comments. However, I find that sometimes great answers that are left as comments can go unnoticed; especially when there are a lot of comments to an answer you may find yourself digging through piles of them looking for a gem. Hopefully this helps someone out!

Visual Studio Code pylint: Unable to import 'protorpc'

I resolve this error by below step :

1 : first of all write this code in terminal :

...$ which python3
/usr/bin/python3

2 : Then :

"python.pythonPath": "/users/bin/python",

done.

The name 'ViewBag' does not exist in the current context

Try to Clean and rebuild. It worked in my case.

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

No alternative method is provided in the method's description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource file. See the sample code here: PreferenceActivity

Posting parameters to a url using the POST method without using a form

If you're trying to link to something, rather than do it from code you can redirect your request through: http://getaspost.appspot.com/

Why is a primary-foreign key relation required when we can join without it?

You don't need a FK, you can join arbitrary columns.

But having a foreign key ensures that the join will actually succeed in finding something.

Foreign key give you certain guarantees that would be extremely difficult and error prone to implement otherwise.

For example, if you don't have a foreign key, you might insert a detail record in the system and just after you checked that the matching master record is present somebody else deletes it. So in order to prevent this you need to lock the master table, when ever you modify the detail table (and vice versa). If you don't need/want that guarantee, screw the FKs.

Depending on your RDBMS a foreign key also might improve performance of select (but also degrades performance of updates, inserts and deletes)

MySql Table Insert if not exist otherwise update

I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:

replace into last_recogs (id, hasher_id, hash_id, last_recog) 
  select l.* from 
    (select id, hasher_id, hash_id, [new_value] from last_recogs 
     where hasher_id in (select id from hashers where name=[hasher_name])
     and hash_id in (select id from hashes where name=[hash_name]) 
     union 
     select 0, m.id, h.id, [new_value] 
     from hashers m cross join hashes h 
     where m.name=[hasher_name] 
     and h.name=[hash_name]) l 
  limit 1;

This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.

How to set app icon for Electron / Atom Shell App

For windows use Resource Hacker

Download and Install: :D

http://www.angusj.com/resourcehacker/

  • Run It
  • Select open and select exe file
  • On your left open a folder called Icon Group
  • Right click 1: 1033
  • Click replace icon
  • Select the icon of your choice
  • Then select replace icon
  • Save then close

You should have build the app

How to trigger click on page load?

try this,

$("document").ready(function(){

$("your id here").trigger("click");
});

How to delete a cookie?

would this work?

function eraseCookie(name) {
    document.cookie = name + '=; Max-Age=0'
}

I know Max-Age causes the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.

How to call Android contacts list?

        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
        while (phones.moveToNext())
        {
        String Name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
        String Number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        }

How to access array elements in a Django template?

Remember that the dot notation in a Django template is used for four different notations in Python. In a template, foo.bar can mean any of:

foo[bar]       # dictionary lookup
foo.bar        # attribute lookup
foo.bar()      # method call
foo[bar]       # list-index lookup

It tries them in this order until it finds a match. So foo.3 will get you your list index because your object isn't a dict with 3 as a key, doesn't have an attribute named 3, and doesn't have a method named 3.

mysql datetime comparison

...this is obviously performing a 'string' comparison

No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:

WHERE int_column = '1'

...where the string value of "1" is converted to an INTeger because int_column's data type is INT, not CHAR/VARCHAR/TEXT.

If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:

WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')

Resizing SVG in html?

Here is an example of getting the bounds using svg.getBox(): https://gist.github.com/john-doherty/2ad94360771902b16f459f590b833d44

At the end you get numbers that you can plug into the svg to set the viewbox properly. Then use any css on the parent div and you're done.

 // get all SVG objects in the DOM
 var svgs = document.getElementsByTagName("svg");
 var svg = svgs[0],
    box = svg.getBBox(), // <- get the visual boundary required to view all children
    viewBox = [box.x, box.y, box.width, box.height].join(" ");

    // set viewable area based on value above
    svg.setAttribute("viewBox", viewBox);

Run function in script from command line (Node JS)

simple way:

let's say you have db.js file in a helpers directory in project structure.

now go inside helpers directory and go to node console

 helpers $ node

2) require db.js file

> var db = require("./db")

3) call your function (in your case its init())

> db.init()

hope this helps

Windows batch script launch program and exit console

%ComSpec% /c %systemroot%\notepad.exe

Determine if two rectangles overlap each other?

struct Rect
{
   Rect(int x1, int x2, int y1, int y2)
   : x1(x1), x2(x2), y1(y1), y2(y2)
   {
       assert(x1 < x2);
       assert(y1 < y2);
   }

   int x1, x2, y1, y2;
};

//some area of the r1 overlaps r2
bool overlap(const Rect &r1, const Rect &r2)
{
    return r1.x1 < r2.x2 && r2.x1 < r1.x2 &&
           r1.y1 < r2.y2 && r2.x1 < r1.y2;
}

//either the rectangles overlap or the edges touch
bool touch(const Rect &r1, const Rect &r2)
{
    return r1.x1 <= r2.x2 && r2.x1 <= r1.x2 &&
           r1.y1 <= r2.y2 && r2.x1 <= r1.y2;
}

How to do something to each file in a directory with a batch script

Alternatively, use:

forfiles /s /m *.png /c "cmd /c echo @path"

The forfiles command is available in Windows Vista and up.

How to only get file name with Linux 'find'?

Use -execdir which automatically holds the current file in {}, for example:

find . -type f -execdir echo '{}' ';'

You can also use $PWD instead of . (on some systems it won't produce an extra dot in the front).

If you still got an extra dot, alternatively you can run:

find . -type f -execdir basename '{}' ';'

-execdir utility [argument ...] ;

The -execdir primary is identical to the -exec primary with the exception that utility will be executed from the directory that holds the current file.

When used + instead of ;, then {} is replaced with as many pathnames as possible for each invocation of utility. In other words, it'll print all filenames in one line.

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

How print out the contents of a HashMap<String, String> in ascending order based on its values?

 SmartPhone[] sp=new SmartPhone[4];
 sp[0]=new SmartPhone(1,"HTC","desire","black",20000,10,true,true);
 sp[1]=new SmartPhone(2,"samsung","grand","black",5000,10,false,true);
 sp[2]=new SmartPhone(14,"google nexus","desire","black",2000,30,true,false);
 sp[3]=new SmartPhone(13,"HTC","desire","white",50000,40,false,false);

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Another GUI based option to fix this error is to download the PackageManagement PowerShell Modules (msi installer) from Microsoft website and install the modules.

Once this is installed you will not get "'Install-Module' is not recognized as the name of a cmdlet" error.

How do I request and process JSON with python?

Python's standard library has json and urllib2 modules.

import json
import urllib2

data = json.load(urllib2.urlopen('http://someurl/path/to/json'))

Error occurred during initialization of boot layer FindException: Module not found

I had the same issue and I fixed it this way:

  1. Deleted all projects from eclipse, not from the computer.
  2. Created a new project and as soon as you write the name of your project, you get another window, in which is written: "Create module-info.java". I just clicked "don't create".
  3. Created a package. Let us call the package mywork.
  4. Created a Java class inside the package myWork. Let us call the class HelloWorld.
  5. I run the file normally and it was working fine.

Note: First, make sure that Java is running properly using the CMD command in that way you will understand the problem is on eclipse and not on JDK.

Get all validation errors from Angular 2 FormGroup

Based on the @MixerOID response, here is my final solution as a component (maybe I create a library). I also support FormArray's:

import {Component, ElementRef, Input, OnInit} from '@angular/core';
import {FormArray, FormGroup, ValidationErrors} from '@angular/forms';
import {TranslateService} from '@ngx-translate/core';

interface AllValidationErrors {
  controlName: string;
  errorName: string;
  errorValue: any;
}

@Component({
  selector: 'app-form-errors',
  templateUrl: './form-errors.component.html',
  styleUrls: ['./form-errors.component.scss']
})
export class FormErrorsComponent implements OnInit {

  @Input() form: FormGroup;
  @Input() formRef: ElementRef;
  @Input() messages: Array<any>;

  private errors: AllValidationErrors[];

  constructor(
    private translateService: TranslateService
  ) {
    this.errors = [];
    this.messages = [];
  }

  ngOnInit() {
    this.form.valueChanges.subscribe(() => {
      this.errors = [];
      this.calculateErrors(this.form);
    });

    this.calculateErrors(this.form);
  }

  calculateErrors(form: FormGroup | FormArray) {
    Object.keys(form.controls).forEach(field => {
      const control = form.get(field);
      if (control instanceof FormGroup || control instanceof FormArray) {
        this.errors = this.errors.concat(this.calculateErrors(control));
        return;
      }

      const controlErrors: ValidationErrors = control.errors;
      if (controlErrors !== null) {
        Object.keys(controlErrors).forEach(keyError => {
          this.errors.push({
            controlName: field,
            errorName: keyError,
            errorValue: controlErrors[keyError]
          });
        });
      }
    });

    // This removes duplicates
    this.errors = this.errors.filter((error, index, self) => self.findIndex(t => {
      return t.controlName === error.controlName && t.errorName === error.errorName;
    }) === index);
    return this.errors;
  }

  getErrorMessage(error) {
    switch (error.errorName) {
      case 'required':
        return this.translateService.instant('mustFill') + ' ' + this.messages[error.controlName];
      default:
        return 'unknown error ' + error.errorName;
    }
  }
}

And the HTML:

<div *ngIf="formRef.submitted">
  <div *ngFor="let error of errors" class="text-danger">
    {{getErrorMessage(error)}}
  </div>
</div>

Usage:

<app-form-errors [form]="languageForm"
                 [formRef]="formRef"
                 [messages]="{language: 'Language'}">
</app-form-errors>

In Angular, how to add Validator to FormControl after control is created?

You simply pass the FormControl an array of validators.

Here's an example showing how you can add validators to an existing FormControl:

this.form.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);

Note, this will reset any existing validators you added when you created the FormControl.

Maven is not working in Java 8 when Javadoc tags are incomplete

I'm a bit late to the party, but I was forced to search for workaround too, ended up here, and then found it.

Here's what works for me:-

export JAVA_TOOL_OPTIONS=-DadditionalJOption=-Xdoclint:none

And then start your Maven build, any Linux distribution build etc. Nice thing about it that it doesn't require Maven config files modification - I couldn't do that as my objective was to rebuild a bunch of Centos rpm packages, so had to go really deep.

Eclipse reports rendering library more recent than ADT plug-in

  1. Click Help > Install New Software.
  2. In the Work with field, enter: https://dl-ssl.google.com/android/eclipse/
  3. Select Developer Tools / Android Development Tools.
  4. Click Next and complete the wizard.

Replace multiple characters in one replace call

I don't know if how much this will help but I wanted to remove <b> and </b> from my string

so I used

mystring.replace('<b>',' ').replace('</b>','');

so basically if you want a limited number of character to be reduced and don't waste time this will be useful.

jquery .on() method with load event

To run function onLoad

jQuery(window).on("load", function(){
    ..code..
});

To run code onDOMContentLoaded (also called onready)

jQuery(document).ready(function(){
    ..code..
});

or the recommended shorthand for onready

jQuery(function($){
    ..code.. ($ is the jQuery object)
});

onready fires when the document has loaded

onload fires when the document and all the associated content, like the images on the page have loaded.

Using AND/OR in if else PHP statement

"AND" does not work in my PHP code.

Server's version maybe?

"&&" works fine.

Why doesn't [01-12] range work as expected?

As polygenelubricants says yours would look for 0|1-1|2 rather than what you wish for, due to the fact that character classes (things in []) match characters rather than strings.

Query to convert from datetime to date mysql

Use the DATE function:

SELECT DATE(orders.date_purchased) AS date

Configure apache to listen on port other than 80

Open httpd.conf file in your text editor. Find this line:

Listen 80

and change it

Listen 8079

After change, save it and restart apache.

Django - Did you forget to register or load this tag?

I had the same problem, here's how I solved it. Following the first section of this very excellent Django tutorial, I did the following:

  1. Create a new Django app by executing: python manage.py startapp new_app
  2. Edit the settings.py file, adding the following to the list of INSTALLED_APPS: 'new_app',
  3. Add a new module to the new_app package named new_app_tags.
  4. In a Django HTML template, add the following to the top of the file, but after {% extends 'base_template_name.html' %}: {% load new_app_tags %}
  5. In the new_app_tags module file, create a custom template tag (see below).
  6. In the same Django HTML template, from step 4 above, use your shiney new custom tag like so: {% multiply_by_two | "5.0" %}
  7. Celebrate!

Example from step 5 above:

from django import template

register = template.Library()

@register.simple_tag
def multiply_by_two(value):
    return float(value) * 2.0

How to find out line-endings in a text file?

You can use the file utility to give you an indication of the type of line endings.

Unix:

$ file testfile1.txt
testfile.txt: ASCII text

"DOS":

$ file testfile2.txt
testfile2.txt: ASCII text, with CRLF line terminators

To convert from "DOS" to Unix:

$ dos2unix testfile2.txt

To convert from Unix to "DOS":

$ unix2dos testfile1.txt

Converting an already converted file has no effect so it's safe to run blindly (i.e. without testing the format first) although the usual disclaimers apply, as always.

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

ORA-12154: TNS:could not resolve the connect identifier specified?

In case the TNS is not defined you can also try this one:

If you are using C#.net 2010 or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:

static string constr = @"Data Source=(DESCRIPTION=
    (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
    (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
    User Id=system ;Password=yourpasswrd"; 

After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified then first you have to do restart your system and run your project.

And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:

Oracle Data Provider for .NET 2.0

Oracle Providers for ASP.NET

Oracle Developer Tools for Visual Studio

Oracle Instant Client 

And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

If you still have problem then please try this.

Build Settings -> User Defined -> Provisioning profile (Remove this.)

It will solved my issue.

Thanks

How to remove all options from a dropdown using jQuery / JavaScript

In case .empty() doesn't work for you, which is for me

function SetDropDownToEmpty() 
{           
$('#dropdown').find('option').remove().end().append('<option value="0"></option>');
$("#dropdown").trigger("liszt:updated");          
}

$(document).ready(
SetDropDownToEmpty() ;
)

Tainted canvases may not be exported

For security reasons, your local drive is declared to be "other-domain" and will taint the canvas.

(That's because your most sensitive info is likely on your local drive!).

While testing try these workarounds:

  • Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders).

  • Post your images to a site that supports cross-domain sharing (like dropbox.com). Be sure you put your images in dropbox's public folder and also set the cross origin flag when downloading the image (var img=new Image(); img.crossOrigin="anonymous" ...)

  • Install a webserver on your development computer (IIS and PHP web servers both have free editions that work nicely on a local computer).

How to use the priority queue STL for objects?

You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person in this case. The default is to use std::less<T>, which resolves to something equivalent to operator<. This relies on it's own stored type having one. So if you were to implement

bool operator<(const Person& lhs, const Person& rhs); 

it should work without any further changes. The implementation could be

bool operator<(const Person& lhs, const Person& rhs)
{
  return lhs.age < rhs.age;
}

If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>. For example,

struct LessThanByAge
{
  bool operator()(const Person& lhs, const Person& rhs) const
  {
    return lhs.age < rhs.age;
  }
};

then instantiate the queue like this:

std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;

Concerning the use of std::greater<Person> as comparator, this would use the equivalent of operator> and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator> that can operate on two Person instances.

How to use pip with python 3.4 on windows?

Assuming you don't have any other Python installations, you should be able to do python -m pip after a default installation. Something like the following should be in your system path:

C:\Python34\Scripts

This would obviously be different, if you installed Python in a different location.

javascript toISOString() ignores timezone offset

Moment js solution to this is

var d = new Date(new Date().setHours(0,0,0,0));
m.add(m.utcOffset(), 'm')
m.toDate().toISOString()
// output "2019-07-18T00:00:00.000Z"

Get timezone from users browser using moment(timezone).js

Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

i notice they also user their own library in their website, so you can have a try using the browser console before installing it

moment().tz(String);

The moment#tz mutator will change the time zone and update the offset.

moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z');   // +01:00

This information is used consistently in other operations, like calculating the start of the day.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format();                     // 2013-11-18T11:55:00-05:00
m.startOf("day").format();      // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format();      // 2013-11-18T00:00:00+01:00

Without an argument, moment#tz returns:

    the time zone name assigned to the moment instance or
    undefined if a time zone has not been set.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz();  // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined;  // true

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

How to get Spinner selected item value to string?

Try this:

String text = mySpinner.getSelectedItem().toString();

Like this you can get value for different Spinners.

Can I load a UIImage from a URL?

Check out the AsyncImageView provided over here. Some good example code, and might even be usable right "out of the box" for you.

Pass request headers in a jQuery AJAX GET call

As of jQuery 1.5, there is a headers hash you can pass in as follows:

$.ajax({
    url: "/test",
    headers: {"X-Test-Header": "test-value"}
});

From http://api.jquery.com/jQuery.ajax:

headers (added 1.5): A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

Python: Find a substring in a string and returning the index of the substring

Not directly answering the question but I got a similar question recently where I was asked to count the number of times a sub-string is repeated in a given string. Here is the function I wrote:

def count_substring(string, sub_string):
    cnt = 0
    len_ss = len(sub_string)
    for i in range(len(string) - len_ss + 1):
        if string[i:i+len_ss] == sub_string:
            cnt += 1
    return cnt

The find() function probably returns the index of the fist occurrence only. Storing the index in place of just counting, can give us the distinct set of indices the sub-string gets repeated within the string.

Disclaimer: I am 'extremly' new to Python programming.

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

You may take a look at the following article for writing a custom DataAnnotationsModelMetadataProvider.

And here's another, more ASP.NET MVC 3ish way to proceed involving the newly introduced IMetadataAware interface.

Start by creating a custom attribute implementing this interface:

public class PlaceHolderAttribute : Attribute, IMetadataAware
{
    private readonly string _placeholder;
    public PlaceHolderAttribute(string placeholder)
    {
        _placeholder = placeholder;
    }

    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.AdditionalValues["placeholder"] = _placeholder;
    }
}

And then decorate your model with it:

public class MyViewModel
{
    [PlaceHolder("Enter title here")]
    public string Title { get; set; }
}

Next define a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }
}

A corresponding view:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Title)
    <input type="submit" value="OK" />
}

And finally the editor template (~/Views/Shared/EditorTemplates/string.cshtml):

@{
    var placeholder = string.Empty;
    if (ViewData.ModelMetadata.AdditionalValues.ContainsKey("placeholder"))
    {
        placeholder = ViewData.ModelMetadata.AdditionalValues["placeholder"] as string;
    }
}
<span>
    @Html.Label(ViewData.ModelMetadata.PropertyName)
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { placeholder = placeholder })
</span>

Regex allow digits and a single dot

Try the following expression

/^\d{0,2}(\.\d{1,2})?$/.test()

Multiple try codes in one block

You'll have to make this separate try blocks:

try:
    code a
except ExplicitException:
    pass

try:
    code b
except ExplicitException:
    try:
        code c
    except ExplicitException:
        try:
            code d
        except ExplicitException:
            pass

This assumes you want to run code c only if code b failed.

If you need to run code c regardless, you need to put the try blocks one after the other:

try:
    code a
except ExplicitException:
    pass

try:
    code b
except ExplicitException:
    pass

try:
    code c
except ExplicitException:
    pass

try:
    code d
except ExplicitException:
    pass

I'm using except ExplicitException here because it is never a good practice to blindly ignore all exceptions. You'll be ignoring MemoryError, KeyboardInterrupt and SystemExit as well otherwise, which you normally do not want to ignore or intercept without some kind of re-raise or conscious reason for handling those.

How to manage exceptions thrown in filters in Spring?

I wanted to provide a solution based on the answer of @kopelitsa. The main differences being:

  1. Reusing the controller exception handling by using the HandlerExceptionResolver.
  2. Using Java config over XML config

First, you need to make sure, that you have a class that handles exceptions occurring in a regular RestController/Controller (a class annotated with @RestControllerAdvice or @ControllerAdvice and method(s) annotated with @ExceptionHandler). This handles your exceptions occurring in a controller. Here is an example using the RestControllerAdvice:

@RestControllerAdvice
public class ExceptionTranslator {

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorDTO processRuntimeException(RuntimeException e) {
        return createErrorDTO(HttpStatus.INTERNAL_SERVER_ERROR, "An internal server error occurred.", e);
    }

    private ErrorDTO createErrorDTO(HttpStatus status, String message, Exception e) {
        (...)
    }
}

To reuse this behavior in the Spring Security filter chain, you need to define a Filter and hook it into your security configuration. The filter needs to redirect the exception to the above defined exception handling. Here is an example:

@Component
public class FilterChainExceptionHandler extends OncePerRequestFilter {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        try {
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            log.error("Spring Security Filter Chain Exception:", e);
            resolver.resolveException(request, response, null, e);
        }
    }
}

The created filter then needs to be added to the SecurityConfiguration. You need to hook it into the chain very early, because all preceding filter's exceptions won't be caught. In my case, it was reasonable to add it before the LogoutFilter. See the default filter chain and its order in the official docs. Here is an example:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private FilterChainExceptionHandler filterChainExceptionHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(filterChainExceptionHandler, LogoutFilter.class)
            (...)
    }

}

Forking / Multi-Threaded Processes | Bash

I don't like using wait because it gets blocked until the process exits, which is not ideal when there are multiple process to wait on as I can't get a status update until the current process is done. I prefer to use a combination of kill -0 and sleep to this.

Given an array of pids to wait on, I use the below waitPids() function to get a continuous feedback on what pids are still pending to finish.

declare -a pids
waitPids() {
    while [ ${#pids[@]} -ne 0 ]; do
        echo "Waiting for pids: ${pids[@]}"
        local range=$(eval echo {0..$((${#pids[@]}-1))})
        local i
        for i in $range; do
            if ! kill -0 ${pids[$i]} 2> /dev/null; then
                echo "Done -- ${pids[$i]}"
                unset pids[$i]
            fi
        done
        pids=("${pids[@]}") # Expunge nulls created by unset.
        sleep 1
    done
    echo "Done!"
}

When I start a process in the background, I add its pid immediately to the pids array by using this below utility function:

addPid() {
    local desc=$1
    local pid=$2
    echo "$desc -- $pid"
    pids=(${pids[@]} $pid)
}

Here is a sample that shows how to use:

for i in {2..5}; do
    sleep $i &
    addPid "Sleep for $i" $!
done
waitPids

And here is how the feedback looks:

Sleep for 2 -- 36271
Sleep for 3 -- 36272
Sleep for 4 -- 36273
Sleep for 5 -- 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Waiting for pids: 36271 36272 36273 36274
Done -- 36271
Waiting for pids: 36272 36273 36274
Done -- 36272
Waiting for pids: 36273 36274
Done -- 36273
Waiting for pids: 36274
Done -- 36274
Done!

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I have that problem and my solution is going source folder and run command line: mvn clean install -DskipTests eclipse:eclipse then return eclipse workspace and refresh project. Hope that help!

Difference between javacore, thread dump and heap dump in Websphere

Thread dumps are javacore show snapshot of threads running in JVM, it is useful to debug hang issues, it will provide info about java level dead locks and also IBm version of javacores provides much more useful information, such as heap usage, CPU usage of each thread and overall heap usage along with number of classes laded by the JVM.

Heapdumps, provides information about Java heap usage by an JVM, which can be used to debug memory leaks. Heapdumps are generated by IBM JVMs when a JVM is runs into outofmemoryerror, Heapdumps are only for heap leaks in java, native out of memory error may result system dumps usually with an "GPF" General protection Fault.

Cannot bulk load because the file could not be opened. Operating System Error Code 3

Using SQL connection via Windows Authentication: A "Kerberos double hop" is happening: one hop is your client application connecting to the SQL Server, a second hop is the SQL Server connecting to the remote "\\NETWORK_MACHINE\". Such a double hop falls under the restrictions of Constrained Delegation and you end up accessing the share as Anonymous Login and hence the Access Denied.

To resolve the issue you need to enable constrained delegation for the SQL Server service account. See here for a good post that explains it quite well

SQL Server using SQL Authentication You need to create a credential for your SQL login and use that to access that particular network resource. See here

Send Email Intent

Maybe you should try this: intent.setType("plain/text");

I found it here. I've used it in my app and it shows only E-Mail and Gmail options.

Repeat table headers in print mode

Some browsers repeat the thead element on each page, as they are supposed to. Others need some help: Add this to your CSS:

thead {display: table-header-group;}
tfoot {display: table-header-group;}

Opera 7.5 and IE 5 won't repeat headers no matter what you try.

(source)

RuntimeError: module compiled against API version a but this version of numpy is 9

You are likely running the Mac default (/usr/bin/python) which has an older version of numpy installed in the system folders. The easiest way to get python working with opencv is to use brew to install both python and opencv into /usr/local and run the /usr/local/bin/python.

brew install python
brew tap homebrew/science
brew install opencv

In DB2 Display a table's definition

In addition to DESCRIBE TABLE, you can use the command below

DESCRIBE INDEXES FOR TABLE *tablename* SHOW DETAIL 

to get information about the table's indexes.

The most comprehensive detail about a table on Db2 for Linux, UNIX, and Windows can be obtained from the db2look utility, which you can run from a remote client or directly on the Db2 server as a local user. The tool produces the DDL and other information necessary to mimic tables and their statistical data. The docs for db2look in Db2 11.5 are here.

The following db2look command will connect to the SALESDB database and obtain the DDL statements necessary to recreate the ORDERS table

db2look -d SALESDB -e -t ORDERS

Printing image with PrintDocument. how to adjust the image to fit paper size

Agree with TonyM and BBoy - this is the correct answer for original 4*6 printing of label. (args.PageBounds). This worked for me for printing Endicia API service shipping Labels.

private void SubmitResponseToPrinter(ILabelRequestResponse response)
    {
        PrintDocument pd = new PrintDocument();
        pd.PrintPage += (sender, args) =>
        {
            Image i = Image.FromFile(response.Labels[0].FullPathFileName.Trim());
            args.Graphics.DrawImage(i, args.PageBounds);
        };
        pd.Print();
    }

Circular (or cyclic) imports in Python

There are a lot of great answers here. While there are usually quick solutions to the problem, some of which feel more pythonic than others, if you have the luxury of doing some refactoring, another approach is to analyze the organization of your code, and try to remove the circular dependency. You may find, for example, that you have:

File a.py

from b import B

class A:
    @staticmethod
    def save_result(result):
        print('save the result')

    @staticmethod
    def do_something_a_ish(param):
        A.save_result(A.use_param_like_a_would(param))

    @staticmethod
    def do_something_related_to_b(param):
        B.do_something_b_ish(param)

File b.py

from a import A

class B:
    @staticmethod
    def do_something_b_ish(param):
        A.save_result(B.use_param_like_b_would(param))

In this case, just moving one static method to a separate file, say c.py:

File c.py

def save_result(result):
    print('save the result')

will allow removing the save_result method from A, and thus allow removing the import of A from a in b:

Refactored File a.py

from b import B
from c import save_result

class A:
    @staticmethod
    def do_something_a_ish(param):
        A.save_result(A.use_param_like_a_would(param))

    @staticmethod
    def do_something_related_to_b(param):
        B.do_something_b_ish(param)

Refactored File b.py

from c import save_result

class B:
    @staticmethod
    def do_something_b_ish(param):
        save_result(B.use_param_like_b_would(param))

In summary, if you have a tool (e.g. pylint or PyCharm) that reports on methods that can be static, just throwing a staticmethod decorator on them might not be the best way to silence the warning. Even though the method seems related to the class, it might be better to separate it out, especially if you have several closely related modules that might need the same functionality and you intend to practice DRY principles.

Bootstrap - dropdown menu not working?

you are missing the "btn btn-navbar" section. For example:

        <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </a>

Take a look to navbar documentation in:

Twitter Bootstrap

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

Getting the names of all files in a directory with PHP

glob() and FilesystemIterator examples:

/* 
 * glob() examples
 */

// get the array of full paths
$result = glob( 'path/*' );

// get the array of file names
$result = array_map( function( $item ) {
    return basename( $item );
}, glob( 'path/*' ) );


/* 
 * FilesystemIterator examples
 */

// get the array of file names by using FilesystemIterator and array_map()
$result = array_map( function( $item ) {
    // $item: SplFileInfo object
    return $item->getFilename();
}, iterator_to_array( new FilesystemIterator( 'path' ), false ) );

// get the array of file names by using FilesystemIterator and iterator_apply() filter
$it = new FilesystemIterator( 'path' );
iterator_apply( 
    $it, 
    function( $item, &$result ) {
        // $item: FilesystemIterator object that points to current element
        $result[] = (string) $item;
        // The function must return TRUE in order to continue iterating
        return true;
    }, 
    array( $it, &$result )
);

Get HTML code from website in C#

Better you can use the Webclient class to simplify your task:

using System.Net;

using (WebClient client = new WebClient())
{
    string htmlCode = client.DownloadString("http://somesite.com/default.html");
}

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

How to keep two folders automatically synchronized?

You can take advantage of fschange. It’s a Linux filesystem change notification. The source code is downloadable from the above link, you can compile it yourself. fschange can be used to keep track of file changes by reading data from a proc file (/proc/fschange). When data is written to a file, fschange reports the exact interval that has been modified instead of just saying that the file has been changed. If you are looking for the more advanced solution, I would suggest checking Resilio Connect. It is cross-platform, provides extended options for use and monitoring. Since it’s BitTorrent-based, it is faster than any other existing sync tool. It was written on their behalf.

How to change progress bar's progress color in Android

Simply use:

DrawableCompat.setTint(progressBar.getIndeterminateDrawable(),yourColor)

How to split a string in Java

Assuming, that

  • you don't really need regular expressions for your split
  • you happen to already use apache commons lang in your app

The easiest way is to use StringUtils#split(java.lang.String, char). That's more convenient than the one provided by Java out of the box if you don't need regular expressions. Like its manual says, it works like this:

A null input String returns null.

 StringUtils.split(null, *)         = null
 StringUtils.split("", *)           = []
 StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
 StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
 StringUtils.split("a:b:c", '.')    = ["a:b:c"]
 StringUtils.split("a b c", ' ')    = ["a", "b", "c"]

I would recommend using commong-lang, since usually it contains a lot of stuff that's usable. However, if you don't need it for anything else than doing a split, then implementing yourself or escaping the regex is a better option.

Check if all values in list are greater than a certain number

There is a builtin function all:

all (x > limit for x in my_list)

Being limit the value greater than which all numbers must be.

How do you add a scroll bar to a div?

<head>
<style>
div.scroll
{
background-color:#00FFFF;
width:40%;
height:200PX;
FLOAT: left;
margin-left: 5%;
padding: 1%;
overflow:scroll;
}


</style>
</head>

<body>



<div class="scroll">You can use the overflow property when you want to have better       control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better </div>


</body>
</html>

Creating a Facebook share button with customized url, title and image

This is the code as 2017:

<i class="fa fa-facebook-square"></i>
<a href="#" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location.href),'facebook-share-dialog','width=626,height=436');return false;">Share on Facebook</a>

Facebook now takes all data from OG metatags.

NOTE: This code assumes you have OG metatags on in site's code.

Source

Java: splitting the filename into a base and extension

I know others have mentioned String.split, but here is a variant that only yields two tokens (the base and the extension):

String[] tokens = fileName.split("\\.(?=[^\\.]+$)");

For example:

"test.cool.awesome.txt".split("\\.(?=[^\\.]+$)");

Yields:

["test.cool.awesome", "txt"]

The regular expression tells Java to split on any period that is followed by any number of non-periods, followed by the end of input. There is only one period that matches this definition (namely, the last period).

Technically Regexically speaking, this technique is called zero-width positive lookahead.


BTW, if you want to split a path and get the full filename including but not limited to the dot extension, using a path with forward slashes,

    String[] tokens = dir.split(".+?/(?=[^/]+$)");

For example:

    String dir = "/foo/bar/bam/boozled"; 
    String[] tokens = dir.split(".+?/(?=[^/]+$)");
    // [ "/foo/bar/bam/" "boozled" ] 

How to get the root dir of the Symfony2 application?

You can also use regular expression in addition to this:

    $directoryPath = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/yourbundle/';
    $directoryPath = preg_replace("/app..../i", "", $directoryPath);
    echo $directoryPath;

Return from lambda forEach() in java

This what helped me:

List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);

Taken from Java 8 Finding Specific Element in List with Lambda

Creating multiline strings in JavaScript

Exact

Ruby produce: "This\nIs\nA\nMultiline\nString\n" - below JS produce exact same string

_x000D_
_x000D_
text = `This
Is
A
Multiline
String
`

// TEST
console.log(JSON.stringify(text));
console.log(text);
_x000D_
_x000D_
_x000D_

This is improvement to Lonnie Best answer because new-line characters in his answer are not exactly the same positions as in ruby output

Inserting a string into a list without getting split into characters

To add to the end of the list:

list.append('foo')

To insert at the beginning:

list.insert(0, 'foo')

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

There is no way to retrieve localStorage, sessionStorage or cookie values via javascript in the browser after they've been deleted via javascript.

If what you're really asking is if there is some other way (from outside the browser) to recover that data, that's a different question and the answer will entirely depend upon the specific browser and how it implements the storage of each of those types of data.

For example, Firefox stores cookies as individual files. When a cookie is deleted, its file is deleted. That means that the cookie can no longer be accessed via the browser. But, we know that from outside the browser, using system tools, the contents of deleted files can sometimes be retrieved.

If you wanted to look into this further, you'd have to discover how each browser stores each data type on each platform of interest and then explore if that type of storage has any recovery strategy.

FIFO based Queue implementations?

A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.add(1);
    queue.add(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

1
2

Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.

So this is a Queue only if used in conjunction with add.

Try this :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.push(1);
    queue.push(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

2
1

Select from table by knowing only date without time (ORACLE)

Try the following way.

Select * from t1 where date(col_name)="8/3/2010" 

Error parsing yaml file: mapping values are not allowed here

Change

application:climate-change

to

application: climate-change

The space after the colon is mandatory in yaml if you want a key-value pair. (See http://www.yaml.org/spec/1.2/spec.html#id2759963)

What is the preferred syntax for defining enums in JavaScript?

class Enum {
  constructor (...vals) {
    vals.forEach( val => {
      const CONSTANT = Symbol(val);
      Object.defineProperty(this, val.toUpperCase(), {
        get () {
          return CONSTANT;
        },
        set (val) {
          const enum_val = "CONSTANT";
          // generate TypeError associated with attempting to change the value of a constant
          enum_val = val;
        }
      });
    });
  }
}

Example of usage:

const COLORS = new Enum("red", "blue", "green");

Get last field using awk substr

I know I'm like 3 years late on this but.... you should consider parameter expansion, it's built-in and faster.

if your input is in a var, let's say, $var1, just do ${var1##*/}. Look below

$ var1='/home/parent/child1/filename'
$ echo ${var1##*/}
filename
$ var1='/home/parent/child1/child2/filename'
$ echo ${var1##*/}
filename
$ var1='/home/parent/child1/child2/child3/filename'
$ echo ${var1##*/}
filename

How to substring in jquery

That's just plain JavaScript: see substring and substr.

Why does configure say no C compiler found when GCC is installed?

Try specifying CC while configuring:

CC=/usr/bin/gcc ./configure --prefix=/usr/local/sphinx

Also check if your compiler produces executables. The following should produce an a.out:

echo "int main(){0;}" | gcc -x c -

How store a range from excel into a Range variable?

What is currentWorksheet? It works if you use the built-in ActiveSheet.

dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

How to select date without time in SQL

For 2008 older version :

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

The issue I was facing was I have a project that is dependent on a library project. In order to build I was following these steps:

msbuild.exe myproject.vbproj /T:Rebuild
msbuild.exe myproject.vbproj /T:Package

That of course meant I was missing my library's dll files in bin and most importantly in the package zip file. I found this works perfectly:

msbuild.exe myproject.vbproj /T:Rebuild;Package

I have no idea why this work or why it didn't in the first place. But hope that helps.

How to connect a Windows Mobile PDA to Windows 10

I haven't managed to get WMDC working on Windows 10 (it hanged on splash screen upon start), so I've finally uninstalled it. But now I have a Portable Devices / Compact device in the Device Manager and I can browse my Windows Compact 7 device within Windows Explorer. All my apps using RAPI also work. Maybe this is the result of installing/uninstalling WMDC, or probably this functionality was already presented on Windows 10 and I've just overlooked it initially.

How to normalize an array in NumPy to a unit vector?

If you don't need utmost precision, your function can be reduced to:

v_norm = v / (np.linalg.norm(v) + 1e-16)

How to get filename without extension from file path in Ruby

You can get directory path to current script with:

File.dirname __FILE__

How can git be installed on CENTOS 5.5?

Just updating this for 2017 and later, as CentOS 5 has reached EOL and the URL for EPEL has changed:

sudo rpm -Uvh http://archives.fedoraproject.org/pub/archive/epel/5/x86_64/epel-release-5-4.noarch.rpm
sudo yum install git

This gets you git 1.8.2.3

"Non-static method cannot be referenced from a static context" error

Instance methods need to be called from an instance. Your setLoanItem method is an instance method (it doesn't have the modifier static), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this)).

You need to create an instance of the class before you can call the method on it:

Media media = new Media();
media.setLoanItem("Yes");

(Btw it would be better to use a boolean instead of a string containing "Yes".)

How do you implement a good profanity filter?

The only way to prevent offensive user input is to prevent all user input.

If you insist on allowing user input and need moderation, then incorporate human moderators.

How to get a product's image in Magento?

If you have the product collection object like:

$collection = Mage::getModel('catalog/product')->getCollection(); 

Now you can get product sku using $_product->getSku() if you can't get image path with

echo $this->helper('catalog/image')->init($_product,'small_image')->resize(135);

Or

$_product->getImageUrl();

Then you can add a little code

$productModel = Mage::getModel('catalog/product');
$_prod = $productModel->loadByAttribute('sku', $_product->getSku()); 
$_prod->getImageUrl();

How to convert HTML to PDF using iTextSharp

First, HTML and PDF are not related although they were created around the same time. HTML is intended to convey higher level information such as paragraphs and tables. Although there are methods to control it, it is ultimately up to the browser to draw these higher level concepts. PDF is intended to convey documents and the documents must "look" the same wherever they are rendered.

In an HTML document you might have a paragraph that's 100% wide and depending on the width of your monitor it might take 2 lines or 10 lines and when you print it it might be 7 lines and when you look at it on your phone it might take 20 lines. A PDF file, however, must be independent of the rendering device, so regardless of your screen size it must always render exactly the same.

Because of the musts above, PDF doesn't support abstract things like "tables" or "paragraphs". There are three basic things that PDF supports: text, lines/shapes and images. (There are other things like annotations and movies but I'm trying to keep it simple here.) In a PDF you don't say "here's a paragraph, browser do your thing!". Instead you say, "draw this text at this exact X,Y location using this exact font and don't worry, I've previously calculated the width of the text so I know it will all fit on this line". You also don't say "here's a table" but instead you say "draw this text at this exact location and then draw a rectangle at this other exact location that I've previously calculated so I know it will appear to be around the text".

Second, iText and iTextSharp parse HTML and CSS. That's it. ASP.Net, MVC, Razor, Struts, Spring, etc, are all HTML frameworks but iText/iTextSharp is 100% unaware of them. Same with DataGridViews, Repeaters, Templates, Views, etc. which are all framework-specific abstractions. It is your responsibility to get the HTML from your choice of framework, iText won't help you. If you get an exception saying The document has no pages or you think that "iText isn't parsing my HTML" it is almost definite that you don't actually have HTML, you only think you do.

Third, the built-in class that's been around for years is the HTMLWorker however this has been replaced with XMLWorker (Java / .Net). Zero work is being done on HTMLWorker which doesn't support CSS files and has only limited support for the most basic CSS properties and actually breaks on certain tags. If you do not see the HTML attribute or CSS property and value in this file then it probably isn't supported by HTMLWorker. XMLWorker can be more complicated sometimes but those complications also make it more extensible.

Below is C# code that shows how to parse HTML tags into iText abstractions that get automatically added to the document that you are working on. C# and Java are very similar so it should be relatively easy to convert this. Example #1 uses the built-in HTMLWorker to parse the HTML string. Since only inline styles are supported the class="headline" gets ignored but everything else should actually work. Example #2 is the same as the first except it uses XMLWorker instead. Example #3 also parses the simple CSS example.

//Create a byte array that will eventually hold our final PDF
Byte[] bytes;

//Boilerplate iTextSharp setup here
//Create a stream that we can write to, in this case a MemoryStream
using (var ms = new MemoryStream()) {

    //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
    using (var doc = new Document()) {

        //Create a writer that's bound to our PDF abstraction and our stream
        using (var writer = PdfWriter.GetInstance(doc, ms)) {

            //Open the document for writing
            doc.Open();

            //Our sample HTML and CSS
            var example_html = @"<p>This <em>is </em><span class=""headline"" style=""text-decoration: underline;"">some</span> <strong>sample <em> text</em></strong><span style=""color: red;"">!!!</span></p>";
            var example_css = @".headline{font-size:200%}";

            /**************************************************
             * Example #1                                     *
             *                                                *
             * Use the built-in HTMLWorker to parse the HTML. *
             * Only inline CSS is supported.                  *
             * ************************************************/

            //Create a new HTMLWorker bound to our document
            using (var htmlWorker = new iTextSharp.text.html.simpleparser.HTMLWorker(doc)) {

                //HTMLWorker doesn't read a string directly but instead needs a TextReader (which StringReader subclasses)
                using (var sr = new StringReader(example_html)) {

                    //Parse the HTML
                    htmlWorker.Parse(sr);
                }
            }

            /**************************************************
             * Example #2                                     *
             *                                                *
             * Use the XMLWorker to parse the HTML.           *
             * Only inline CSS and absolutely linked          *
             * CSS is supported                               *
             * ************************************************/

            //XMLWorker also reads from a TextReader and not directly from a string
            using (var srHtml = new StringReader(example_html)) {

                //Parse the HTML
                iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
            }

            /**************************************************
             * Example #3                                     *
             *                                                *
             * Use the XMLWorker to parse HTML and CSS        *
             * ************************************************/

            //In order to read CSS as a string we need to switch to a different constructor
            //that takes Streams instead of TextReaders.
            //Below we convert the strings into UTF8 byte array and wrap those in MemoryStreams
            using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css))) {
                using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_html))) {

                    //Parse the HTML
                    iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
                }
            }


            doc.Close();
        }
    }

    //After all of the PDF "stuff" above is done and closed but **before** we
    //close the MemoryStream, grab all of the active bytes from the stream
    bytes = ms.ToArray();
}

//Now we just need to do something with those bytes.
//Here I'm writing them to disk but if you were in ASP.Net you might Response.BinaryWrite() them.
//You could also write the bytes to a database in a varbinary() column (but please don't) or you
//could pass them to another function for further PDF processing.
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
System.IO.File.WriteAllBytes(testFile, bytes);

2017's update

There are good news for HTML-to-PDF demands. As this answer showed, the W3C standard css-break-3 will solve the problem... It is a Candidate Recommendation with plan to turn into definitive Recommendation this year, after tests.

As not-so-standard there are solutions, with plugins for C#, as showed by print-css.rocks.

How to fix Error: listen EADDRINUSE while using nodejs?

The aforementioned killall -9 node, suggested by Patrick works as expected and solves the problem but you may want to read the edit part of this very answer about why kill -9 may not be the best way to do it.

On top of that you might want to target a single process rather than blindly killing all active processes.

In that case, first get the process ID (PID) of the process running on that port (say 8888):

lsof -i tcp:8888

This will return something like:

COMMAND   PID    USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
node     57385   You   11u  IPv6 0xac745b2749fd2be3      0t0  TCP *:ddi-tcp-1 (LISTEN)

Then just do (ps - actually do not. Please keep reading below):

kill -9 57385

You can read a bit more about this here.

EDIT: I was reading on a fairly related topic today and stumbled upon this interesting thread on why should i not kill -9 a process.

Generally, you should use kill -15 before kill -9 to give the target process a chance to clean up after itself. (Processes can't catch or ignore SIGKILL, but they can and often do catch SIGTERM.) If you don't give the process a chance to finish what it's doing and clean up, it may leave corrupted files (or other state) around that it won't be able to understand once restarted.

So, as stated you should better kill the above process with:

kill -15 57385

EDIT 2: As noted in a comment around here many times this error is a consequence of not exiting a process gracefully. That means, a lot of people exit a node command (or any other) using CTRL+Z. The correct way of stopping a running process is issuing the CTRL+C command which performs a clean exit.

Exiting a process the right way will free up that port while shutting down. This will allow you to restart the process without going through the trouble of killing it yourself before being able to re-run it again.

swift UITableView set rowHeight

For setting row height there is separate method:

For Swift 3

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 100.0;//Choose your custom row height
}

Older Swift uses

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 100.0;//Choose your custom row height
}

Otherwise you can set row height using:

self.tableView.rowHeight = 44.0

In ViewDidLoad.

Spring Boot - Handle to Hibernate SessionFactory

You can accomplish this with:

SessionFactory sessionFactory = 
    entityManagerFactory.unwrap(SessionFactory.class);

where entityManagerFactory is an JPA EntityManagerFactory.

package net.andreaskluth.hibernatesample;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SomeService {

  private SessionFactory hibernateFactory;

  @Autowired
  public SomeService(EntityManagerFactory factory) {
    if(factory.unwrap(SessionFactory.class) == null){
      throw new NullPointerException("factory is not a hibernate factory");
    }
    this.hibernateFactory = factory.unwrap(SessionFactory.class);
  }

}

How to use IntelliJ IDEA to find all unused code?

Just use Analyze | Inspect Code with appropriate inspection enabled (Unused declaration under Declaration redundancy group).

Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

This is in contrast to the previous answers, I had exactly the same error: "A collection with cascade=”all-delete-orphan” was no longer referenced...." when my setter function looked like this:

public void setTaxCalculationRules(Set<TaxCalculationRule> taxCalculationRules_) {
    if( this.taxCalculationRules == null ) {
        this.taxCalculationRules = taxCalculationRules_;
    } else {
        this.taxCalculationRules.retainAll(taxCalculationRules_);
        this.taxCalculationRules.addAll(taxCalculationRules_);
    }
}

And then it disappeared when I changed it to the simple version:

public void setTaxCalculationRules(Set<TaxCalculationRule> taxCalculationRules_) {
    this.taxCalculationRules = taxCalculationRules_;
}

(hibernate versions - tried both 5.4.10 and 4.3.11. Spent several days trying all sorts of solutions before coming back to the simple assignment in the setter. Confused now as to why this so.)

RSA encryption and decryption in Python

# coding: utf-8
from __future__ import unicode_literals
import base64
import os

import six
from Crypto import Random
from Crypto.PublicKey import RSA


class PublicKeyFileExists(Exception): pass


class RSAEncryption(object):
    PRIVATE_KEY_FILE_PATH = None
    PUBLIC_KEY_FILE_PATH = None

    def encrypt(self, message):
        public_key = self._get_public_key()
        public_key_object = RSA.importKey(public_key)
        random_phrase = 'M'
        encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
        # use base64 for save encrypted_message in database without problems with encoding
        return base64.b64encode(encrypted_message)

    def decrypt(self, encoded_encrypted_message):
        encrypted_message = base64.b64decode(encoded_encrypted_message)
        private_key = self._get_private_key()
        private_key_object = RSA.importKey(private_key)
        decrypted_message = private_key_object.decrypt(encrypted_message)
        return six.text_type(decrypted_message, encoding='utf8')

    def generate_keys(self):
        """Be careful rewrite your keys"""
        random_generator = Random.new().read
        key = RSA.generate(1024, random_generator)
        private, public = key.exportKey(), key.publickey().exportKey()

        if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
            raise PublicKeyFileExists('???? ? ????????? ?????? ??????????. ??????? ????')
        self.create_directories()

        with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
            private_file.write(private)
        with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
            public_file.write(public)
        return private, public

    def create_directories(self, for_private_key=True):
        public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
        if not os.path.exists(public_key_path):
            os.makedirs(public_key_path)
        if for_private_key:
            private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
            if not os.path.exists(private_key_path):
                os.makedirs(private_key_path)

    def _get_public_key(self):
        """run generate_keys() before get keys """
        with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _get_private_key(self):
        """run generate_keys() before get keys """
        with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _to_format_for_encrypt(value):
        if isinstance(value, int):
            return six.binary_type(value)
        for str_type in six.string_types:
            if isinstance(value, str_type):
                return value.encode('utf8')
        if isinstance(value, six.binary_type):
            return value

And use

KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS

class TestingEncryption(RSAEncryption):
    PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
    PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'


# django/flask
from django.core.files import File

class ProductionEncryption(RSAEncryption):
    PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'

    def _get_private_key(self):
        """run generate_keys() before get keys """
        from corportal.utils import global_elements
        private_key = global_elements.request.FILES.get('private_key')
        if private_key:
            private_key_file = File(private_key)
            return private_key_file.read()

message = 'Hello ??? friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)

How to group by month from Date field using sql

SQL Server 2012 version above,

SELECT  format(Closing_Date,'yyyy-MM') as ClosingMonth,
        Category,  
        COUNT(Status) TotalCount 
FROM    MyTable
WHERE   Closing_Date >= '2012-02-01' 
AND     Closing_Date <= '2012-12-31'
AND     Defect_Status1 IS NOT NULL
GROUP BY format(Closing_Date,'yyyy-MM'), Category;

How to sort an associative array by its values in Javascript?

@commonpike's answer is "the right one", but as he goes on to comment...

most browsers nowadays just support Object.keys()

Yeah.. Object.keys() is WAY better.

But what's even better? Duh, it's it in coffeescript!

sortedKeys = (x) -> Object.keys(x).sort (a,b) -> x[a] - x[b]

sortedKeys
  'a' :  1
  'b' :  3
  'c' :  4
  'd' : -1

[ 'd', 'a', 'b', 'c' ]