Programs & Examples On #Synapse

Apache Synapse is a lightweight and high-performance Enterprise Service Bus

"The semaphore timeout period has expired" error for USB connection

Okay, I am now connecting without the semaphore timeout problem.

If anyone reading ever encounters the same thing, I hope that this procedure works for you; but no promises; hey, it's windows.

In my case this was Windows 7

I got a little hint from This page on eHow; not sure if that might help anyone or not.

So anyway, this was the simple twenty three step procedure that worked for me

  • Click on start button

  • Choose Control Panel

  • From Control Panel, choose Device Manger

  • From Device Manager, choose Universal Serial Bus Controllers

  • From Universal Serial Bus Controllers, click the little sideways triangle

  • I cannot predict what you'll see on your computer, but on mine I get a long drop-down list

  • Begin the investigation to figure out which one of these members of this list is the culprit...

    • On each member of the drop-down list, right-click on the name

    • A list will open, choose Properties

    • Guesswork time: using the various tabs near the top of the resulting window which opens, make a guess if this is the USB adapter driver which is choking your stuff with semaphore timeouts

  • Once you have made the proper guess, then close the USB Root Hub Properties window (but leave the Device Manager window open).

  • Physically disonnect anything and everything from that USB hub.

  • Unplug it.

  • Return your mouse pointer to that USB Root Hub in the list which you identified earlier.

  • Right click again

  • Choose Uninstall

  • Let Windows do its thing

  • Wait a little while

  • Power Down the whole computer if you have the time; some say this is required. I think I got away without it.

  • Plug the USB hub back into a USB connector on the PC

  • If the list in the device manager blinks and does a few flash-bulbs, it's okay.

  • Plug the BlueTooth connector back into the USB hub

  • Let windows do its thing some more

  • Within two minutes, I had a working COM port again, no semaphore timeouts.

Hope it works for anyone else who may be having a similar problem.

What do 3 dots next to a parameter type mean in Java?

Also to shed some light, it is important to know that var-arg parameters are limited to one and you can't have several var-art params. For example this is illigal:

public void myMethod(String... strings, int ... ints){
// method body
}

Flexbox: center horizontally and vertically

diplay: flex; for it's container and margin:auto; for it's item works perfect.

NOTE: You have to setup the width and height to see the effect.

_x000D_
_x000D_
#container{_x000D_
  width: 100%; /*width needs to be setup*/_x000D_
  height: 150px; /*height needs to be setup*/_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.item{_x000D_
  margin: auto; /*These will make the item in center*/_x000D_
  background-color: #CCC;_x000D_
}
_x000D_
<div id="container">_x000D_
   <div class="item">CENTER</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to sort an array based on the length of each element?

I adapted @shareef's answer to make it concise. I use,

.sort(function(arg1, arg2) { return arg1.length - arg2.length })

Which JDK version (Language Level) is required for Android Studio?

Normally, I would go with what the documentation says but if the instructor explicitly said to stick with JDK 6, I'd use JDK 6 because you would want your development environment to be as close as possible to the instructors. It would suck if you ran into an issue and having the thought in the back of your head that maybe it's because you're on JDK 7 that you're having the issue. Btw, I haven't touched Android recently but I personally never ran into issues when I was on JDK 7 but mind you, I only code Android apps casually.

How can I quickly sum all numbers in a file?

Here's another one-liner

( echo 0 ; sed 's/$/ +/' foo ; echo p ) | dc

This assumes the numbers are integers. If you need decimals, try

( echo 0 2k ; sed 's/$/ +/' foo ; echo p ) | dc

Adjust 2 to the number of decimals needed.

How to output HTML from JSP <%! ... %> block?

<%!
private void myFunc(String Bits, javax.servlet.jsp.JspWriter myOut)
{  
  try{ myOut.println("<div>"+Bits+"</div>"); } 
  catch(Exception eek) { }
}
%>
...
<%
  myFunc("more difficult than it should be",out);
%>

Try this, it worked for me!

In JPA 2, using a CriteriaQuery, how to count results

It is a bit tricky, depending on the JPA 2 implementation you use, this one works for EclipseLink 2.4.1, but doesn't for Hibernate, here a generic CriteriaQuery count for EclipseLink:

public static Long count(final EntityManager em, final CriteriaQuery<?> criteria)
  {
    final CriteriaBuilder builder=em.getCriteriaBuilder();
    final CriteriaQuery<Long> countCriteria=builder.createQuery(Long.class);
    countCriteria.select(builder.count(criteria.getRoots().iterator().next()));
    final Predicate
            groupRestriction=criteria.getGroupRestriction(),
            fromRestriction=criteria.getRestriction();
    if(groupRestriction != null){
      countCriteria.having(groupRestriction);
    }
    if(fromRestriction != null){
      countCriteria.where(fromRestriction);
    }
    countCriteria.groupBy(criteria.getGroupList());
    countCriteria.distinct(criteria.isDistinct());
    return em.createQuery(countCriteria).getSingleResult();
  }

The other day I migrated from EclipseLink to Hibernate and had to change my count function to the following, so feel free to use either as this is a hard problem to solve, it might not work for your case, it has been in use since Hibernate 4.x, notice that I don't try to guess which is the root, instead I pass it from the query so problem solved, too many ambiguous corner cases to try to guess:

  public static <T> long count(EntityManager em,Root<T> root,CriteriaQuery<T> criteria)
  {
    final CriteriaBuilder builder=em.getCriteriaBuilder();
    final CriteriaQuery<Long> countCriteria=builder.createQuery(Long.class);

    countCriteria.select(builder.count(root));

    for(Root<?> fromRoot : criteria.getRoots()){
      countCriteria.getRoots().add(fromRoot);
    }

    final Predicate whereRestriction=criteria.getRestriction();
    if(whereRestriction!=null){
      countCriteria.where(whereRestriction);
    }

    final Predicate groupRestriction=criteria.getGroupRestriction();
    if(groupRestriction!=null){
      countCriteria.having(groupRestriction);
    }

    countCriteria.groupBy(criteria.getGroupList());
    countCriteria.distinct(criteria.isDistinct());
    return em.createQuery(countCriteria).getSingleResult();
  }

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

I noticed that in the csproj the framework entity had hintpath like

<HintPath>..\..\..\..\..\..\Users\{myusername}

I had this in the nuget.config file:

 <config>
 <add key="repositoryPath" value="../lib" />
 </config>

a) I removed the above lines, b) uninstalled the framework entity package, c) THEN CLOSED THE solution and reopened it, d) reinstalled the framework.

It fixed my issue.

Date constructor returns NaN in IE, but works in Firefox and Chrome

You can use the following code to parse ISO8601 date string:

function parseISO8601(d) {
    var timestamp = d;
    if (typeof (d) !== 'number') {
        timestamp = Date.parse(d);
    }
    return new Date(timestamp);
};

Bootstrap 3 only for mobile

If you're looking to make the elements be 33.3% only on small devices and lower:

This is backwards from what Bootstrap is designed for, but you can do this:

<div class="row">
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
</div>

This will make each element 33.3% wide on small and extra small devices but 100% wide on medium and larger devices.

JSFiddle: http://jsfiddle.net/jdwire/sggt8/embedded/result/

If you're only looking to hide elements for smaller devices:

I think you're looking for the visible-xs and/or visible-sm classes. These will let you make certain elements only visible to small screen devices.

For example, if you want a element to only be visible to small and extra-small devices, do this:

<div class="visible-xs visible-sm">You're using a fairly small device.</div>

To show it only for larger screens, use this:

<div class="hidden-xs hidden-sm">You're probably not using a phone.</div>

See http://getbootstrap.com/css/#responsive-utilities-classes for more information.

Remove specific characters from a string in Javascript

if it is not the first two chars and you wanna remove F0 from the whole string then you gotta use this regex

_x000D_
_x000D_
   let string = 'F0123F0456F0';_x000D_
   let result = string.replace(/F0/ig, '');_x000D_
   console.log(result);
_x000D_
_x000D_
_x000D_

numpy max vs amax vs maximum

For completeness, in Numpy there are four maximum related functions. They fall into two different categories:

  • np.amax/np.max, np.nanmax: for single array order statistics
  • and np.maximum, np.fmax: for element-wise comparison of two arrays

I. For single array order statistics

NaNs propagator np.amax/np.max and its NaN ignorant counterpart np.nanmax.

  • np.max is just an alias of np.amax, so they are considered as one function.

    >>> np.max.__name__
    'amax'
    >>> np.max is np.amax
    True
    
  • np.max propagates NaNs while np.nanmax ignores NaNs.

    >>> np.max([np.nan, 3.14, -1])
    nan
    >>> np.nanmax([np.nan, 3.14, -1])
    3.14
    

II. For element-wise comparison of two arrays

NaNs propagator np.maximum and its NaNs ignorant counterpart np.fmax.

  • Both functions require two arrays as the first two positional args to compare with.

    # x1 and x2 must be the same shape or can be broadcast
    np.maximum(x1, x2, /, ...);
    np.fmax(x1, x2, /, ...)
    
  • np.maximum propagates NaNs while np.fmax ignores NaNs.

    >>> np.maximum([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([ nan,  nan, 2.72])
    >>> np.fmax([np.nan, 3.14, 0], [np.NINF, np.nan, 2.72])
    array([-inf, 3.14, 2.72])
    
  • The element-wise functions are np.ufunc(Universal Function), which means they have some special properties that normal Numpy function don't have.

    >>> type(np.maximum)
    <class 'numpy.ufunc'>
    >>> type(np.fmax)
    <class 'numpy.ufunc'>
    >>> #---------------#
    >>> type(np.max)
    <class 'function'>
    >>> type(np.nanmax)
    <class 'function'>
    

And finally, the same rules apply to the four minimum related functions:

  • np.amin/np.min, np.nanmin;
  • and np.minimum, np.fmin.

Convert byte to string in Java

String str = "0x63";
int temp = Integer.parseInt(str.substring(2, 4), 16);
char c = (char)temp;
System.out.print(c);

How to select the first, second, or third element with a given class name?

Yes, you can do this. For example, to style the td tags that make up the different columns of a table you could do something like this:

table.myClass tr > td:first-child /* First column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td /* Second column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td+td /* Third column */
{
  /* some style here */
}

Regular expression containing one word or another

You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:

([0-9]+)\s+((\bseconds\b)|(\bminutes\b))

Without those you were either matching a number followed by seconds OR just the word minutes

GridLayout and Row/Column Span Woe

Android Support V7 GridLayout library makes excess space distribution easy by accommodating the principle of weight. To make a column stretch, make sure the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity. Remember to add dependency for this library. Add com.android.support:gridlayout-v7:25.0.1 in build.gradle.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:columnCount="2"
app:rowCount="2">

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="First"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="Second"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"
    android:text="Third"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1" />

<TextView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center"        
    app:layout_columnWeight="1"
    app:layout_rowWeight="1"
    android:text="fourth"/>

</android.support.v7.widget.GridLayout>

Get current cursor position

GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.

Hiding the cursor can be done with ShowCursor().

Is there a way to list open transactions on SQL Server 2000 database?

For all databases query sys.sysprocesses

SELECT * FROM sys.sysprocesses WHERE open_tran = 1

For the current database use:

DBCC OPENTRAN

Hide Text with CSS, Best Practice?

Another way

position: absolute;
top: 0px;
left: -5000px;

Css Move element from left to right animated

Try this

_x000D_
_x000D_
div_x000D_
{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:red;_x000D_
  transition: all 1s ease-in-out;_x000D_
  -webkit-transition: all 1s ease-in-out;_x000D_
  -moz-transition: all 1s ease-in-out;_x000D_
  -o-transition: all 1s ease-in-out;_x000D_
  -ms-transition: all 1s ease-in-out;_x000D_
  position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
  transform: translate(3em,0);_x000D_
  -webkit-transform: translate(3em,0);_x000D_
  -moz-transform: translate(3em,0);_x000D_
  -o-transform: translate(3em,0);_x000D_
  -ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

DEMO

is there a require for json in node.js

You can import json files by using the node.js v14 experimental json modules flag. More details here

file.js

import data from './folder/file.json'

export default {
  foo () {
    console.log(data)
  }
}

And you call it with node --experimental-json-modules file.js

How to search for string in an array

Here's another answer. It works fast, reliably (see atomicules' answer) and has compact calling code:

' Returns true if item is in the array; false otherwise.
Function IsInArray(ar, item$) As Boolean
    Dim delimiter$, list$

    ' Chr(7) is the ASCII 'Bell' Character.
    ' It was chosen for being unlikely to be found in a normal array.
    delimiter = Chr(7)

    ' Create a list string containing all the items in the array separated by the delimiter.
    list = delimiter & Join(ar, delimiter) & delimiter

    IsInArray = InStr(list, delimiter & item & delimiter) > 0
End Function

Sample usage:

Sub test()
    Debug.Print "Is 'A' in the list?", IsInArray(Split("A,B", ","), "A")
End Sub

Gets last digit of a number

public static void main(String[] args) {

    System.out.println(lastDigit(2347));
}

public static int lastDigit(int number)
{
    //your code goes here. 
    int last = number % 10;

    return last;
}

0/p:

7

Bootstrap 3 2-column form layout

As mentioned earlier, you can use the grid system to layout your inputs and labels anyway that you want. The trick is to remember that you can use rows within your columns to break them into twelfths as well.

The example below is one possible way to accomplish your goal and will put the two text boxes near Label3 on the same line when the screen is small or larger.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset="utf-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->_x000D_
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
    <!--[if lt IE 9]>_x000D_
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>_x000D_
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>_x000D_
    <![endif]-->_x000D_
  </head>_x000D_
  <body>_x000D_
    <div class="row">_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <label>Label1</label>_x000D_
            <input class="form-control" type="text"/>_x000D_
        </div>_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <label>Label2</label>_x000D_
            <input class="form-control" type="text"/>_x000D_
        </div>_x000D_
        <div class="col-xs-6">_x000D_
            <div class="row">_x000D_
                <label class="col-xs-12">Label3</label>_x000D_
            </div>_x000D_
            <div class="row">_x000D_
                <div class="col-xs-12 col-sm-6">_x000D_
                    <input class="form-control" type="text"/>_x000D_
                </div>_x000D_
                <div class="col-xs-12 col-sm-6">_x000D_
                    <input class="form-control" type="text"/>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <label>Label4</label>_x000D_
            <input class="form-control" type="text"/>_x000D_
        </div>_x000D_
    </div>_x000D_
   _x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/m3u8bjv0/2/

How much memory can a 32 bit process access on a 64 bit operating system?

The limit is not 2g or 3gb its 4gb for 32bit.

The reason people think its 3gb is that the OS shows 3gb free when they really have 4gb of system ram.

Its total RAM of 4gb. So if you have a 1 gb video card that counts as part of the total ram viewed by the 32bit OS.

4Gig not 3 not 2 got it?

Failed to instantiate module error in Angular js

I got this error due to not pointing the script to the correct path. So make absolutely sure that you are pointing to the correct path in you html file.

How to convert string values from a dictionary, into int/float datatypes?

If that's your exact format, you can go through the list and modify the dictionaries.

for item in list_of_dicts:
    for key, value in item.iteritems():
        try:
            item[key] = int(value)
        except ValueError:
            item[key] = float(value)

If you've got something more general, then you'll have to do some kind of recursive update on the dictionary. Check if the element is a dictionary, if it is, use the recursive update. If it's able to be converted into a float or int, convert it and modify the value in the dictionary. There's no built-in function for this and it can be quite ugly (and non-pythonic since it usually requires calling isinstance).

Convert js Array() to JSon object for use with JQuery .ajax

There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:

var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}

There is no need of converting it into JSON because its already a json object. To view the same use json.toSource();

SQLAlchemy create_all() does not create tables

You should put your model class before create_all() call, like this:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

If your models are declared in a separate module, import them before calling create_all().

Say, the User model is in a file called models.py,

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

# See important note below
from models import User

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

Important note: It is important that you import your models after initializing the db object since, in your models.py _you also need to import the db object from this module.

Convert absolute path into relative path given a current directory using Bash

This script gives correct results only for inputs that are absolute paths or relative paths without . or ..:

#!/bin/bash

# usage: relpath from to

if [[ "$1" == "$2" ]]
then
    echo "."
    exit
fi

IFS="/"

current=($1)
absolute=($2)

abssize=${#absolute[@]}
cursize=${#current[@]}

while [[ ${absolute[level]} == ${current[level]} ]]
do
    (( level++ ))
    if (( level > abssize || level > cursize ))
    then
        break
    fi
done

for ((i = level; i < cursize; i++))
do
    if ((i > level))
    then
        newpath=$newpath"/"
    fi
    newpath=$newpath".."
done

for ((i = level; i < abssize; i++))
do
    if [[ -n $newpath ]]
    then
        newpath=$newpath"/"
    fi
    newpath=$newpath${absolute[i]}
done

echo "$newpath"

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

run main class of Maven project

Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec

Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec, as I have ~/bin in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...

Launch it from the root of your project, where you can see src and target dirs.

The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)

$ mvnexec 
 1) org.jmeld.ui.JMeldComponent
 2) org.jmeld.ui.text.FileDocument
 3) org.jmeld.JMeld
 4) org.jmeld.util.UIDefaultsPrint
 5) org.jmeld.util.PrintProperties
 6) org.jmeld.util.file.DirectoryDiff
 7) org.jmeld.util.file.VersionControlDiff
 8) org.jmeld.vc.svn.InfoCmd
 9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#? 

If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P)

By default it compiles project every run. but you can avoid that using mvnexec -B

It allows to search only in test classes -M or --no-main, or only in main classes -T or --no-test. also has a filter by name option -f <whatever>

Hope this could save you some time, for me it does.

How to make function decorators and chain them together?

And of course you can return lambdas as well from a decorator function:

def makebold(f): 
    return lambda: "<b>" + f() + "</b>"
def makeitalic(f): 
    return lambda: "<i>" + f() + "</i>"

@makebold
@makeitalic
def say():
    return "Hello"

print say()

Node.js server that accepts POST requests

Receive POST and GET request in nodejs :

1).Server

    var http = require('http');
    var server = http.createServer ( function(request,response){

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();

Rails raw SQL example

You can do direct SQL to have a single query for both tables. I'll provide a sanitized query example to hopefully keep people from putting variables directly into the string itself (SQL injection danger), even though this example didn't specify the need for it:

@results = []
ActiveRecord::Base.connection.select_all(
  ActiveRecord::Base.send(:sanitize_sql_array, 
   ["... your SQL query goes here and ?, ?, ? are replaced...;", a, b, c])
).each do |record|
  # instead of an array of hashes, you could put in a custom object with attributes
  @results << {col_a_name: record["col_a_name"], col_b_name: record["col_b_name"], ...}
end

Edit: as Huy said, a simple way is ActiveRecord::Base.connection.execute("..."). Another way is ActiveRecord::Base.connection.exec_query('...').rows. And you can use native prepared statements, e.g. if using postgres, prepared statement can be done with raw_connection, prepare, and exec_prepared as described in https://stackoverflow.com/a/13806512/178651

You can also put raw SQL fragments into ActiveRecord relational queries: http://guides.rubyonrails.org/active_record_querying.html and in associations, scopes, etc. You could probably construct the same SQL with ActiveRecord relational queries and can do cool things with ARel as Ernie mentions in http://erniemiller.org/2010/03/28/advanced-activerecord-3-queries-with-arel/. And, of course there are other ORMs, gems, etc.

If this is going to be used a lot and adding indices won't cause other performance/resource issues, consider adding an index in the DB for payment_details.created_at and for payment_errors.created_at.

If lots of records and not all records need to show up at once, consider using pagination:

If you need to paginate, consider creating a view in the DB first called payment_records which combines the payment_details and payment_errors tables, then have a model for the view (which will be read-only). Some DBs support materialized views, which might be a good idea for performance.

Also consider hardware or VM specs on Rails server and DB server, config, disk space, network speed/latency/etc., proximity, etc. And consider putting DB on different server/VM than the Rails app if you haven't, etc.

How to loop through all elements of a form jQuery

pure JavaScript is not that difficult:

for(var i=0; i < form.elements.length; i++){
    var e = form.elements[i];
    console.log(e.name+"="+e.value);
}

Note: because form.elements is a object for-in loop does not work as expected.

Answer found here (by Chris Pietschmann), documented here (W3S).

downcast and upcast

Upcasting (using (Employee)someInstance) is generally easy as the compiler can tell you at compile time if a type is derived from another.

Downcasting however has to be done at run time generally as the compiler may not always know whether the instance in question is of the type given. C# provides two operators for this - is which tells you if the downcast works, and return true/false. And as which attempts to do the cast and returns the correct type if possible, or null if not.

To test if an employee is a manager:

Employee m = new Manager();
Employee e = new Employee();

if(m is Manager) Console.WriteLine("m is a manager");
if(e is Manager) Console.WriteLine("e is a manager");

You can also use this

Employee someEmployee = e  as Manager;
    if(someEmployee  != null) Console.WriteLine("someEmployee (e) is a manager");

Employee someEmployee = m  as Manager;
    if(someEmployee  != null) Console.WriteLine("someEmployee (m) is a manager");

How to convert upper case letters to lower case

str.lower() converts all cased characters to lowercase.

Arrays in cookies PHP

Cookies are basically text, so you can store an array by encoding it as a JSON string (see json_encode). Be aware that there is a limit on the length of the string you can store though.

How do I pass a class as a parameter in Java?

Class as paramater. Example.

Three classes:

class TestCar {

    private int UnlockCode = 111;
    protected boolean hasAirCondition = true;
    String brand = "Ford";
    public String licensePlate = "Arizona 111";
}

--

class Terminal {

public void hackCar(TestCar car) {
     System.out.println(car.hasAirCondition);
     System.out.println(car.licensePlate);
     System.out.println(car.brand);
     }
}

--

class Story {

    public static void main(String args[]) {
        TestCar testCar = new TestCar();
        Terminal terminal = new Terminal();
        terminal.hackCar(testCar);
    }

}

In class Terminal method hackCar() take class TestCar as parameter.

How do I apply a diff patch on Windows?

When applying patches using TortoiseSVN, I typically save the path in the root of the checked out repository. You should then be able to right click on the patch, go to the TortoiseSVN menu, and click ApplyPatch. ApplyPatch should automatically figure out which level in the directory hierarchy the patch was created.

I have, however, had issues in the past with applying patches that contain new files, or which involve renames to files. Whatever algorithm Tortoise uses for this doesn't seem to handle those scenarios very well. Unicode can give you similar issues.

How do I indent multiple lines at once in Notepad++?

If you're using QuickText and like pressing Tab for it, you can otherwise change the indentation key.

Go Settings > Shortcup Mapper > Scintilla Command. Look at the number 10.

  • I changed 10 to : CTRL + ALT + RIGHT and
  • 11 to : CTRL+ ALT+ LEFT.

Now I think it's even better than the TABL / SHIFT + TAB as default.

Change directory in Node.js command prompt

  1. Open file nodevars.bat
  2. Just add your path to the end, "%HOMEDRIVE%%HOMEPATH% /file1/file2/file3
  3. Save file nodevars.bat

This work even with Swedish words

Heroku deployment error H10 (App crashed)

I had the same issue (same error on heroku, working on local machine) and I tried all the solutions listed here including heroku run rails console which ran without error messages. I tried heroku run rake db:migrate and heroku run rake db:migrate:reset a few times. None of this solved the problem. On going through some files that are used in production but not in dev environment, I found some whitespace in the puma.rb file to be the culprit. Hope this helps someone who has the same issue. Changing this made it work

  ActiveRecord::Base.establish_connection
  End

to

  ActiveRecord::Base.establish_connection
end

How do I share a global variable between c files?

Use extern keyword in another .c file.

How to call a method daily, at specific time, in C#?

As others have said you can use a console app to run when scheduled. What others haven't said is that you can this app trigger a cross process EventWaitHandle which you are waiting on in your main application.

Console App:

class Program
{
    static void Main(string[] args)
    {
        EventWaitHandle handle = 
            new EventWaitHandle(true, EventResetMode.ManualReset, "GoodMutexName");
        handle.Set();
    }
}

Main App:

private void Form1_Load(object sender, EventArgs e)
{
    // Background thread, will die with application
    ThreadPool.QueueUserWorkItem((dumby) => EmailWait());
}

private void EmailWait()
{
    EventWaitHandle handle = 
        new EventWaitHandle(false, EventResetMode.ManualReset, "GoodMutexName");

    while (true)
    {
        handle.WaitOne();

        SendEmail();

        handle.Reset();
    }
}

How do I convert an existing callback API to promises?

In Node.js 8 you can promisify object methods on the fly using this npm module:

https://www.npmjs.com/package/doasync

It uses util.promisify and Proxies so that your objects stay unchanged. Memoization is also done with the use of WeakMaps). Here are some examples:

With objects:

const fs = require('fs');
const doAsync = require('doasync');

doAsync(fs).readFile('package.json', 'utf8')
  .then(result => {
    console.dir(JSON.parse(result), {colors: true});
  });

With functions:

doAsync(request)('http://www.google.com')
  .then(({body}) => {
    console.log(body);
    // ...
  });

You can even use native call and apply to bind some context:

doAsync(myFunc).apply(context, params)
  .then(result => { /*...*/ });

Python Pandas replicate rows in dataframe

Other way is using concat() function:

import pandas as pd

In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

In [604]: df
Out[604]: 
  col1  col2
0    a     0
1    b     1
2    c     2

In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]: 
  col1  col2
0    a     0
1    b     1
2    c     2
3    a     0
4    b     1
5    c     2
6    a     0
7    b     1
8    c     2

In [606]: pd.concat([df]*3)
Out[606]: 
  col1  col2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2
0    a     0
1    b     1
2    c     2

Replace part of a string in Python?

Use the replace() method on string:

>>> stuff = "Big and small"
>>> stuff.replace( " and ", "/" )
'Big/small'

Change the color of cells in one column when they don't match cells in another column

  1. Select your range from cell A (or the whole columns by first selecting column A). Make sure that the 'lighter coloured' cell is A1 then go to conditional formatting, new rule:

    enter image description here

  2. Put the following formula and the choice of your formatting (notice that the 'lighter coloured' cell comes into play here, because it is being used in the formula):

    =$A1<>$B1
    

    enter image description here

  3. Then press OK and that should do it.

    enter image description here

How do you reverse a string in place in C or C++?

Note that the beauty of std::reverse is that it works with char * strings and std::wstrings just as well as std::strings

void strrev(char *str)
{
    if (str == NULL)
        return;
    std::reverse(str, str + strlen(str));
}

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

Should work in all cases:

SELECT regexp_replace(0.1234, '^(-?)([.,])', '\10\2') FROM dual

How to add an image to an svg container using D3.js

 var svg = d3.select("body")
        .append("svg")
        .style("width", 200)
        .style("height", 100)

How to create a fixed sidebar layout with Bootstrap 4?

I'm using the J.S. to fix a sidebar menu. I've tried a lot of solutions with CSS but it's the simplest way to solve it, just add J.S. adding and removing a native BootStrap class: "position-fixed".

The J.S.:

var lateral = false;
function fixar() {

            var element, name, arr;
            element = document.getElementById("minhasidebar");

            if (lateral) {
                element.className = element.className.replace(
                        /\bposition-fixed\b/g, "");
                lateral = false;
            } else {

                name = "position-fixed";
                arr = element.className.split(" ");
                if (arr.indexOf(name) == -1) {
                    element.className += " " + name;
                }
                lateral = true;
            }

        }

The HTML:

Sidebar:

<aside>
        <nav class="sidebar ">
             <div id="minhasidebar">
                 <ul class="nav nav-pills">
                     <li class="nav-item"><a class="nav-link active" 
                     th:href="@{/hoje/inicial}"> <i class="oi oi-clipboard"></i> 
                     <span>Hoje</span>
                     </a></li>
                 </ul>
             </div>
        </nav>            
</aside>

Storing Python dictionaries

Also see the speeded-up package ujson:

import ujson

with open('data.json', 'wb') as fp:
    ujson.dump(data, fp)

In PowerShell, how do I test whether or not a specific variable exists in global scope?

So far, it looks like the answer that works is this one.

To break it out further, what worked for me was this:

Get-Variable -Name foo -Scope Global -ea SilentlyContinue | out-null

$? returns either true or false.

How do I get cURL to not show the progress bar?

In curl version 7.22.0 on Ubuntu and 7.24.0 on OSX the solution to not show progress but to show errors is to use both -s (--silent) and -S (--show-error) like so:

curl -sS http://google.com > temp.html

This works for both redirected output > /some/file, piped output | less and outputting directly to the terminal for me.

Update: Since curl 7.67.0 there is a new option --no-progress-meter which does precisely this and nothing else, see clonejo's answer for more details.

Array of arrays (Python/NumPy)

It seems strange that you would write arrays without commas (is that a MATLAB syntax?)

Have you tried going through NumPy's documentation on multi-dimensional arrays?

It seems NumPy has a "Python-like" append method to add items to a NumPy n-dimensional array:

>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)

>>> p = np.append(p, [[7],[8],[9]],1)

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

It has also been answered already...

From the documentation for MATLAB users:

You could use a matrix constructor which takes a string in the form of a matrix MATLAB literal:

mat("1 2 3; 4 5 6")

or

matrix("[1 2 3; 4 5 6]")

Please give it a try and tell me how it goes.

How to open the terminal in Atom?

I didn't want to install a package just for that purpose so I ended up using this in my init.coffee:

spawn = require('child_process').spawn
atom.commands.add 'atom-text-editor', 'open-terminal', ->
  file = atom.workspace.getActiveTextEditor().getPath()
  dir = atom.project.getDirectoryForProjectPath(file).path
  spawn 'mate-terminal', ["--working-directory=#{dir}"], {
    detached: true
  }

With that, I could map ctrl-shift-t to the open-terminal command and it opens a mate-terminal.

deleted object would be re-saved by cascade (remove deleted object from associations)

Some how all the above solutions did not worked in hibernate 5.2.10.Final.

But setting the map to null as below worked for me:

playlist.setPlaylistadMaps(null);

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

JQuery / JavaScript - trigger button click from another button click event

Add id's to both inputs, id="first" and id="second"

//trigger second button
$("#second").click()

jQuery AJAX form data serialize using PHP

<form method="post" name="myForm" id="myForm">

replace with above form tag remove action from form tag. and set url : "check.php" in ajax in your case first it goes to jQuery ajax then submit again the form. that's why it's creating issue.

i know i'm too late for this reply but i think it would help.

How to set my default shell on Mac?

Terminal.app > Preferences > General > Shells open with: > /bin/fish

  1. Open your terminal and press command+, (comma). This will open a preferences window.
  2. The first tab is 'General'.
  3. Find 'Shells open with' setting and choose 2nd option which needs complete path to the shell.
  4. Paste the link to your fish command, which generally is /usr/local/bin/fish.

See this screenshot where zsh is being set as default.

screenshot of entering <code>/bin/zsh</code> in Terminal.app preferences

I am using macOS Sierra. Also works in macOS Mojave.

Change icon on click (toggle)

Instead of overwriting the html every time, just toggle the class.

$('#click_advance').click(function() {
    $('#display_advance').toggle('1000');
    $("i", this).toggleClass("icon-circle-arrow-up icon-circle-arrow-down");
});

Simpler way to create dictionary of separate variables?

While this is probably an awful idea, it is along the same lines as rlotun's answer but it'll return the correct result more often.

import inspect
def getVarName(getvar):
  frame = inspect.currentframe()
  callerLocals = frame.f_back.f_locals
  for k, v in list(callerLocals.items()):
    if v is getvar():
      callerLocals.pop(k)
      try:
        getvar()
        callerLocals[k] = v
      except NameError:
        callerLocals[k] = v
        del frame
        return k
  del frame

You call it like this:

bar = True
foo = False
bean = False
fooName = getVarName(lambda: foo)
print(fooName) # prints "foo"

How do I get ruby to print a full backtrace instead of a truncated one?

[examine all threads backtraces to find the culprit]
Even fully expanded call stack can still hide the actual offending line of code from you when you use more than one thread!

Example: One thread is iterating ruby Hash, other thread is trying to modify it. BOOM! Exception! And the problem with the stack trace you get while trying to modify 'busy' hash is that it shows you chain of functions down to the place where you're trying to modify hash, but it does NOT show who's currently iterating it in parallel (who owns it)! Here's the way to figure that out by printing stack trace for ALL currently running threads. Here's how you do this:

# This solution was found in comment by @thedarkone on https://github.com/rails/rails/issues/24627
rescue Object => boom

    thread_count = 0
    Thread.list.each do |t|
      thread_count += 1
      err_msg += "--- thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace begin \n"
      # Lets see if we are able to pin down the culprit
      # by collecting backtrace for all existing threads:
      err_msg += t.backtrace.join("\n")
      err_msg += "\n---thread #{thread_count} of total #{Thread.list.size} #{t.object_id} backtrace end \n"
    end

    # and just print it somewhere you like:
    $stderr.puts(err_msg)

    raise # always reraise
end

The above code snippet is useful even just for educational purposes as it can show you (like x-ray) how many threads you actually have (versus how many you thought you have - quite often those two are different numbers ;)

How to use font-awesome icons from node-modules

You have to set the proper font path. e.g.

my-style.scss

$fa-font-path:"../node_modules/font-awesome/fonts";
@import "../node_modules/font-awesome/scss/font-awesome";
.icon-user {
  @extend .fa;
  @extend .fa-user;
}

How can one display images side by side in a GitHub README.md?

The easiest way I can think of solving this is using the tables included in GitHub's flavored markdown.

To your specific example it would look something like this:

Solarized dark             |  Solarized Ocean
:-------------------------:|:-------------------------:
![](https://...Dark.png)  |  ![](https://...Ocean.png)

This creates a table with Solarized Dark and Ocean as headers and then contains the images in the first row. Obviously you would replace the ... with the real link. The :s are optional (They just center the content in the cells, which is kinda unnecessary in this case). Also you might want to downsize the images so they will display better side-by-side.

ThreeJS: Remove object from scene

THIS WORKS GREAT - I tested it so, please SET NAME for every object

give the name to the object upon creation

    mesh.name = 'nameMeshObject';

and use this if you have to delete an object

    delete3DOBJ('nameMeshObject');



    function delete3DOBJ(objName){
        var selectedObject = scene.getObjectByName(objName);
        scene.remove( selectedObject );
        animate();
    }

open a new scene , add object open new scene , add object

delete an object and create new delete object and create new

TypeError: $.browser is undefined

Somewhere the code--either your code or a jQuery plugin--is calling $.browser to get the current browser type.

However, early has year the $.browser function was deprecated. Since then some bugs have been filed against it but because it is deprecated, the jQuery team has decided not to fix them. I've decided not to rely on the function at all.

I don't see any references to $.browser in your code, so the problem probably lies in one of your plugins. To find it, look at the source code for each plugin that you've referenced with a <script> tag.

As for how to fix it: well, it depends on the context. E.g., maybe there's an updated version of the problematic plugin. Or perhaps you can use another plugin that does something similar but doesn't depend on $.browser.

How to print a two dimensional array?

more simpler approach , use java 5 style for loop

Integer[][] twoDimArray = {{8, 9},{8, 10}};
        for (Integer[] array: twoDimArray){
            System.out.print(array[0] + " ,");
            System.out.println(array[1]);
        }

Resize image in PHP

This resource(broken link) is also worth considering - some very tidy code that uses GD. However, I modified their final code snippet to create this function which meets the OPs requirements...

function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
    
    $target_dir = "your-uploaded-images-folder/";
    $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
    
    $image = new SimpleImage();
    $image->load($_FILES[$html_element_name]['tmp_name']);
    $image->resize($new_img_width, $new_img_height);
    $image->save($target_file);
    return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user
    
}

You will also need to include this PHP file...

<?php
 
/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/
 
class SimpleImage {
 
   var $image;
   var $image_type;
 
   function load($filename) {
 
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {
 
         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
 
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
 
         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image,$filename);
      }
      if( $permissions != null) {
 
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image);
      }
   }
   function getWidth() {
 
      return imagesx($this->image);
   }
   function getHeight() {
 
      return imagesy($this->image);
   }
   function resizeToHeight($height) {
 
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
 
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
 
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }
 
   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }      
 
}
?>

Oracle SQL Developer: Unable to find a JVM

There is another route of failure, besides the version of Java you are running: You could be running out of Heap/RAM

If you had a once working version of SQLDeveloper, and you are starting to see the screenshot referenced in the original post, then you can try to adjust the amount of space SQLDeveloper requests when starting up.

Edit the file:

/ide/bin/ide.conf

Edit the line that specifies the max ram to use: AddVMOption -Xmx, reducing the size. For example I changed my file to have the following lines, which solved the issue.

#AddVMOption  -Xmx640M   # Original Value
AddVMOption  -Xmx256M    # New Value

How do I compare a value to a backslash?

When you only need to check for equality, you can also simply use the in operator to do a membership test in a sequence of accepted elements:

if message.value[0] in ('/', '\\'):
    do_stuff()

Can I use Twitter Bootstrap and jQuery UI at the same time?

Kendo UI has a nice bootstrap theme here and a set of web UI comparable to jquery-UI. They also have an open source version that works nicely with the theme.

How to split string and push in array using jquery

var string = 'a,b,c,d',
    strx   = string.split(',');
    array  = [];

array = array.concat(strx);
// ["a","b","c","d"]

Select method in List<t> Collection

Well, to start with List<T> does have the FindAll and ConvertAll methods - but the more idiomatic, modern approach is to use LINQ:

// Find all the people older than 30
var query1 = list.Where(person => person.Age > 30);

// Find each person's name
var query2 = list.Select(person => person.Name);

You'll need a using directive in your file to make this work:

using System.Linq;

Note that these don't use strings to express predicates and projects - they use delegates, usually created from lambda expressions as above.

If lambda expressions and LINQ are new to you, I would suggest you get a book covering LINQ first, such as LINQ in Action, Pro LINQ, C# 4 in a Nutshell or my own C# in Depth. You certainly can learn LINQ just from web tutorials, but I think it's such an important technology, it's worth taking the time to learn it thoroughly.

Convert float to std::string in C++

Important:
Read the note at the end.

Quick answer :
Use to_string(). (available since c++11)
example :

#include <iostream>   
#include <string>  

using namespace std;
int main ()
{
    string pi = "pi is " + to_string(3.1415926);
    cout<< "pi = "<< pi << endl;

  return 0;
}

run it yourself : http://ideone.com/7ejfaU
These are available as well :

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

Important Note:
As @Michael Konecný rightfully pointed out, using to_string() is risky at best that is its very likely to cause unexpected results.
From http://en.cppreference.com/w/cpp/string/basic_string/to_string :

With floating point types std::to_string may yield unexpected results as the number of significant digits in the returned string can be zero, see the example.
The return value may differ significantly from what std::cout prints by default, see the example. std::to_string relies on the current locale for formatting purposes, and therefore concurrent calls to std::to_string from multiple threads may result in partial serialization of calls. C++17 provides std::to_chars as a higher-performance locale-independent alternative.

The best way would be to use stringstream as others such as @dcp demonstrated in his answer.:

This issue is demonstrated in the following example :
run the example yourself : https://www.jdoodle.com/embed/v0/T4k

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

template < typename Type > std::string to_str (const Type & t)
{
  std::ostringstream os;
  os << t;
  return os.str ();
}

int main ()
{

  // more info : https://en.cppreference.com/w/cpp/string/basic_string/to_string
  double    f = 23.43;
  double    f2 = 1e-9;
  double    f3 = 1e40;
  double    f4 = 1e-40;
  double    f5 = 123456789;
  std::string f_str = std::to_string (f);
  std::string f_str2 = std::to_string (f2); // Note: returns "0.000000"
  std::string f_str3 = std::to_string (f3); // Note: Does not return "1e+40".
  std::string f_str4 = std::to_string (f4); // Note: returns "0.000000"
  std::string f_str5 = std::to_string (f5);

  std::cout << "std::cout: " << f << '\n'
    << "to_string: " << f_str << '\n'
    << "ostringstream: " << to_str (f) << "\n\n"
    << "std::cout: " << f2 << '\n'
    << "to_string: " << f_str2 << '\n'
    << "ostringstream: " << to_str (f2) << "\n\n"
    << "std::cout: " << f3 << '\n'
    << "to_string: " << f_str3 << '\n'
    << "ostringstream: " << to_str (f3) << "\n\n"
    << "std::cout: " << f4 << '\n'
    << "to_string: " << f_str4 << '\n'
    << "ostringstream: " << to_str (f4) << "\n\n"
    << "std::cout: " << f5 << '\n'
    << "to_string: " << f_str5 << '\n'
    << "ostringstream: " << to_str (f5) << '\n';

  return 0;
}

output :

std::cout: 23.43
to_string: 23.430000
ostringstream: 23.43

std::cout: 1e-09
to_string: 0.000000
ostringstream: 1e-09

std::cout: 1e+40
to_string: 10000000000000000303786028427003666890752.000000
ostringstream: 1e+40

std::cout: 1e-40
to_string: 0.000000
ostringstream: 1e-40

std::cout: 1.23457e+08
to_string: 123456789.000000
ostringstream: 1.23457e+08 

Laravel - Route::resource vs Route::controller

RESTful Resource controller

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

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

Gives you these named routes:

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

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

class UsersController extends BaseController {

    public function index() {}

    public function show($id) {}

    public function store() {}

}

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

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

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

API Resource controller

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

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

RESTful Resource Controller documentation


Implicit controller

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

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

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

class UserController extends BaseController {

    public function getIndex()
    {
        // GET request to index
    }

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

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

}

Implicit Controller documentation


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

Simplest code for array intersection in javascript

If you need to have it handle intersecting multiple arrays:

_x000D_
_x000D_
const intersect = (a1, a2, ...rest) => {
  const a12 = a1.filter(value => a2.includes(value))
  if (rest.length === 0) { return a12; }
  return intersect(a12, ...rest);
};

console.log(intersect([1,2,3,4,5], [1,2], [1, 2, 3,4,5], [2, 10, 1])) 
_x000D_
_x000D_
_x000D_

Concatenating Column Values into a Comma-Separated List

You can do a shortcut using coalesce to concatenate a series of strings from a record in a table, for example.

declare @aa varchar (200)
set @aa = ''

select @aa = 
    case when @aa = ''
    then CarName
    else @aa + coalesce(',' + CarName, '')
    end
  from Cars

print @aa

Is there an upper bound to BigInteger?

The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.

Functional style of Java 8's Optional.ifPresent and if-not-Present?

Another solution would be to use higher-order functions as follows

opt.<Runnable>map(value -> () -> System.out.println("Found " + value))
   .orElse(() -> System.out.println("Not Found"))
   .run();

Replacing NULL with 0 in a SQL server query

If you are using Presto, AWS Athena etc, there is no ISNULL() function. Instead, use:

SELECT COALESCE(myColumn, 0 ) FROM myTable

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

First install "Microsoft ASP.NET Web API Client" nuget package:

  PM > Install-Package Microsoft.AspNet.WebApi.Client

Then use the following function to post your data:

public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
    using (var httpClient = new HttpClient())
    {
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsAsync<TResult>();
        }
    }
}

And this is how to use it:

TokenResponse tokenResponse = 
    await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);

or

TokenResponse tokenResponse = 
    (Task.Run(async () 
        => await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
        .Result

or (not recommended)

TokenResponse tokenResponse = 
    PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;

Determine if char is a num or letter

chars are just integers, so you can actually do a straight comparison of your character against literals:

if( c >= '0' && c <= '9' ){

This applies to all characters. See your ascii table.

ctype.h also provides functions to do this for you.

Send HTML in email via PHP

I have a this code and it will run perfectly for my site

  public function forgotpassword($pass,$name,$to)
    {
        $body ="<table  width=100% border=0><tr><td>";
        $body .= "<img width=200 src='";
        $body .= $this->imageUrl();
        $body .="'></img></td><td style=position:absolute;left:350;top:60;><h2><font color = #346699>PMS Pvt Ltd.</font><h2></td></tr>";
        $body .='<tr><td colspan=2><br/><br/><br/><strong>Dear '.$name.',</strong></td></tr>';
        $body .= '<tr><td colspan=2><br/><font size=3>As per Your request we send Your Password.</font><br/><br/>Password is : <b>'.$pass.'</b></td></tr>';
        $body .= '<tr><td colspan=2><br/>If you have any questions, please feel free to contact us at:<br/><a href="mailto:[email protected]" target="_blank">[email protected]</a></td></tr>';
        $body .= '<tr><td colspan=2><br/><br/>Best regards,<br>The PMS Team.</td></tr></table>';
        $subject = "Forgot Password";
        $this->sendmail($body,$to,$subject);
    }

mail function

   function sendmail($body,$to,$subject)
        {
            //require_once 'init.php';


            $from='[email protected]';      
            $headersfrom='';
            $headersfrom .= 'MIME-Version: 1.0' . "\r\n";
            $headersfrom .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
            $headersfrom .= 'From: '.$from.' '. "\r\n";
            mail($to,$subject,$body,$headersfrom);
        }

image url function is use for if you want to change the image you have change in only one function i have many mail function like forgot password create user there for i am use image url function you can directly set path.

function imageUrl()
    {
        return "http://".$_SERVER['SERVER_NAME'].substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], "/")+1)."images/capacity.jpg";
    }

Multiple aggregations of the same column using pandas GroupBy.agg()

Would something like this work:

In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]: 
              func2     func1
dummy                        
1     -4.263768e-16 -0.188565

Add Favicon with React and Webpack

Browsers look for your favicon in /favicon.ico, so that's where it needs to be. You can double check if you've positioned it in the correct place by navigating to [address:port]/favicon.ico and seeing if your icon appears.

In dev mode, you are using historyApiFallback, so will need to configure webpack to explicitly return your icon for that route:

historyApiFallback: {
    index: '[path/to/index]',
    rewrites: [
        // shows favicon
        { from: /favicon.ico/, to: '[path/to/favicon]' }
    ]
}

In your server.js file, try explicitly rewriting the url:

app.configure(function() {
    app.use('/favicon.ico', express.static(__dirname + '[route/to/favicon]'));
});

(or however your setup prefers to rewrite urls)

I suggest generating a true .ico file rather than using a .png, since I've found that to be more reliable across browsers.

Postgres integer arrays as parameters?

You can always use a properly formatted string. The trick is the formatting.

command.Parameters.Add("@array_parameter", string.Format("{{{0}}}", string.Join(",", array));

Note that if your array is an array of strings, then you'll need to use array.Select(value => string.Format("\"{0}\", value)) or the equivalent. I use this style for an array of an enumerated type in PostgreSQL, because there's no automatic conversion from the array.

In my case, my enumerated type has some values like 'value1', 'value2', 'value3', and my C# enumeration has matching values. In my case, the final SQL query ends up looking something like (E'{"value1","value2"}'), and this works.

jQuery get the location of an element relative to window

function getWindowRelativeOffset(parentWindow, elem) {
        var offset = {
            left : 0,
            top : 0
        };
        // relative to the target field's document
        offset.left = elem.getBoundingClientRect().left;
        offset.top = elem.getBoundingClientRect().top;
        // now we will calculate according to the current document, this current
        // document might be same as the document of target field or it may be
        // parent of the document of the target field
        var childWindow = elem.document.frames.window;
        while (childWindow != parentWindow) {
            offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
            offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
            childWindow = childWindow.parent;
        }
        return offset;
    };

you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus for IE only as per my requirement but similar can be done for other browsers

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

How to fix 'android.os.NetworkOnMainThreadException'?

The error is due to executing long running operations in main thread,You can easily rectify the problem by using AsynTask or Thread. You can checkout this library AsyncHTTPClient for better handling.

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {

    @Override
    public void onStart() {
        // Called before a request is started
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        // Called when response HTTP status is "200 OK"
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        // Called when response HTTP status is "4XX" (for example, 401, 403, 404)
    }

    @Override
    public void onRetry(int retryNo) {
        // Called when request is retried
    }
});

How to use icons and symbols from "Font Awesome" on Native Android Application

As all answers are great but I didn't want to use a library and each solution with just one line java code made my Activities and Fragments very messy. So I over wrote the TextView class as follows:

public class FontAwesomeTextView extends TextView {
private static final String TAG = "TextViewFontAwesome";
public FontAwesomeTextView(Context context) {
    super(context);
    init();
}

public FontAwesomeTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init();
}

private void setCustomFont(Context ctx, AttributeSet attrs) {
    TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
    String customFont = a.getString(R.styleable.TextViewPlus_customFont);
    setCustomFont(ctx, customFont);
    a.recycle();
}

private void init() {
    if (!isInEditMode()) {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fontawesome-webfont.ttf");
        setTypeface(tf);
    }
}

public boolean setCustomFont(Context ctx, String asset) {
    Typeface typeface = null;
    try {
        typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
    } catch (Exception e) {
        Log.e(TAG, "Unable to load typeface: "+e.getMessage());
        return false;
    }

    setTypeface(typeface);
    return true;
}
}

what you should do is copy the font ttf file into assets folder .And use this cheat sheet for finding each icons string.

hope this helps.

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

I had the same issue, and I have solved it by changing my net connection. In fact, my last internet connection was too slow (45 kbit/s). So you should try again with a faster net connection.

Using Spring MVC Test to unit test multipart POST request

Here's what worked for me, here I'm attaching a file to my EmailController under test. Also take a look at the postman screenshot on how I'm posting the data.

    @WebAppConfiguration
    @RunWith(SpringRunner.class)
    @SpringBootTest(
            classes = EmailControllerBootApplication.class
        )
    public class SendEmailTest {

        @Autowired
        private WebApplicationContext webApplicationContext;

        @Test
        public void testSend() throws Exception{
            String jsonStr = "{\"to\": [\"[email protected]\"],\"subject\": "
                    + "\"CDM - Spring Boot email service with attachment\","
                    + "\"body\": \"Email body will contain  test results, with screenshot\"}";

            Resource fileResource = new ClassPathResource(
                    "screen-shots/HomePage-attachment.png");

            assertNotNull(fileResource);

            MockMultipartFile firstFile = new MockMultipartFile( 
                       "attachments",fileResource.getFilename(),
                        MediaType.MULTIPART_FORM_DATA_VALUE,
                        fileResource.getInputStream());  
                        assertNotNull(firstFile);


            MockMvc mockMvc = MockMvcBuilders.
                  webAppContextSetup(webApplicationContext).build();

            mockMvc.perform(MockMvcRequestBuilders
                   .multipart("/api/v1/email/send")
                    .file(firstFile)
                    .param("data", jsonStr))
                    .andExpect(status().is(200));
            }
        }

Postman Request

Disable/turn off inherited CSS3 transitions

If you want to disable a single transition property, you can do:

transition: color 0s;

(since a zero second transition is the same as no transition.)

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

i use $.each of jquery but you can make it with a for loop, an improvement is this:

        //.ArraySort(array)
        /* Sort an array
         */
        ArraySort = function(array, sortFunc){
              var tmp = [];
              var aSorted=[];
              var oSorted={};

              for (var k in array) {
                if (array.hasOwnProperty(k)) 
                    tmp.push({key: k, value:  array[k]});
              }

              tmp.sort(function(o1, o2) {
                    return sortFunc(o1.value, o2.value);
              });                     

              if(Object.prototype.toString.call(array) === '[object Array]'){
                  $.each(tmp, function(index, value){
                      aSorted.push(value.value);
                  });
                  return aSorted;                     
              }

              if(Object.prototype.toString.call(array) === '[object Object]'){
                  $.each(tmp, function(index, value){
                      oSorted[value.key]=value.value;
                  });                     
                  return oSorted;
              }               
     };

So now you can do

    console.log("ArraySort");
    var arr1 = [4,3,6,1,2,8,5,9,9];
    var arr2 = {'a':4, 'b':3, 'c':6, 'd':1, 'e':2, 'f':8, 'g':5, 'h':9};
    var arr3 = {a: 'green', b: 'brown', c: 'blue', d: 'red'};
    var result1 = ArraySort(arr1, function(a,b){return a-b});
    var result2 = ArraySort(arr2, function(a,b){return a-b});
    var result3 = ArraySort(arr3, function(a,b){return a>b});
    console.log(result1);
    console.log(result2);       
    console.log(result3);

What are the differences between a clustered and a non-clustered index?

Clustered Index

  • Only one per table
  • Faster to read than non clustered as data is physically stored in index order

Non Clustered Index

  • Can be used many times per table
  • Quicker for insert and update operations than a clustered index

Both types of index will improve performance when select data with fields that use the index but will slow down update and insert operations.

Because of the slower insert and update clustered indexes should be set on a field that is normally incremental ie Id or Timestamp.

SQL Server will normally only use an index if its selectivity is above 95%.

How does EL empty operator work in JSF?

Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable using not empty operator on my dataModel that extends javax.faces.model.ListDataModel

Code sample:

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;

public class EntityDataModel extends ListDataModel<Entity> implements
        Collection<Entity>, SelectableDataModel<Entity>, Serializable {

    public EntityDataModel(List<Entity> data) { super(data); }

    @Override
    public Entity getRowData(String rowKey) {
        // In a real app, a more efficient way like a query by rowKey should be
        // implemented to deal with huge data
        List<Entity> entitys = (List<Entity>) getWrappedData();
        for (Entity entity : entitys) {
            if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
        }
        return null;
    }

    @Override
    public Object getRowKey(Entity entity) {
        return entity.getId();
    }

    @Override
    public boolean isEmpty() {
        List<Entity> entity = (List<Entity>) getWrappedData();
        return (entity == null) || entity.isEmpty();
    }
    // ... other not implemented methods of Collection...
}

Java split string to array

Consider this example:

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|")));
    // output : [Real, How, To]
  }
}

The result does not include the empty strings between the "|" separator. To keep the empty strings :

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To|||";
    System.out.println
       (java.util.Arrays.toString(testString.split("\\|", -1)));
    // output : [Real, How, To, , , ]
  }
}

For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html

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

Use pwd to search from any directory you are in, recursing downward

grep -rnw `pwd` -e "pattern"

Update Depending on the version of grep you are using, you can omit pwd. On newer versions . seems to be the default case for grep if no directory is given thus:

grep -rnw -e "pattern"

or

grep -rnw "pattern"

will do the same thing as above!

Appending an id to a list if not already present in a string

There are a couple things going on with your example. You have a list containing a string of numbers and newline characters:

list = ['350882 348521 350166\r\n']

And you are trying to find a number ID within this list:

id = 348521
if id not in list:
    ...

Your first conditional is always going to pass, because it will be looking for integer 348521 in list which has one element at index list[0] with the string value of '350882 348521 350166\r\n', so integer 348521 will be added to that list, making it a list of two elements: a string and an integer, as your output shows.

To reiterate: list is searched for id, not the string in list's first element.

If you were trying to find if the string representation of '348521' was contained within the larger string contained within your list, you could do the following, noting that you would need to do this for each element in list:

if str(id) not in list[0]: # list[0]: '350882 348521 350166\r\n'
    ...                    #                  ^^^^^^

However be aware that you would need to wrap str(id) with whitespace for the search, otherwise it would also match:

2348521999
 ^^^^^^

It is unclear whether you want your "list" to be a "string of integers separated by whitespace" or if you really want a list of integers.

If all you are trying to accomplish is to have a list of IDs, and to add IDs to that list only if they are not already contained, (and if the order of the elements in the list is not important,) then a set would be the best data structure to use.

ids = set(
    [int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]
)

# Adding an ID already in the set has no effect
ids.add(348521)

If the ordering of the IDs in the string is important then I would keep your IDs in a standard list and use your conditional check:

ids = [int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]

if 348521 not in ids:
    ...

How to parse float with two decimal places in javascript?

The solution that work for me is the following

parseFloat(value)

Where to download Microsoft Visual c++ 2003 redistributable

Storm's answer is not correct. No hard feelings Storm, and apologies to the OP as I'm a bit late to the party here (wish I could have helped sooner, but I didn't run into the problem until today, or this stack overflow answer until I was figuring out a solution.)

The Visual C++ 2003 runtime was not available as a seperate download because it was included with the .NET 1.1 runtime.

If you install the .NET 1.1 runtime you will get msvcr71.dll installed, and in addition added to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.

The .NET 1.1 runtime is available here: http://www.microsoft.com/downloads/en/details.aspx?familyid=262d25e3-f589-4842-8157-034d1e7cf3a3&displaylang=en (23.1 MB)

If you are looking for a file that ends with a "P" such as msvcp71.dll, this indicates that your file was compiled against a C++ runtime (as opposed to a C runtime), in some situations I noticed these files were only installed when I installed the full SDK. If you need one of these files, you may need to install the full .NET 1.1 SDK as well, which is available here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d (106.2 MB)

After installing the SDK I now have both msvcr71.dll and msvcp71.dll in my System32 folder, and the application I'm trying to run (boomerang c++ decompiler) works fine without any missing DLL errors.

Also on a side note: be VERY aware of the difference between a Hotfix Update and a Regular Update. As noted in the linked KB932298 download (linked below by Storm): "Please be aware this Hotfix has not gone through full Microsoft product regression testing nor has it been tested in combination with other Hotfixes."

Hotfixes are NOT meant for general users, but rather users who are facing a very specific problem. As described in the article only install that Hotfix if you are have having specific daylight savings time issues with the rules that changed in 2007. -- Likely this was a pre-release for customers who "just couldn't wait" for the official update (probably for some business critical application) -- for regular users Windows Update should be all you need.

Thanks, and I hope this helps others who run into this issue!

How to view query error in PDO PHP

You need to set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION.
And since you expect the exception to be thrown by the prepare() method you should disable the PDO::ATTR_EMULATE_PREPARES* feature. Otherwise the MySQL server doesn't "see" the statement until it's executed.

<?php
try {
    $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);


    $pdo->prepare('INSERT INTO DoesNotExist (x) VALUES (?)');
}
catch(Exception $e) {
    echo 'Exception -> ';
    var_dump($e->getMessage());
}

prints (in my case)

Exception -> string(91) "SQLSTATE[42S02]: Base table or view not found: 
1146 Table 'test.doesnotexist' doesn't exist"

see http://wezfurlong.org/blog/2006/apr/using-pdo-mysql/
EMULATE_PREPARES=true seems to be the default setting for the pdo_mysql driver right now. The query cache thing has been fixed/change since then and with the mysqlnd driver I hadn't problems with EMULATE_PREPARES=false (though I'm only a php hobbyist, don't take my word on it...)

*) and then there's PDO::MYSQL_ATTR_DIRECT_QUERY - I must admit that I don't understand the interaction of those two attributes (yet?), so I set them both, like

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::ATTR_EMULATE_PREPARES=>false,
    PDO::MYSQL_ATTR_DIRECT_QUERY=>false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));

Determine project root from a running node.js application

the easiest way to get the global root (assuming you use NPM to run your node.js app 'npm start', etc)

var appRoot = process.env.PWD;

If you want to cross-verify the above

Say you want to cross-check process.env.PWD with the settings of you node.js application. if you want some runtime tests to check the validity of process.env.PWD, you can cross-check it with this code (that I wrote which seems to work well). You can cross-check the name of the last folder in appRoot with the npm_package_name in your package.json file, for example:

    var path = require('path');

    var globalRoot = __dirname; //(you may have to do some substring processing if the first script you run is not in the project root, since __dirname refers to the directory that the file is in for which __dirname is called in.)

    //compare the last directory in the globalRoot path to the name of the project in your package.json file
    var folders = globalRoot.split(path.sep);
    var packageName = folders[folders.length-1];
    var pwd = process.env.PWD;
    var npmPackageName = process.env.npm_package_name;
    if(packageName !== npmPackageName){
        throw new Error('Failed check for runtime string equality between globalRoot-bottommost directory and npm_package_name.');
    }
    if(globalRoot !== pwd){
        throw new Error('Failed check for runtime string equality between globalRoot and process.env.PWD.');
    }

you can also use this NPM module: require('app-root-path') which works very well for this purpose

Do you know the Maven profile for mvnrepository.com?

Once you've found your jar through mvnrepository.com, hover the "download (JAR)" link, and you'll see the link to the repository which contains your jar (you can probably Right clic and "Copy link URL" to get the URL, what ever your browser is).

Then, you have to add this repository to the repositories used by your project, in your pom.xml :

<project>
  ...
  <repositories>
    <repository>
      <id>my-alternate-repository</id>
      <url>http://myrepo.net/repo</url>
    </repository>
  </repositories>
  ...
</project>

EDIT : now MVNrepository.com has evolved : You can find the link to the repository in the "Repositories" section :

License

Categories

HomePage

Date

Files

Repositories

UML class diagram enum

Typically you model the enum itself as a class with the enum stereotype

jQuery onclick toggle class name

It can even be made dependent to another attribute changes. like this:

$('.classA').toggleClass('classB', $('input').prop('disabled'));

In this case, classB are added each time the input is disabled

How to properly create composite primary keys - MYSQL

I would not make the primary key of the "info" table a composite of the two values from other tables.

Others can articulate the reasons better, but it feels wrong to have a column that is really made up of two pieces of information. What if you want to sort on the ID from the second table for some reason? What if you want to count the number of times a value from either table is present?

I would always keep these as two distinct columns. You could use a two-column primay key in mysql ...PRIMARY KEY(id_a, id_b)... but I prefer using a two-column unique index, and having an auto-increment primary key field.

How to get the next auto-increment id in mysql

What do you need the next incremental ID for?

MySQL only allows one auto-increment field per table and it must also be the primary key to guarantee uniqueness.

Note that when you get the next insert ID it may not be available when you use it since the value you have is only within the scope of that transaction. Therefore depending on the load on your database, that value may be already used by the time the next request comes in.

I would suggest that you review your design to ensure that you do not need to know which auto-increment value to assign next

Finding all objects that have a given property inside a collection

Solutions based on predicates, filters and custom iterators/comparators are nice, but they don't provide analogue with database index. For instance: I would like to search collection of cats different ways: by sex and age and by age, so it looks like two indexes: 1) [sex, age] 2) [age]. Values, accessed by that indexes could be hashed, to implement fast lookup, without iterating the whole collection. Is anywhere there such solution?

Bootstrap 3 Carousel Not Working

Well, Bootstrap Carousel has various parameters to control.

i.e.

Interval: Specifies the delay (in milliseconds) between each slide.

pause: Pauses the carousel from going through the next slide when the mouse pointer enters the carousel, and resumes the sliding when the mouse pointer leaves the carousel.

wrap: Specifies whether the carousel should go through all slides continuously, or stop at the last slide

For your reference:

enter image description here

Fore more details please click here...

Hope this will help you :)

Note: This is for the further help.. I mean how can you customise or change default behaviour once carousel is loaded.

How add unique key to existing table (with non uniques rows)

Either create an auto-increment id or a UNIQUE id and add it to the natural key you are talking about with the 4 fields. this will make every row in the table unique...

What is (x & 1) and (x >>= 1)?

(n & 1) will check if 'n' is odd or even, this is similar to (n%2).

  1. In case 'n' is odd (n & 1) will return true/1;

  2. Else it will return back false/0;


The '>>' in (n>>=1) is a bitwise operator called "Right shift", this operator will modify the value of 'n', the formula is:

(n >>= m) => (n = n>>m) => (n = n/2^m)

Go through GeeksforGeek's article on "Bitwise Operator's", recommended!

Origin null is not allowed by Access-Control-Allow-Origin

I was looking for an solution to make an XHR request to a server from a local html file and found a solution using Chrome and PHP. (no Jquery)

Javascripts:

var x = new XMLHttpRequest(); 
if(x) x.onreadystatechange=function(){ 
    if (x.readyState === 4 && x.status===200){
        console.log(x.responseText); //Success
    }else{ 
        console.log(x); //Failed
    }
};
x.open(GET, 'http://example.com/', true);
x.withCredentials = true;
x.send();

My Chrome's request header Origin: null

My PHP response header (Note that 'null' is a string). HTTP_REFERER allow cross-origin from a remote server to another.

header('Access-Control-Allow-Origin: '.(trim($_SERVER['HTTP_REFERER'],'/')?:'null'),true);
header('Access-Control-Allow-Credentials:true',true);

I was able to successfully connect to my server. You can disregards the Credentials headers, but this works for me with Apache's AuthType Basic enabled

I tested compatibility with FF and Opera, It works in many cases such as:

From a VM LAN IP (192.168.0.x) back to the VM'S WAN (public) IP:port
From a VM LAN IP back to a remote server domain name.
From a local .HTML file to the VM LAN IP and/or VM WAN IP:port,
From a local .HTML file to a remote server domain name.
And so on.

How to stop IIS asking authentication for default website on localhost

It could be because of couple of Browser settings. Try with these options checked..

Tools > Internet Options > Advanced > Enable Integrated Windows Authentication (works with Integrated Windows Authentication set on IIS)

Tools > Internet Options> Security > Local Intranet > Custom Level > Automatic Logon

Worst case, try adding localhost to the Trusted sites.

If you are in a network, you can also try debugging by getting a network trace. Could be because of some proxy trying to authenticate.

How to set-up a favicon?

This method is recommended

<link rel="icon" 
  type="image/png" 
  href="/somewhere/myicon.png" />

Indexing vectors and arrays with +:

Description and examples can be found in IEEE Std 1800-2017 § 11.5.1 "Vector bit-select and part-select addressing". First IEEE appearance is IEEE 1364-2001 (Verilog) § 4.2.1 "Vector bit-select and part-select addressing". Here is an direct example from the LRM:

logic [31: 0] a_vect;
logic [0 :31] b_vect;
logic [63: 0] dword;
integer sel;
a_vect[ 0 +: 8] // == a_vect[ 7 : 0]
a_vect[15 -: 8] // == a_vect[15 : 8]
b_vect[ 0 +: 8] // == b_vect[0 : 7]
b_vect[15 -: 8] // == b_vect[8 :15]
dword[8*sel +: 8] // variable part-select with fixed width

If sel is 0 then dword[8*(0) +: 8] == dword[7:0]
If sel is 7 then dword[8*(7) +: 8] == dword[63:56]

The value to the left always the starting index. The number to the right is the width and must be a positive constant. the + and - indicates to select the bits of a higher or lower index value then the starting index.

Assuming address is in little endian ([msb:lsb]) format, then if(address[2*pointer+:2]) is the equivalent of if({address[2*pointer+1],address[2*pointer]})

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

How to make a Python script run like a service or daemon in Linux

to creating some thing that is running like service you can use this thing :

The first thing that you must do is installing the Cement framework: Cement frame work is a CLI frame work that you can deploy your application on it.

command line interface of the app :

interface.py

 from cement.core.foundation import CementApp
 from cement.core.controller import CementBaseController, expose
 from YourApp import yourApp

 class Meta:
    label = 'base'
    description = "your application description"
    arguments = [
        (['-r' , '--run'],
          dict(action='store_true', help='Run your application')),
        (['-v', '--version'],
          dict(action='version', version="Your app version")),
        ]
        (['-s', '--stop'],
          dict(action='store_true', help="Stop your application")),
        ]

    @expose(hide=True)
    def default(self):
        if self.app.pargs.run:
            #Start to running the your app from there !
            YourApp.yourApp()
        if self.app.pargs.stop:
            #Stop your application
            YourApp.yourApp.stop()

 class App(CementApp):
       class Meta:
       label = 'Uptime'
       base_controller = 'base'
       handlers = [MyBaseController]

 with App() as app:
       app.run()

YourApp.py class:

 import threading

 class yourApp:
     def __init__:
        self.loger = log_exception.exception_loger()
        thread = threading.Thread(target=self.start, args=())
        thread.daemon = True
        thread.start()

     def start(self):
        #Do every thing you want
        pass
     def stop(self):
        #Do some things to stop your application

Keep in mind that your app must run on a thread to be daemon

To run the app just do this in command line

python interface.py --help

Why is textarea filled with mysterious white spaces?

I know its late but may help others.

use this in when document indentation is required.

$('document').ready(function()
{
    $('textarea').each(function(){
            $(this).val($(this).val().trim());
        }
    );
});

same question

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

If you want to disable the clickable, you can also add inline this in html

style="cursor: not-allowed;"

Flask raises TemplateNotFound error even though template file exists

Check that:

  1. the template file has the right name
  2. the template file is in a subdirectory called templates
  3. the name you pass to render_template is relative to the template directory (index.html would be directly in the templates directory, auth/login.html would be under the auth directory in the templates directory.)
  4. you either do not have a subdirectory with the same name as your app, or the templates directory is inside that subdir.

If that doesn't work, turn on debugging (app.debug = True) which might help figure out what's wrong.

How do I handle ImeOptions' done button click?

Thanks to chikka.anddev and Alex Cohn in Kotlin it is:

text.setOnEditorActionListener { v, actionId, event ->
    if (actionId == EditorInfo.IME_ACTION_DONE ||
        event?.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER) {
        doSomething()
        true
    } else {
        false
    }
}

Here I check for Enter key, because it returns EditorInfo.IME_NULL instead of IME_ACTION_DONE.

See also Android imeOptions="actionDone" not working. Add android:singleLine="true" in the EditText.

How to use greater than operator with date?

I have tried but above not working after research found below the solution.

SELECT * FROM my_table where DATE(start_date) > '2011-01-01';

Ref

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

AWS : The config profile (MyName) could not be found

Use as follows

[profilename]
region=us-east-1
output=text

Example cmd

aws --profile myname CMD opts

how to disable DIV element and everything inside

You can't use "disable" to disable a click event. I don't know how or if it worked in IE6-9, but it didn't work on Chrome, and it shouldn't work on IE10 like that.

You can disable the onclick event, too, by attaching an event that cancels:

;(function () {
    function cancel () { return false; };
    document.getElementById("test").disabled = true;
    var nodes = document.getElementById("test").getElementsByTagName('*');
    console.log(nodes);
    for (var i = 0; i < nodes.length; i++) {
        nodes[i].setAttribute('disabled', true);
        nodes[i].onclick = cancel;
    }
}());

Furthermore, setting "disabled" on a node directly doesn't necessarily add the attribute- using setAttribute does.

http://jsfiddle.net/2fPZu/

How to extend / inherit components?

As far as I know component inheritance has not been implemented yet in Angular 2 and I'm not sure if they have plans to, however since Angular 2 is using typescript (if you've decided to go that route) you can use class inheritance by doing class MyClass extends OtherClass { ... }. For component inheritance I'd suggest getting involved with the Angular 2 project by going to https://github.com/angular/angular/issues and submitting a feature request!

How to set response header in JAX-RS so that user sees download popup for Excel?

@Context ServletContext ctx;
@Context private HttpServletResponse response;

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/download/{filename}")
public StreamingOutput download(@PathParam("filename") String fileName) throws Exception {
    final File file = new File(ctx.getInitParameter("file_save_directory") + "/", fileName);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() + "\"");
    return new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException,
                WebApplicationException {
            Utils.writeBuffer(new BufferedInputStream(new FileInputStream(file)), new BufferedOutputStream(output));
        }
    };
}

git cherry-pick says "...38c74d is a merge but no -m option was given"

-m means the parent number.

From the git doc:

Usually you cannot cherry-pick a merge because you do not know which side of the merge should be considered the mainline. This option specifies the parent number (starting from 1) of the mainline and allows cherry-pick to replay the change relative to the specified parent.

For example, if your commit tree is like below:

- A - D - E - F -   master
   \     /
    B - C           branch one

then git cherry-pick E will produce the issue you faced.

git cherry-pick E -m 1 means using D-E, while git cherry-pick E -m 2 means using B-C-E.

Embedding SVG into ReactJS

Update 2016-05-27

As of React v15, support for SVG in React is (close to?) 100% parity with current browser support for SVG (source). You just need to apply some syntax transformations to make it JSX compatible, like you already have to do for HTML (class ? className, style="color: purple" ? style={{color: 'purple'}}). For any namespaced (colon-separated) attribute, e.g. xlink:href, remove the : and capitalize the second part of the attribute, e.g. xlinkHref. Here’s an example of an svg with <defs>, <use>, and inline styles:

function SvgWithXlink (props) {
    return (
        <svg
            width="100%"
            height="100%"
            xmlns="http://www.w3.org/2000/svg"
            xmlnsXlink="http://www.w3.org/1999/xlink"
        >
            <style>
                { `.classA { fill:${props.fill} }` }
            </style>
            <defs>
                <g id="Port">
                    <circle style={{fill:'inherit'}} r="10"/>
                </g>
            </defs>

            <text y="15">black</text>
            <use x="70" y="10" xlinkHref="#Port" />
            <text y="35">{ props.fill }</text>
            <use x="70" y="30" xlinkHref="#Port" className="classA"/>
            <text y="55">blue</text>
            <use x="0" y="50" xlinkHref="#Port" style={{fill:'blue'}}/>
        </svg>
    );
}

Working codepen demo

For more details on specific support, check the docs’ list of supported SVG attributes. And here’s the (now closed) GitHub issue that tracked support for namespaced SVG attributes.


Previous answer

You can do a simple SVG embed without having to use dangerouslySetInnerHTML by just stripping the namespace attributes. For example, this works:

        render: function() {
            return (
                <svg viewBox="0 0 120 120">
                    <circle cx="60" cy="60" r="50"/>
                </svg>
            );
        }

At which point you can think about adding props like fill, or whatever else might be useful to configure.

Compiler error: "class, interface, or enum expected"

You miss the class declaration.

public class DerivativeQuiz{
   public static void derivativeQuiz(String args[]){ ... }
}

What's the difference between align-content and align-items?

The main difference is when the height of the elements are not the same! Then you can see how in the row, they are all center\end\start

Jquery-How to grey out the background while showing the loading icon over it

I reworked the example you provided in the js fiddle : http://jsfiddle.net/zravs3hp/

Step 1 :

I renamed your container div to overlay, as semantically this div is not a container, but an overlay. I also placed the loader div as a child of this overlay div.

The resulting html is :

<div class="overlay">
    <div id="loading-img"></div>
</div>


<div class="content">
    <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea velit provident sint aliquid eos omnis aperiam officia architecto error incidunt nemo obcaecati adipisci doloremque dicta neque placeat natus beatae cupiditate minima ipsam quaerat explicabo non reiciendis qui sit. ...</div>
    <button id="button">Submit</button>
</div>

The css of the overlay is the following

.overlay {
    background: #e9e9e9;  <- I left your 'gray' background
    display: none;        <- Not displayed by default
    position: absolute;   <- This and the following properties will
    top: 0;                  make the overlay, the element will expand
    right: 0;                so as to cover the whole body of the page
    bottom: 0;
    left: 0;
    opacity: 0.5;
}

Step 2 :

I added some dummy text so as to have something to overlay.

Step 3 :

Then, in the click handler we just need to show the overlay :

$("#button").click(function () {
    $(".overlay").show();
});

Allow access permission to write in Program Files of Windows 7

It would be neater to create a folder named "c:\programs writable\" and put you app below that one. That way a jungle of low c-folders can be avoided.

The underlying trade-off is security versus ease-of-use. If you know what you are doing you want to be god on you own pc. If you must maintain healthy systems for your local anarchistic society, you may want to add some security.

How do I use Wget to download all images into a single folder, from a URL?

wget -nd -r -l 2 -A jpg,jpeg,png,gif http://t.co
  • -nd: no directories (save all files to the current directory; -P directory changes the target directory)
  • -r -l 2: recursive level 2
  • -A: accepted extensions
wget -nd -H -p -A jpg,jpeg,png,gif -e robots=off example.tumblr.com/page/{1..2}
  • -H: span hosts (wget doesn't download files from different domains or subdomains by default)
  • -p: page requisites (includes resources like images on each page)
  • -e robots=off: execute command robotos=off as if it was part of .wgetrc file. This turns off the robot exclusion which means you ignore robots.txt and the robot meta tags (you should know the implications this comes with, take care).

Example: Get all .jpg files from an exemplary directory listing:

$ wget -nd -r -l 1 -A jpg http://example.com/listing/

Angularjs autocomplete from $http

I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.

Here's the demo: http://justgoscha.github.io/allmighty-autocomplete/ And here the documentation and repository: https://github.com/JustGoscha/allmighty-autocomplete

So basically you have to return a promise when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $qservice/directive/controller where you issue your HTTP Request.

Example:

function getMyHttpData(){
  var deferred = $q.defer();
  $http.jsonp(request).success(function(data){
    // the promise gets resolved with the data from HTTP
    deferred.resolve(data);
  });
  // return the promise
  return deferred.promise;
}

I hope this helps.

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

Angular directives - when and how to use compile, controller, pre-link and post-link

What else happens between these function calls?

The various directive functions are executed from within two other angular functions called $compile (where the directive's compile is executed) and an internal function called nodeLinkFn (where the directive's controller, preLink and postLink are executed). Various things happen within the angular function before and after the directive functions are called. Perhaps most notably is the child recursion. The following simplified illustration shows key steps within the compile and link phases:

An illustration showing Angular compile and link phases

To demonstrate the these steps, let's use the following HTML markup:

<div ng-repeat="i in [0,1,2]">
    <my-element>
        <div>Inner content</div>
    </my-element>
</div>

With the following directive:

myApp.directive( 'myElement', function() {
    return {
        restrict:   'EA',
        transclude: true,
        template:   '<div>{{label}}<div ng-transclude></div></div>'
    }
});

Compile

The compile API looks like so:

compile: function compile( tElement, tAttributes ) { ... }

Often the parameters are prefixed with t to signify the elements and attributes provided are those of the source template, rather than that of the instance.

Prior to the call to compile transcluded content (if any) is removed, and the template is applied to the markup. Thus, the element provided to the compile function will look like so:

<my-element>
    <div>
        "{{label}}"
        <div ng-transclude></div>
    </div>
</my-element>

Notice that the transcluded content is not re-inserted at this point.

Following the call to the directive's .compile, Angular will traverse all child elements, including those that may have just been introduced by the directive (the template elements, for instance).

Instance creation

In our case, three instances of the source template above will be created (by ng-repeat). Thus, the following sequence will execute three times, once per instance.

Controller

The controller API involves:

controller: function( $scope, $element, $attrs, $transclude ) { ... }

Entering the link phase, the link function returned via $compile is now provided with a scope.

First, the link function create a child scope (scope: true) or an isolated scope (scope: {...}) if requested.

The controller is then executed, provided with the scope of the instance element.

Pre-link

The pre-link API looks like so:

function preLink( scope, element, attributes, controller ) { ... }

Virtually nothing happens between the call to the directive's .controller and the .preLink function. Angular still provide recommendation as to how each should be used.

Following the .preLink call, the link function will traverse each child element - calling the correct link function and attaching to it the current scope (which serves as the parent scope for child elements).

Post-link

The post-link API is similar to that of the pre-link function:

function postLink( scope, element, attributes, controller ) { ... }

Perhaps worth noticing that once a directive's .postLink function is called, the link process of all its children elements has completed, including all the children's .postLink functions.

This means that by the time .postLink is called, the children are 'live' are ready. This includes:

  • data binding
  • transclusion applied
  • scope attached

The template at this stage will thus look like so:

<my-element>
    <div class="ng-binding">
        "{{label}}"
        <div ng-transclude>                
            <div class="ng-scope">Inner content</div>
        </div>
    </div>
</my-element>

How to parse JSON in Kotlin?

There is no question that the future of parsing in Kotlin will be with kotlinx.serialization. It is part of Kotlin libraries. Version kotlinx.serialization 1.0 is finally released

https://github.com/Kotlin/kotlinx.serialization

import kotlinx.serialization.*
import kotlinx.serialization.json.JSON

@Serializable
data class MyModel(val a: Int, @Optional val b: String = "42")

fun main(args: Array<String>) {

    // serializing objects
    val jsonData = JSON.stringify(MyModel.serializer(), MyModel(42))
    println(jsonData) // {"a": 42, "b": "42"}
    
    // serializing lists
    val jsonList = JSON.stringify(MyModel.serializer().list, listOf(MyModel(42)))
    println(jsonList) // [{"a": 42, "b": "42"}]

    // parsing data back
    val obj = JSON.parse(MyModel.serializer(), """{"a":42}""")
    println(obj) // MyModel(a=42, b="42")
}

syntaxerror: "unexpected character after line continuation character in python" math

As the others already mentioned: the division operator is / rather than **. If you wanna print the ** character within a string you have to escape it:

print("foo \\")
# will print: foo \

I think to print the string you wanted I think you gonna need this code:

print("Length between sides: " + str((length*length)*2.6) + " \\ 1.5 = " + str(((length*length)*2.6)/1.5) + " Units")

And this one is a more readable version of the above (using the format method):

message = "Length between sides: {0} \\ 1.5 = {1} Units"
val1 = (length * length) * 2.6
val2 = ((length * length) * 2.6) / 1.5
print(message.format(val1, val2))

Listview Scroll to the end of the list after updating the list

Supposing you know when the list data has changed, you can manually tell the list to scroll to the bottom by setting the list selection to the last row. Something like:

private void scrollMyListViewToBottom() {
    myListView.post(new Runnable() {
        @Override
        public void run() {
            // Select the last row so it will scroll into view...
            myListView.setSelection(myListAdapter.getCount() - 1);
        }
    });
}

How can we run a test method with multiple parameters in MSTest?

This feature is in pre-release now and works with Visual Studio 2015.

For example:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    [DataRow(1, 2, 2)]
    [DataRow(2, 3, 5)]
    [DataRow(3, 5, 8)]
    public void AdditionTest(int a, int b, int result)
    {
        Assert.AreEqual(result, a + b);
    }
}

Converting a String array into an int Array in java

public static int[] strArrayToIntArray(String[] a){
    int[] b = new int[a.length];
    for (int i = 0; i < a.length; i++) {
        b[i] = Integer.parseInt(a[i]);
    }

    return b;
}

This is a simple function, that should help you. You can use him like this:

int[] arr = strArrayToIntArray(/*YOUR STR ARRAY*/);

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

How can I run an EXE program from a Windows Service using C#?

Top answer with most upvotes isn't wrong but still the opposite of what I would post. I say it will totally work to start an exe file and you can do this in the context of any user. Logically you just can't have any user interface or ask for user input...

Here is my advice:

  1. Create a simple Console Application that does what your service should do right on start without user interaction. I really recommend not using the Windows Service project type especially because you (currently) can't using .NET Core.
  2. Add code to start your exe you want to call from service

Example to start e.g. plink.exe. You could even listen to the output:

var psi = new ProcessStartInfo()
{
    FileName = "./Client/plink.exe", //path to your *.exe
    Arguments = "-telnet -P 23 127.0.0.1 -l myUsername -raw", //arguments
    RedirectStandardError = true,
    RedirectStandardOutput = true,
    RedirectStandardInput = true,
    UseShellExecute = false,
    CreateNoWindow = true //no window, you can't show it anyway
};

var p = Process.Start(psi);
  1. Use NSSM (Non-Sucking Service Manager) to register that Console Application as service. NSSM can be controlled via command line and can show an UI to configure the service or you configure it via command line. You can run the service in the context of any user if you know the login data of that user.

I took LocalSystem account which is default and more than Local Service. It worked fine without having to enter login information of a specific user. I didn't even tick the checkbox "Allow service to interact with desktop" which you could if you need higher permissions.

Option to allow service to interact with desktop

Lastly I just want to say how funny it is that the top answer says quite the opposite of my answer and still both of us are right it's just how you interpret the question :-D. If you now say but you can't with the windows service project type - You CAN but I had this before and installation was sketchy and it was maybe kind of an unintentional hack until I found NSSM.

Understanding Spring @Autowired usage

Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.

Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :

<beans:bean id="movieFinder" class="com.movies.MovieFinder" />

or if the MovieFinder class has a constructor with a primitive value, then you could something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg value="100" />
</beans:bean>

or if the MovieFinder class has a constructor expecting another class, then you could do something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg ref="otherBeanRef" />
</beans:bean>

...where 'otherBeanRef' is another bean that has a reference to the expected class.

SQL query to group by day

For oracle you can

group by trunc(created);

as this truncates the created datetime to the previous midnight.

Another option is to

group by to_char(created, 'DD.MM.YYYY');

which achieves the same result, but may be slower as it requires a type conversion.

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

When using moment.js, use:

var tz = moment.tz.guess();

It will return an IANA time zone identifier, such as America/Los_Angeles for the US Pacific time zone.

It is documented here.

Internally, it first tries to get the time zone from the browser using the following call:

Intl.DateTimeFormat().resolvedOptions().timeZone

If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.

If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.

How to programmatically send SMS on the iPhone?

[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"sms:number"]] 

This would be the best and short way to do it.

Warning: #1265 Data truncated for column 'pdd' at row 1

As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)

EDIT 1:

Following your comment, I run a test table:

mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)

Insertion:

mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)

EDIT 2:

So, aparently you want to insert a NULL value to pdd field as your comment states ? You can do that in 2 ways like this:

Method 1:

mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)

Method 2:

mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)

EDIT 3:

You failed to change the default value of pdd field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)

mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3  Duplicates: 0  Warnings: 1

jQuery: Adding two attributes via the .attr(); method

Use curly brackets and put all the attributes you want to add inside

Example:

$('#objId').attr({
    target: 'nw',
    title: 'Opens in a new window'
});

Multiple "order by" in LINQ

This should work for you:

var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name)

What is the correct syntax for 'else if'?

def function(a):
    if a == '1':
        print ('1a')
    elif a == '2':
        print ('2a')
    else:
        print ('3a')

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

I had to turn PAE/NX off and then back to on...voila !!

How to select unique records by SQL

There are 4 methods you can use:

  1. DISTINCT
  2. GROUP BY
  3. Subquery
  4. Common Table Expression (CTE) with ROW_NUMBER()

Consider the following sample TABLE with test data:

/** Create test table */
CREATE TEMPORARY TABLE dupes(word text, num int, id int);

/** Add test data with duplicates */
INSERT INTO dupes(word, num, id)
VALUES ('aaa', 100, 1)
      ,('bbb', 200, 2)
      ,('ccc', 300, 3)
      ,('bbb', 400, 4)
      ,('bbb', 200, 5)     -- duplicate
      ,('ccc', 300, 6)     -- duplicate
      ,('ddd', 400, 7)
      ,('bbb', 400, 8)     -- duplicate
      ,('aaa', 100, 9)     -- duplicate
      ,('ccc', 300, 10);   -- duplicate

Option 1: SELECT DISTINCT

This is the most simple and straight forward, but also the most limited way:

SELECT DISTINCT word, num 
FROM    dupes
ORDER BY word, num;

/*
word|num|
----|---|
aaa |100|
bbb |200|
bbb |400|
ccc |300|
ddd |400|
*/

Option 2: GROUP BY

Grouping allows you to add aggregated data, like the min(id), max(id), count(*), etc:

SELECT  word, num, min(id), max(id), count(*)
FROM    dupes
GROUP BY word, num
ORDER BY word, num;

/*
word|num|min|max|count|
----|---|---|---|-----|
aaa |100|  1|  9|    2|
bbb |200|  2|  5|    2|
bbb |400|  4|  8|    2|
ccc |300|  3| 10|    3|
ddd |400|  7|  7|    1|
*/

Option 3: Subquery

Using a subquery, you can first identify the duplicate rows to ignore, and then filter them out in the outer query with the WHERE NOT IN (subquery) construct:

/** Find the higher id values of duplicates, distinct only added for clarity */
    SELECT  distinct d2.id
    FROM    dupes d1
        INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
    WHERE d2.id > d1.id

/*
id|
--|
 5|
 6|
 8|
 9|
10|
*/

/** Use the previous query in a subquery to exclude the dupliates with higher id values */
SELECT  *
FROM    dupes
WHERE   id NOT IN (
    SELECT  d2.id
    FROM    dupes d1
        INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
    WHERE d2.id > d1.id
)
ORDER BY word, num;

/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/

Option 4: Common Table Expression with ROW_NUMBER()

In the Common Table Expression (CTE), select the ROW_NUMBER(), partitioned by the group column and ordered in the desired order. Then SELECT only the records that have ROW_NUMBER() = 1:

WITH CTE AS (
    SELECT  *
           ,row_number() OVER(PARTITION BY word, num ORDER BY id) AS row_num
    FROM    dupes
)
SELECT  word, num, id 
FROM    cte
WHERE   row_num = 1
ORDER BY word, num;

/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/

Is there a link to the "latest" jQuery library on Google APIs?

Up until jQuery 1.11.1, you could use the following URLs to get the latest version of jQuery:

For example:

<script src="https://code.jquery.com/jquery-latest.min.js"></script>

However, since jQuery 1.11.1, both jQuery and Google stopped updating these URL's; they will forever be fixed at 1.11.1. There is no supported alternative URL to use. For an explanation of why this is the case, see this blog post; Don't use jquery-latest.js.

Both hosts support https as well as http, so change the protocol as you see fit (or use a protocol relative URI)

See also: https://developers.google.com/speed/libraries/devguide

Html- how to disable <a href>?

<script>
    $(document).ready(function(){
        $('#connectBtn').click(function(e){
            e.preventDefault();
        })
    });
</script>

This will prevent the default action.

How can I remove the extension of a filename in a shell script?

You can also use parameter expansion:

$ filename=foo.txt
$ echo "${filename%.*}"
foo

Just be aware that if there is no file extension, it will look further back for dots, e.g.

  • If the filename only starts with a dot (e.g. .bashrc) it will remove the whole filename.
  • If there's a dot only in the path (e.g. path.to/myfile or ./myfile), then it will trim inside the path.

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

Is there a way to reset IIS 7.5 to factory settings?

This link has some useful suggestions: http://forums.iis.net/t/1085990.aspx

It depends on where you have the config settings stored. By default IIS7 will have all of it's configuration settings stored in a file called "ApplicationHost.Config". If you have delegation configured then you will see site/app related config settings getting written to web.config file for the site/app. With IIS7 on vista there is an automatica backup file for master configuration is created. This file is called "application.config.backup" and it resides inside "C:\Windows\System32\inetsrv\config" You could rename this file to applicationHost.config and replace it with the applicationHost.config inside the config folder. IIS7 on server release will have better configuration back up story, but for now I recommend using APPCMD to backup/restore your configuration on regualr basis. Example: APPCMD ADD BACK "MYBACKUP" Another option (really the last option) is to uninstall/reinstall IIS along with WPAS (Windows Process activation service).

git am error: "patch does not apply"

I had this error, was able to overcome it by using : patch -p1 < example.patch

I took it from here: https://www.drupal.org/node/1129120

Axios get access to response header fields

For Spring Boot 2 if you don't want to use global CORS configuration, you can do it by method or class/controller level using @CrossOrigin adnotation with exposedHeaders atribute.

For example, to add header authorization for YourController methods:

@CrossOrigin(exposedHeaders = "authorization")
@RestController
public class YourController {
    ...
}

How to update/refresh specific item in RecyclerView

I got to solve this issue by catching the position of the item that needed to be modified and then in the adapter call

public void refreshBlockOverlay(int position) {
    notifyItemChanged(position);
}

, this will call onBindViewHolder(ViewHolder holder, int position) for this specific item at this specific position.

Npm install cannot find module 'semver'

I was getting same issue but solve this issue with an below command.

npm install semver

Center align a column in twitter bootstrap

I tried the approaches given above, but these methods fail when dynamically the height of the content in one of the cols increases, it basically pushes the other cols down.

for me the basic table layout solution worked.

// Apply this to the enclosing row
.row-centered {
  text-align: center;
  display: table-row;
}
// Apply this to the cols within the row
.col-centered {
  display: table-cell;
  float: none;
  vertical-align: top;
}

How to get a barplot with several variables side by side grouped by a factor

You can use aggregate to calculate the means:

means<-aggregate(df,by=list(df$gender),mean)
Group.1      tea     coke     beer    water gender
1       1 87.70171 27.24834 24.27099 37.24007      1
2       2 24.73330 25.27344 25.64657 24.34669      2

Get rid of the Group.1 column

means<-means[,2:length(means)]

Then you have reformat the data to be in long format:

library(reshape2)
means.long<-melt(means,id.vars="gender")
  gender variable    value
1      1      tea 87.70171
2      2      tea 24.73330
3      1     coke 27.24834
4      2     coke 25.27344
5      1     beer 24.27099
6      2     beer 25.64657
7      1    water 37.24007
8      2    water 24.34669

Finally, you can use ggplot2 to create your plot:

library(ggplot2)
ggplot(means.long,aes(x=variable,y=value,fill=factor(gender)))+
  geom_bar(stat="identity",position="dodge")+
  scale_fill_discrete(name="Gender",
                      breaks=c(1, 2),
                      labels=c("Male", "Female"))+
  xlab("Beverage")+ylab("Mean Percentage")

enter image description here

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

I had met a similar problem, after i add a scope property of servlet dependency in pom.xml

 <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

Then it was ok . maybe that will help you.

Using multiple parameters in URL in express

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
    var data = {
        "fruit": {
            "apple": req.params.fruitName,
            "color": req.params.fruitColor
        }
    }; 

    send.json(data);
});

If that doesn't work, try using console.log(req.params) to see what it is giving you.

Sorting objects by property values

javascript has the sort function which can take another function as parameter - that second function is used to compare two elements.

Example:

cars = [

    {
        name: "Honda",
        speed: 80
    },

    {
        name: "BMW",
        speed: 180
    },

    {
        name: "Trabi",
        speed: 40
    },

    {
        name: "Ferrari",
        speed: 200
    }
]


cars.sort(function(a, b) { 
    return a.speed - b.speed;
})

for(var i in cars)
    document.writeln(cars[i].name) // Trabi Honda BMW Ferrari 

ok, from your comment i see that you're using the word 'sort' in a wrong sense. In programming "sort" means "put things in a certain order", not "arrange things in groups". The latter is much simpler - this is just how you "sort" things in the real world

  • make two empty arrays ("boxes")
  • for each object in your list, check if it matches the criteria
  • if yes, put it in the first "box"
  • if no, put it in the second "box"

Export MySQL database using PHP only

I would Suggest that you do the folllowing,

_x000D_
_x000D_
<?php_x000D_
_x000D_
$con = mysqli_connect('HostName', 'UserName', 'Password', 'DatabaseName');_x000D_
_x000D_
_x000D_
$tables = array();_x000D_
_x000D_
$result = mysqli_query($con,"SHOW TABLES");_x000D_
while ($row = mysqli_fetch_row($result)) {_x000D_
 $tables[] = $row[0];_x000D_
}_x000D_
_x000D_
$return = '';_x000D_
_x000D_
foreach ($tables as $table) {_x000D_
 $result = mysqli_query($con, "SELECT * FROM ".$table);_x000D_
 $num_fields = mysqli_num_fields($result);_x000D_
_x000D_
 $return .= 'DROP TABLE '.$table.';';_x000D_
 $row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE '.$table));_x000D_
 $return .= "\n\n".$row2[1].";\n\n";_x000D_
_x000D_
 for ($i=0; $i < $num_fields; $i++) { _x000D_
  while ($row = mysqli_fetch_row($result)) {_x000D_
   $return .= 'INSERT INTO '.$table.' VALUES(';_x000D_
   for ($j=0; $j < $num_fields; $j++) { _x000D_
    $row[$j] = addslashes($row[$j]);_x000D_
    if (isset($row[$j])) {_x000D_
     $return .= '"'.$row[$j].'"';} else { $return .= '""';}_x000D_
     if($j<$num_fields-1){ $return .= ','; }_x000D_
    }_x000D_
    $return .= ");\n";_x000D_
   }_x000D_
  }_x000D_
  $return .= "\n\n\n";_x000D_
 _x000D_
}_x000D_
_x000D_
_x000D_
$handle = fopen('backup.sql', 'w+');_x000D_
fwrite($handle, $return);_x000D_
fclose($handle);_x000D_
echo "success";_x000D_
_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

upd. fixed error in code, added space before VALUES in line $return .= 'INSERT INTO '.$table.'VALUES(';

Difference between using Makefile and CMake to compile the code

Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.

Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?

How do I implement JQuery.noConflict() ?

In addition to that, passing true to $.noConflict(true); will also restore previous (if any) global variable jQuery, so that plugins can be initialized with correct jQuery version when multiple versions are being used.

What causes java.lang.IncompatibleClassChangeError?

I had the same issue, and later I figured out that I am running the application on Java version 1.4 while the application is compiled on version 6.

Actually, the reason was of having a duplicate library, one is located within the classpath and the other one is included inside a jar file that is located within the classpath.

How to count the NaN values in a column in pandas DataFrame

Lets assume df is a pandas DataFrame.

Then,

df.isnull().sum(axis = 0)

This will give number of NaN values in every column.

If you need, NaN values in every row,

df.isnull().sum(axis = 1)

How to use KeyListener

The class which implements KeyListener interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame. So

  1. Make one Key listener class as

    class MyListener implements KeyListener{
    
       // override all the methods of KeyListener interface.
    }
    
  2. Now our class MyKeyListener is ready to listen the key events. But it can not directly do so.

  3. Create any object like JFrame object through which MyListener can listen the key events. for that you need to add MyListener object to the JFrame object.

    JFrame f=new JFrame();
    f.addKeyListener(new MyKeyListener);
    

pip cannot install anything

I had this error message occur as I had set a Windows Environment Variable to an invalid certificate file.

Check if you have a CURL_CA_BUNDLE variable by typing SET at the command prompt.

You can override it for the current session with SET CURL_CA_BUNDLE=

The pip.log contained the following:

Getting page https://pypi.python.org/simple/pip/
Could not fetch URL https://pypi.python.org/simple/pip/: connection error: [Errno 185090050] _ssl.c:340: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib

Using the rJava package on Win7 64 bit with R

Update (July 2018):

The latest CRAN version of rJava will find the jvm.dll automatically, without manually setting the PATH or JAVA_HOME. However note that:

  • To use rJava in 32-bit R, you need Java for Windows x86
  • To use rJava in 64-bit R, you need Java for Windows x64
  • To build or check R packages with multi-arch (the default) you need to install both Java For Windows x64 as well as Java for Windows x86. On Win 64, the former installs in C:\Program files\Java\ and the latter in C:\Program Files (x86)\Java\ so they do not conflict.

As of Java version 9, support for x86 (win32) has been discontinued. Hence the latest working multi-arch setup is to install both jdk-8u172-windows-i586.exe and jdk-8u172-windows-x64.exe and then the binary package from CRAN:

install.packages("rJava")

The binary package from CRAN should pick up on the jvm by itself. Experts only: to build rJava from source, you need the --merge-multiarch flag:

install.packages('rJava', type = 'source', INSTALL_opts='--merge-multiarch')

Old anwser:

(Note: many of folks in other answers/comments have said to remove JAVA_HOME, so consider that. I have not revisited this issue recently to know if all the steps below are still necessary.)

Here is some quick advice on how to get up and running with R + rJava on Windows 7 64bit. There are several possibilities, but most have fatal flaws. Here is what worked for me:

Add jvm.dll to your PATH

rJava, the R<->Java bridge, will need jvm.dll, but R will have trouble finding that DLL. It resides in a folder like

C:\Program Files\Java\jdk1.6.0_25\jre\bin\server

or

C:\Program Files\Java\jre6\jre\bin\client

Wherever yours is, add that directory to your windows PATH variable. (Windows -> "Path" -> "Edit environment variables to for your account" -> PATH -> edit the value.)

You may already have Java on your PATH. If so you should find the client/server directory in the same Java "home" dir as the one already on your PATH.

To be safe, make sure your architectures match.If you have Java in Program Files, it is 64-bit, so you ought to run R64. If you have Java in Program Files (x86), that's 32-bit, so you use plain 32-bit R.

Re-launch R from the Windows Menu

If R is running, quit.

From the Start Menu , Start R / RGUI, RStudio. This is very important, to make R pick up your PATH changes.

Install rJava 0.9.2.

Earlier versions do not work! Mirrors are not up-to-date, so go to the source at www.rforge.net: http://www.rforge.net/rJava/files/. Note the advice there

“Please use

`install.packages('rJava',,'http://www.rforge.net/')`

to install.”

That is almost correct. This actually works:

install.packages('rJava', .libPaths()[1], 'http://www.rforge.net/')

Watch the punctuation! The mysterious “.libPaths()[1],” just tells R to install the package in the primary library directory. For some reason, leaving the value blank doesn’t work, even though it should default.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

1) in a query window in SQL Server Management Studio, run the command:

SET SHOWPLAN_ALL ON

2) run your slow query

3) your query will not run, but the execution plan will be returned. store this output

4) run your fast version of the query

5) your query will not run, but the execution plan will be returned. store this output

6) compare the slow query version output to the fast query version output.

7) if you still don't know why one is slower, post both outputs in your question (edit it) and someone here can help from there.

How to switch to new window in Selenium for Python?

window_handles should give you the references to all open windows.

this is what the docu has to say about switching windows.

How to round down to nearest integer in MySQL?

Use FLOOR(), if you want to round your decimal to the lower integer. Examples:

FLOOR(1.9) => 1
FLOOR(1.1) => 1

Use ROUND(), if you want to round your decimal to the nearest integer. Examples:

ROUND(1.9) => 2
ROUND(1.1) => 1

Use CEIL(), if you want to round your decimal to the upper integer. Examples:

CEIL(1.9) => 2
CEIL(1.1) => 2

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

How can you tell when a layout has been drawn?

You can add a tree observer to the layout. This should return the correct width and height. onCreate() is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width, put this on the onCreate() method:

    final LinearLayout layout = (LinearLayout) findViewById(R.id.YOUR_VIEW_ID);
    ViewTreeObserver vto = layout.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener (new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    layout.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    layout.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
            int width  = layout.getMeasuredWidth();
            int height = layout.getMeasuredHeight(); 

        } 
    });

How to compare two Carbon Timestamps?

First, Eloquent automatically converts it's timestamps (created_at, updated_at) into carbon objects. You could just use updated_at to get that nice feature, or specify edited_at in your model in the $dates property:

protected $dates = ['edited_at'];

Now back to your actual question. Carbon has a bunch of comparison functions:

  • eq() equals
  • ne() not equals
  • gt() greater than
  • gte() greater than or equals
  • lt() less than
  • lte() less than or equals

Usage:

if($model->edited_at->gt($model->created_at)){
    // edited at is newer than created at
}

How do I read text from the clipboard?

I found out this was the easiest way to get access to the clipboard from python:

1) Install pyperclip: pip install pyperclip

2) Usage:

import pyperclip

s = pyperclip.paste()
pyperclip.copy(s)

# the type of s is string

Tested on Win10 64-bit, Python 3.5 and Python 3.7.3 (64-bit). Seems to work with non-ASCII characters, too. Tested characters include ±°©©aß????Fåäö

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

@chappers solution (in the comments) works as.integer(as.logical(data.frame$column.name))

send/post xml file using curl command line

If you have multiple headers then you might want to use the following:

curl -X POST --header "Content-Type:application/json" --header "X-Auth:AuthKey" --data @hello.json Your_url

Really killing a process in Windows

taskkill /im myprocess.exe /f

The "/f" is for "force". If you know the PID, then you can specify that, as in:

taskkill /pid 1234 /f

Lots of other options are possible, just type taskkill /? for all of them. The "/t" option kills a process and any child processes; that may be useful to you.

JavaScript for detecting browser language preference

If you are using ASP .NET MVC and you want to get the Accepted-Languages header from JavaScript then here is a workaround example that does not involve any asynchronous requests.

In your .cshtml file, store the header securely in a div's data- attribute:

<div data-languages="@Json.Encode(HttpContext.Current.Request.UserLanguages)"></div>

Then your JavaScript code can access the info, e.g. using JQuery:

<script type="text/javascript">
$('[data-languages]').each(function () {
    var languages = $(this).data("languages");
    for (var i = 0; i < languages.length; i++) {
        var regex = /[-;]/;
        console.log(languages[i].split(regex)[0]);
    }
});
</script>

Of course you can use a similar approach with other server technologies as others have mentioned.

Maven: Non-resolvable parent POM

Just add <relativePath /> so the parent in pom should look like:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath />
    </parent>