Programs & Examples On #Db structure

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

Bash script - variable content as a command to run

line=$((${RANDOM} % $(wc -l < /etc/passwd)))
sed -n "${line}p" /etc/passwd

just with your file instead.

In this example I used the file /etc/password, using the special variable ${RANDOM} (about which I learned here), and the sed expression you had, only difference is that I am using double quotes instead of single to allow the variable expansion.

React js onClick can't pass value to method

Using arrow function :

You must install stage-2:

npm install babel-preset-stage-2 :

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value=0
        }
    }

    changeValue = (data) => (e) => {
        alert(data);  //10
        this.setState({ [value]: data })
    }

    render() {
        const data = 10;
        return (
            <div>
                <input type="button" onClick={this.changeValue(data)} />
            </div>
        );
    }
}
export default App; 

Xcode 10 Error: Multiple commands produce

If your app is generating the error related to the multiple .app files then removing the .plist files from "Copy bundle Resources" WILL NOT WORK.

If the error is related to .app file then follow the following steps

  1. Select the Target.

  2. Go to Build Phases tab.

  3. Remove the items listed in Output Files
  4. Compile the code if it compiles successfully then not follow the next steps.
  5. If code does not compile successfully and Xcode may give you an error related to "Library not found". Then add the missing library in General Tab in Linked Frameworks and Libraries that Xcode mentioned in the error.
  6. Keep adding these libraries (that Xcode ask through compile errors) in Linked Frameworks and Libraries until the code compiles successfully.

    Hope this helps.

How to get the path of current worksheet in VBA?

Always nice to have:

Dim myPath As String     
Dim folderPath As String 

folderPath = Application.ActiveWorkbook.Path    
myPath = Application.ActiveWorkbook.FullName

iOS - UIImageView - how to handle UIImage image orientation

If you need to rotate and fix the image orientation below extension would be useful.

extension UIImage {

    public func imageRotatedByDegrees(degrees: CGFloat) -> UIImage {
        //Calculate the size of the rotated view's containing box for our drawing space
        let rotatedViewBox: UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        let t: CGAffineTransform = CGAffineTransform(rotationAngle: degrees * CGFloat.pi / 180)
        rotatedViewBox.transform = t
        let rotatedSize: CGSize = rotatedViewBox.frame.size
        //Create the bitmap context
        UIGraphicsBeginImageContext(rotatedSize)
        let bitmap: CGContext = UIGraphicsGetCurrentContext()!
        //Move the origin to the middle of the image so we will rotate and scale around the center.
        bitmap.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
        //Rotate the image context
        bitmap.rotate(by: (degrees * CGFloat.pi / 180))
        //Now, draw the rotated/scaled image into the context
        bitmap.scaleBy(x: 1.0, y: -1.0)
        bitmap.draw(self.cgImage!, in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }


    public func fixedOrientation() -> UIImage {
        if imageOrientation == UIImageOrientation.up {
            return self
        }

        var transform: CGAffineTransform = CGAffineTransform.identity

        switch imageOrientation {
        case UIImageOrientation.down, UIImageOrientation.downMirrored:
            transform = transform.translatedBy(x: size.width, y: size.height)
            transform = transform.rotated(by: CGFloat.pi)
            break
        case UIImageOrientation.left, UIImageOrientation.leftMirrored:
            transform = transform.translatedBy(x: size.width, y: 0)
            transform = transform.rotated(by: CGFloat.pi/2)
            break
        case UIImageOrientation.right, UIImageOrientation.rightMirrored:
            transform = transform.translatedBy(x: 0, y: size.height)
            transform = transform.rotated(by: -CGFloat.pi/2)
            break
        case UIImageOrientation.up, UIImageOrientation.upMirrored:
            break
        }

        switch imageOrientation {
        case UIImageOrientation.upMirrored, UIImageOrientation.downMirrored:
            transform.translatedBy(x: size.width, y: 0)
            transform.scaledBy(x: -1, y: 1)
            break
        case UIImageOrientation.leftMirrored, UIImageOrientation.rightMirrored:
            transform.translatedBy(x: size.height, y: 0)
            transform.scaledBy(x: -1, y: 1)
        case UIImageOrientation.up, UIImageOrientation.down, UIImageOrientation.left, UIImageOrientation.right:
            break
        }

        let ctx: CGContext = CGContext(data: nil,
                                       width: Int(size.width),
                                       height: Int(size.height),
                                       bitsPerComponent: self.cgImage!.bitsPerComponent,
                                       bytesPerRow: 0,
                                       space: self.cgImage!.colorSpace!,
                                       bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!

        ctx.concatenate(transform)

        switch imageOrientation {
        case UIImageOrientation.left, UIImageOrientation.leftMirrored, UIImageOrientation.right, UIImageOrientation.rightMirrored:
            ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
        default:
            ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            break
        }

        let cgImage: CGImage = ctx.makeImage()!

        return UIImage(cgImage: cgImage)
    }
}

How can I get the count of line in a file in an efficient way?

All previous answers suggest to read though the whole file and count the amount of newlines you find while doing this. You commented some as "not effective" but thats the only way you can do that. A "line" is nothing else as a simple character inside the file. And to count that character you must have a look at every single character within the file.

I'm sorry, but you have no choice. :-)

Spring MVC Controller redirect using URL parameters instead of in response

http://jira.springframework.org/browse/SPR-6464 provided me with what I needed to get things working until Spring MVC offers the functionality (potentially in the 3.0.2 release). Although I simply implemented the classes they have temporarily and added the filter to my web application context. Works great!

Shortcuts in Objective-C to concatenate NSStrings

Was trying the following in the lldb pane

[NSString stringWithFormat:@"%@/%@/%@", three, two, one];

which errors.

instead use alloc and initWithFormat method:

[[NSString alloc] initWithFormat:@"%@/%@/%@", @"three", @"two", @"one"];

How to make an HTTP get request with parameters

You can also pass value directly via URL.

If you want to call method public static void calling(string name){....}

then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya); webrequest.Method = "GET"; webrequest.ContentType = "application/text";

Just make sure you are using ?Object = value in URL

How do I manage MongoDB connections in a Node.js web application?

mongodb.com -> new project -> new cluster -> new collection -> connect -> IP address: 0.0.0.0/0 & db cred -> connect your application -> copy connection string and paste in .env file of your node app and make sure to replace "" with the actual password for the user and also replace "/test" with your db name

create new file .env

CONNECTIONSTRING=x --> const client = new MongoClient(CONNECTIONSTRING) 
PORT=8080 
JWTSECRET=mysuper456secret123phrase

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

I have also faced the similar problem with the following details Java 1.8.0_121, Spark spark-1.6.1-bin-hadoop2.6, Windows 10 and Eclipse Oxygen.When I ran my WordCount.java in Eclipse using HADOOP_HOME as a system variable as mentioned in the previous post, it did not work, what worked for me is -

System.setProperty("hadoop.home.dir", "PATH/TO/THE/DIR");

PATH/TO/THE/DIR/bin=winutils.exe whether you run within Eclipse as a Java application or by spark-submit from cmd using

spark-submit --class groupid.artifactid.classname --master local[2] /path to the jar file created using maven /path to a demo test file /path to output directory command

Example: Go to the bin location of Spark/home/location/bin and execute the spark-submit as mentioned,

D:\BigData\spark-2.3.0-bin-hadoop2.7\bin>spark-submit --class com.bigdata.abdus.sparkdemo.WordCount --master local[1] D:\BigData\spark-quickstart\target\spark-quickstart-0.0.1-SNAPSHOT.jar D:\BigData\spark-quickstart\wordcount.txt

Set background colour of cell to RGB value of data in cell

Sub AddColor()
    For Each cell In Selection
        R = Round(cell.Value)
        G = Round(cell.Offset(0, 1).Value)
        B = Round(cell.Offset(0, 2).Value)
        Cells(cell.Row, 1).Resize(1, 4).Interior.Color = RGB(R, G, B)
    Next cell
End Sub

Assuming that there are 3 columns R, G and B (in this order). Select first column ie R. press alt+F11 and run the above code. We have to select the first column (containing R or red values) and run the code every time we change the values to reflect the changes.

I hope this simpler code helps !

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

Here is the function example trim generic type of array object

const trimArrayObject = <T>(items: T[]) => {

  items.forEach(function (o) {

    for (let [key, value] of Object.entries(o)) {

      const keyName = <keyof typeof o>key;

      if (Array.isArray(value)) {

        trimArrayObject(value);

      } else if (typeof o[keyName] === "string") {

        o[keyName] = value.trim();

      }

    }

  });

};

Case-insensitive search in Rails model

Assuming that you use mysql, you could use fields that are not case sensitive: http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html

MySQL error code: 1175 during UPDATE in MySQL Workbench

In the MySQL Workbech version 6.2 don't exits the PreferenceSQLQueriesoptions.

In this case it's possible use: SET SQL_SAFE_UPDATES=0;

Best way to store data locally in .NET (C#)

Without knowing what your data looks like, i.e. the complexity, size, etc...XML is easy to maintain and easily accessible. I would NOT use an Access database, and flat files are more difficult to maintain over the long haul, particularly if you are dealing with more than one data field/element in your file.

I deal with large flat-file data feeds in good quantities daily, and even though an extreme example, flat-file data is much more difficult to maintain than the XML data feeds I process.

A simple example of loading XML data into a dataset using C#:

DataSet reportData = new DataSet();

reportData.ReadXml(fi.FullName);

You can also check out LINQ to XML as an option for querying the XML data...

HTH...

Error Code: 1005. Can't create table '...' (errno: 150)

Error Code: 1005

I had a similar issue, so here are few things that I did try (not in any order, except for the solution :) )

  1. Changed the foreign key names (it didn't work)
  2. Reduced the foreign key length
  3. Verified the datatypes (darn nothing wrong)
  4. Check indexes
  5. Check the collations (everything fine, darn again)
  6. Truncated the table, of no good use
  7. Dropped the table and re-created
  8. Tried to see if any circular reference is being created --- all fine
  9. Finally, I saw that I had two editors open. One that in PhpStorm (JetBrains) and the other MySQL workbench. It seems that the PhpStorm / MySQL Workbench creates some kind of edit lock.

    I closed PhpStorm just to check if locking was the case (it could have been the other way around). This solved my problem.

What type of hash does WordPress use?

$hash_type$salt$password

If the hash does not use a salt, then there is no $ sign for that. The actual hash in your case is after the 2nd $

The reason for this is, so you can have many types of hashes with different salts and feeds that string into a function that knows how to match it with some other value.

How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

If you are using ES6 you can:

var sample = [1, 2, 3]

var result = sample.filter(elem => elem !== 2)

/* output */
[1, 3]

Also take notice filter does not update the existing array it will return a new filtered array every time.

How do I raise an exception in Rails so it behaves like other Rails exceptions?

If you need an easier way to do it, and don't want much fuss, a simple execution could be:

raise Exception.new('something bad happened!')

This will raise an exception, say e with e.message = something bad happened!

and then you can rescue it as you are rescuing all other exceptions in general.

Repeat a string in JavaScript a number of times

For all browsers

The following function will perform a lot faster than the option suggested in the accepted answer:

var repeat = function(str, count) {
    var array = [];
    for(var i = 0; i < count;)
        array[i++] = str;
    return array.join('');
}

You'd use it like this :

var repeatedString = repeat("a", 10);

To compare the performance of this function with that of the option proposed in the accepted answer, see this Fiddle and this Fiddle for benchmarks.

For moderns browsers only

In modern browsers, you can now do this using String.prototype.repeat method:

var repeatedString = "a".repeat(10);

Read more about this method on MDN.

This option is even faster. Unfortunately, it doesn't work in any version of Internet explorer. The numbers in the table specify the first browser version that fully supports the method:

enter image description here

How to parse dates in multiple formats using SimpleDateFormat

Implemented the same in scala, Please help urself with converting to Java, the core logic and functions used stays the same.

import java.text.SimpleDateFormat
import org.apache.commons.lang.time.DateUtils

object MultiDataFormat {
  def main(args: Array[String]) {

val dates =Array("2015-10-31","26/12/2015","19-10-2016")

val possibleDateFormats:Array[String] = Array("yyyy-MM-dd","dd/MM/yyyy","dd-MM-yyyy")

val sdf =  new SimpleDateFormat("yyyy-MM-dd") //change it as per the requirement
  for (date<-dates) {
    val outputDate = DateUtils.parseDateStrictly(date, possibleDateFormats)
    System.out.println("inputDate ==> " + date + ", outputDate ==> " +outputDate + " " + sdf.format(outputDate) )
  }
}

}

BackgroundWorker vs background Thread

The basic difference is, like you stated, generating GUI events from the BackgroundWorker. If the thread does not need to update the display or generate events for the main GUI thread, then it can be a simple thread.

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

Get encoding of a file in Windows

The only way that I have found to do this is VIM or Notepad++.

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

SELECT convert(datetime, '23/07/2009', 103)

successful/fail message pop up box after submit?

Instead of using a submit button, try using a <button type="button">Submit</button>

You can then call a javascript function in the button, and after the alert popup is confirmed, you can manually submit the form with document.getElementById("form").submit(); ... so you'll need to name and id your form for that to work.

Javascript AES encryption

There is also a Stanford free lib as an alternative to Cryptojs

http://crypto.stanford.edu/sjcl/

How to remove \n from a list element?

To handle many newline delimiters, including character combinations like \r\n, use splitlines. Combine join and splitlines to remove/replace all newlines from a string s:

''.join(s.splitlines())

To remove exactly one trailing newline, pass True as the keepends argument to retain the delimiters, removing only the delimiters on the last line:

def chomp(s):
    if len(s):
        lines = s.splitlines(True)
        last = lines.pop()
        return ''.join(lines + last.splitlines())
    else:
        return ''

Change color inside strings.xml

If you want to support text formatting from within your strings.xml file, you have to escape the tags – or use a CDATA section.. Otherwise Android simply ignores them when reading the resource file.

e.g

<string name="hello_world">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>

OR

String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);

JavaScript: clone a function

function cloneFunction(Func, ...args) {
  function newThat(...args2) {
    return new Func(...args2);
  }
  function clone() {
    if (this instanceof clone) {
      return newThat(...args);
    }
    return Func.apply(this, args);
  }
  for (const key in Func) {
    if (Func.hasOwnProperty(key)) {
      clone[key] = Func[key];
    }
  }
  Object.defineProperty(clone, 'name', { value: Func.name, configurable: true })
  return clone
};

function myFunction() {
  console.log('Called Function')
}

myFunction.value = 'something';

const newFunction = cloneFunction(myFunction);

newFunction.another = 'somethingelse';

console.log('Equal? ', newFunction === myFunction);
console.log('Names: ', myFunction.name, newFunction.name);
console.log(myFunction);
console.log(newFunction);
console.log('InstanceOf? ', newFunction instanceof myFunction);

myFunction();
newFunction();

While I would never recommend using this, I thought it would be an interesting little challenge to come up with a more precise clone by taking some of the practices that seemed to be the best and fixing it up a bit. Heres the result of the logs:

Equal?  false
Names:  myFunction myFunction
{ [Function: myFunction] value: 'something' }
{ [Function: myFunction] value: 'something', another: 'somethingelse' }
InstanceOf?  false
Called Function
Called Function

Making interface implementations async

An abstract class can be used instead of an interface (in C# 7.3).

// Like interface
abstract class IIO
{
    public virtual async Task<string> DoOperation(string Name)
    {
        throw new NotImplementedException(); // throwing exception
        // return await Task.Run(() => { return ""; }); // or empty do
    }
}

// Implementation
class IOImplementation : IIO
{
    public override async Task<string> DoOperation(string Name)
    {
        return await await Task.Run(() =>
        {
            if(Name == "Spiderman")
                return "ok";
            return "cancel";
        }); 
    }
}

Grouping functions (tapply, by, aggregate) and the *apply family

On the side note, here is how the various plyr functions correspond to the base *apply functions (from the intro to plyr document from the plyr webpage http://had.co.nz/plyr/)

Base function   Input   Output   plyr function 
---------------------------------------
aggregate        d       d       ddply + colwise 
apply            a       a/l     aaply / alply 
by               d       l       dlply 
lapply           l       l       llply  
mapply           a       a/l     maply / mlply 
replicate        r       a/l     raply / rlply 
sapply           l       a       laply 

One of the goals of plyr is to provide consistent naming conventions for each of the functions, encoding the input and output data types in the function name. It also provides consistency in output, in that output from dlply() is easily passable to ldply() to produce useful output, etc.

Conceptually, learning plyr is no more difficult than understanding the base *apply functions.

plyr and reshape functions have replaced almost all of these functions in my every day use. But, also from the Intro to Plyr document:

Related functions tapply and sweep have no corresponding function in plyr, and remain useful. merge is useful for combining summaries with the original data.

How do pointer-to-pointer's work in C? (and when might you use them?)

When covering pointers on a programming course at university, we were given two hints as to how to begin learning about them. The first was to view Pointer Fun With Binky. The second was to think about the Haddocks' Eyes passage from Lewis Carroll's Through the Looking-Glass

“You are sad,” the Knight said in an anxious tone: “Let me sing you a song to comfort you.”

“Is it very long?” Alice asked, for she had heard a good deal of poetry that day.

“It's long,” said the Knight, “but it's very, very beautiful. Everybody that hears me sing it - either it brings the tears to their eyes, or else -”

“Or else what?” said Alice, for the Knight had made a sudden pause.

“Or else it doesn't, you know. The name of the song is called ‘Haddocks' Eyes.’”

“Oh, that's the name of the song, is it?" Alice said, trying to feel interested.

“No, you don't understand,” the Knight said, looking a little vexed. “That's what the name is called. The name really is ‘The Aged Aged Man.’”

“Then I ought to have said ‘That's what the song is called’?” Alice corrected herself.

“No, you oughtn't: that's quite another thing! The song is called ‘Ways And Means’: but that's only what it's called, you know!”

“Well, what is the song, then?” said Alice, who was by this time completely bewildered.

“I was coming to that,” the Knight said. “The song really is ‘A-sitting On A Gate’: and the tune's my own invention.”

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

Display the current time and date in an Android application

To display the current date function:

Calendar c = Calendar.getInstance();

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String date = df.format(c.getTime());
Date.setText(date);

You must want to import

import java.text.SimpleDateFormat; import java.util.Calendar;

You must want to use

TextView Date;
Date = (TextView) findViewById(R.id.Date);

Writing image to local server

A few things happening here:

  1. I assume you required fs/http, and set the dir variable :)
  2. google.com redirects to www.google.com, so you're saving the redirect response's body, not the image
  3. the response is streamed. that means the 'data' event fires many times, not once. you have to save and join all the chunks together to get the full response body
  4. since you're getting binary data, you have to set the encoding accordingly on response and writeFile (default is utf8)

This should work:

var http = require('http')
  , fs = require('fs')
  , options

options = {
    host: 'www.google.com'
  , port: 80
  , path: '/images/logos/ps_logo2.png'
}

var request = http.get(options, function(res){
    var imagedata = ''
    res.setEncoding('binary')

    res.on('data', function(chunk){
        imagedata += chunk
    })

    res.on('end', function(){
        fs.writeFile('logo.png', imagedata, 'binary', function(err){
            if (err) throw err
            console.log('File saved.')
        })
    })

})

JQuery - Call the jquery button click event based on name property

You can use normal CSS selectors to select an element by name using jquery. Like this:

Button Code
<button type="button" name="mybutton">Click Me!</button>

Selector & Event Bind Code
$("button[name='mybutton']").click(function() {});

Int to Char in C#

Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use

string s = Char.ConvertFromUtf32(56);

which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

python request with authentication (access_token)

I'll add a bit hint: it seems what you pass as the key value of a header depends on your authorization type, in my case that was PRIVATE-TOKEN

header = {'PRIVATE-TOKEN': 'my_token'}
response = requests.get(myUrl, headers=header)

React this.setState is not a function

React recommends bind this in all methods that needs to use this of class instead this of self function.

constructor(props) {
    super(props)
    this.onClick = this.onClick.bind(this)
}

 onClick () {
     this.setState({...})
 }

Or you may to use arrow function instead.

How to parse JSON response from Alamofire API in Swift?

I found the answer on GitHub for Swift2

https://github.com/Alamofire/Alamofire/issues/641

Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
    .responseJSON { request, response, result in
        switch result {
        case .Success(let JSON):
            print("Success with JSON: \(JSON)")

        case .Failure(let data, let error):
            print("Request failed with error: \(error)")

            if let data = data {
                print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
            }
        }
    }

HTML: can I display button text in multiple lines?

one other way to improve and style the multi-line text is

 <button>Click here to<br/> 
     <span style="color:red;">start playing</span>

   </button>

How do I add PHP code/file to HTML(.html) files?

Create an empty file using notepad and name it .htaccess ,Then copy that file in your project directory and add this line and save.

AddType application/x-httpd-php .htm .html

else save the .html file using .php as php can support html,and save it in computer/var/www/html path(linux)

Angular ng-click with call to a controller function not working

You should probably use the ngHref directive along with the ngClick:

 <a ng-href='#here' ng-click='go()' >click me</a>

Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    {{msg}}
    <a ng-href='#here' ng-click='go()' >click me</a>
    <div style='height:1000px'>

      <a id='here'></a>

    </div>
     <h1>here</h1>
  </body>

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.go = function() {

    $scope.msg = 'clicked';
  }
});

I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.

** Update **

Here is a demo of the set and get working fine with a service.

http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, sharedProperties) {
  $scope.name = 'World';

  $scope.go = function(item) {
    sharedProperties.setListName(item);


  }

  $scope.getItem = function() {

    $scope.msg = sharedProperties.getListName();
  }
});

app.service('sharedProperties', function () {
    var list_name = '';

    return {

        getListName: function() {
            return list_name;
        },
        setListName: function(name) {
            list_name = name;
        }
    };


});

* Edit *

Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.

Remove empty space before cells in UITableView

There is may be pre-added UIRefreshControl. I have this problem with code like this:

self.refreshControl = [[UIRefreshControl alloc] init];{
    [self.refreshControl setAttributedTitle:[[NSAttributedString alloc]
                                             initWithString:@"Your string"]];
    [self.refreshControl addTarget:self
                            action:@selector(updateScreen)
                  forControlEvents:UIControlEventValueChanged];

}

As you see, I set self.refreshController immediately after init

But, if you set refreshControl after setup, then top-space don't interfere you.

UIRefreshControl *refreshControl  = [[UIRefreshControl alloc] init];{
    [self.refreshControl setAttributedTitle:[[NSAttributedString alloc]
                                             initWithString:@"Your String"]];
    [self.refreshControl addTarget:self
                            action:@selector(updateScreen)
                  forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refreshControl;
}

How to get input field value using PHP

Example of using PHP to get a value from a form:

Put this in foobar.php:

<html>
<body>
  <form action="foobar_submit.php" method="post">
    <input name="my_html_input_tag"  value="PILLS HERE"/>

    <input type="submit" name="my_form_submit_button" 
           value="Click here for penguins"/>

    </form>
</body>
</html>

Read the above code so you understand what it is doing:

"foobar.php is an HTML document containing an HTML form. When the user presses the submit button inside the form, the form's action property is run: foobar_submit.php. The form will be submitted as a POST request. Inside the form is an input tag with the name "my_html_input_tag". It's default value is "PILLS HERE". That causes a text box to appear with text: 'PILLS HERE' on the browser. To the right is a submit button, when you click it, the browser url changes to foobar_submit.php and the below code is run.

Put this code in foobar_submit.php in the same directory as foobar.php:

<?php
  echo $_POST['my_html_input_tag'];
  echo "<br><br>";
  print_r($_POST); 
?>

Read the above code so you know what its doing:

The HTML form from above populated the $_POST superglobal with key/value pairs representing the html elements inside the form. The echo prints out the value by key: 'my_html_input_tag'. If the key is found, which it is, its value is returned: "PILLS HERE".

Then print_r prints out all the keys and values from $_POST so you can peek as to what else is in there.

The value of the input tag with name=my_html_input_tag was put into the $_POST and you retrieved it inside another PHP file.

How to execute Python code from within Visual Studio Code

If you have a project consisting of multiple Python files and you want to start running/debugging with the main program independent of which file is current you create the following launch configuration (change MyMain.py to your main file).

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Python: Main File",
      "type": "python",
      "request": "launch",
      "program": "${workspaceFolder}/MyMain.py",
      "console": "integratedTerminal",
      "cwd": "${workspaceFolder}"
    }
  ]
}

how to call javascript function in html.actionlink in asp.net mvc?

For calling javascript in your action link you simply need to write actionlink like this:

@Html.ActionLink("Delete", "Your-Action", new { id = item.id },
                 new { onclick="return confirm('Are you sure?');"})

Don't get confused between route values and the html attributes.

vi/vim editor, copy a block (not usual action)

just use V to select lines or v to select chars or Ctrlv to select a block.

When the selection spans the area you'd like to copy just hit y and use p to paste it anywhere you like...

delete map[key] in go?

From Effective Go:

To delete a map entry, use the delete built-in function, whose arguments are the map and the key to be deleted. It's safe to do this even if the key is already absent from the map.

delete(timeZone, "PDT")  // Now on Standard Time

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

Using @angular/forms when you use a <form> tag it automatically creates a FormGroup.

For every contained ngModel tagged <input> it will create a FormControl and add it into the FormGroup created above; this FormControl will be named into the FormGroup using attribute name.

Example:

<form #f="ngForm">
    <input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
    <span>{{ f.controls['firstField']?.value }}</span>
</form>

Said this, the answer to your question follows.

When you mark it as standalone: true this will not happen (it will not be added to the FormGroup).

Reference: https://github.com/angular/angular/issues/9230#issuecomment-228116474

AngularJS is rendering <br> as text not as a newline

You can use \n to concatenate words and then apply this style to container div.

style="white-space: pre;"

More info can be found at https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

_x000D_
_x000D_
<p style="white-space: pre;">_x000D_
    This is normal text._x000D_
</p>_x000D_
<p style="white-space: pre;">_x000D_
    This _x000D_
  text _x000D_
  contains _x000D_
  new lines._x000D_
</p>
_x000D_
_x000D_
_x000D_

FIX CSS <!--[if lt IE 8]> in IE

Also, the comment tag

<comment></comment> 

is only supported in IE 8 and below, so if that's exactly what you're trying to target, you could wrap them in comment tag. They're the same as

<!--[if lte IE 8]><![endif]-->

In which lte means "less than or equal to".

See: Conditional Comments.

Ways to insert javascript into URL?

I believe the right answer is "it depends".

As others have pointed out, if the web application that is processing your request is naively receiving and echoing back the received payload or URL parameters (for GET requests) then it might be subject to code injection.

However, if the web application sanitizes and/or filters payload/parameters, it shouldn't be a problem.

It also depends on the user agent (e.g. browser), a customized user agent might inject code without user notice if it detects any in the request (don't know of any public one, but that is also possible).

Spring-Security-Oauth2: Full authentication is required to access this resource

I had the same problem, but I solve this with the following class:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class OAuthSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}

How do you launch the JavaScript debugger in Google Chrome?

Ctrl + Shift + J opens Developer Tools.

Check if string ends with one of the strings from a list

There is two ways: regular expressions and string (str) methods.

String methods are usually faster ( ~2x ).

import re, timeit
p = re.compile('.*(.mp3|.avi)$', re.IGNORECASE)
file_name = 'test.mp3'
print(bool(t.match(file_name))
%timeit bool(t.match(file_name)

792 ns ± 1.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

file_name = 'test.mp3'
extensions = ('.mp3','.avi')
print(file_name.lower().endswith(extensions))
%timeit file_name.lower().endswith(extensions)

274 ns ± 4.22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

How to test web service using command line curl

From the documentation on http://curl.haxx.se/docs/httpscripting.html :

HTTP Authentication

curl --user name:password http://www.example.com 

Put a file to a HTTP server with curl:

curl --upload-file uploadfile http://www.example.com/receive.cgi

Send post data with curl:

curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi

How to print out more than 20 items (documents) in MongoDB's shell?

I suggest you to have a ~/.mongorc.js file so you do not have to set the default size everytime.

 # execute in your terminal
 touch ~/.mongorc.js
 echo 'DBQuery.shellBatchSize = 100;' > ~/.mongorc.js
 # add one more line to always prettyprint the ouput
 echo 'DBQuery.prototype._prettyShell = true; ' >> ~/.mongorc.js

To know more about what else you can do, I suggest you to look at this article: http://mo.github.io/2017/01/22/mongo-db-tips-and-tricks.html

How to get Url Hash (#) from server side

Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX). Regards Artur

You may see also how to play with back button and browser history at Malcan

Which Protocols are used for PING?

Internet Control Message Protocol

http://en.wikipedia.org/wiki/Internet_Control_Message_Protocol

ICMP is built on top of a bunch of other protocols, so in that sense your TA is correct. However, ping itself is ICMP.

Checking for empty or null List<string>

For anyone who doesn't have the guarantee that the list will not be null, you can use the null-conditional operator to safely check for null and empty lists in a single conditional statement:

if (list?.Any() != true)
{
    // Handle null or empty list
}

How can I use "." as the delimiter with String.split() in java

You might be interested in the StringTokenizer class. However, the java docs advise that you use the .split method as StringTokenizer is a legacy class.

MAVEN_HOME, MVN_HOME or M2_HOME

Here is my Maven setup. You can use it as an example. You don't need anything else in order to use Maven.

M2_HOME is used for both Maven 2 and 3

export M2_HOME=/Users/xxx/sdk/apache-maven-3.0.5
export M2=$M2_HOME/bin
export MAVEN_OPTS="-Xmx1048m -Xms256m -XX:MaxPermSize=312M"
export PATH=$M2:$PATH

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

Java generating Strings with placeholders

See String.format method.

String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true

Simplest way to set image as JPanel background

I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class

yes you will have to extend JPanel and override the paintcomponent(Graphics g) function to do so.

@Override
  protected void paintComponent(Graphics g) {

    super.paintComponent(g);
        g.drawImage(bgImage, 0, 0, null);
}

I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).

You can use other component which allows to add image as icon directly e.g. JLabel if you want.

ImageIcon icon = new ImageIcon(imgURL); 
JLabel thumb = new JLabel();
thumb.setIcon(icon);

But again in the bracket trying to keep things organized and simple !! what makes you to think that just creating a new class will lead you to a messy world ?

How to change the Text color of Menu item in Android?

My situation was settings text color in the options menu (main app menu showed on menu button press).

Tested in API 16 with appcompat-v7-27.0.2 library, AppCompatActivity for MainActivity and AppCompat theme for the application in AndroidManifest.xml.

styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  <item name="actionBarPopupTheme">@style/PopupTheme</item>
</style>

<style name="PopupTheme" parent="@style/ThemeOverlay.AppCompat.Light">
  <item name="android:textColorSecondary">#f00</item>
</style>

Don't know if that textColorSecondary affects other elements but it controls the menu text color.


I searched some examples on the topic but all ready-to-use snippets didn't work.

So I wanted to investigate it with the source code for the appcompat-v7 library (specifically with the res folder of the .aar package).

Though in my case I used Eclipse with exploded .aar dependencies. So I could change the default styles and check the results. Don't know how to explode the libraries to use with Gradle or Android Studio directly. It deserves another thread of investigation.

So my purpose was so find which color in the res/values/values.xml file is used for the menu text (I was almost sure the color was there).

  1. I opened that file, then duplicated all colors, put them below the default ones to override them and assigned #f00 value to all of them.
  2. Start the app.
  3. Many elements had red background or text color. And the menu items too. That was what I needed.
  4. Removing my added colors by blocks of 5-10 lines I ended with the secondary_text_default_material_light color item.
  5. Searching that name in the files within the res folder (or better within res/colors) I found only one occurrence in the color/abc_secondary_text_material_light.xml file (I used Sublime Text for these operations so it's easier to find thing I need).
  6. Back to the values.xml 8 usages were found for the @color/abc_secondary_text_material_light.
  7. It was a Light theme so 4 left in 2 themes: Base.ThemeOverlay.AppCompat.Light and Platform.AppCompat.Light.
  8. The first theme was a child of the second one so there were only 2 attributes with that color resource: android:textColorSecondary and android:textColorTertiaryin the Base.ThemeOverlay.AppCompat.Light.
  9. Changing their values directly in the values.xml and running the app I found that the final correct attribute was android:textColorSecondary.
  10. Next I needed a theme or another attribute so I could change it in my app's style.xml (because my theme had as the parent the Theme.AppCompat.Light and not the ThemeOverlay.AppCompat.Light).
  11. I searched in the same file for the Base.ThemeOverlay.AppCompat.Light. It had a child ThemeOverlay.AppCompat.Light.
  12. Searching for the ThemeOverlay.AppCompat.Light I found its usage in the Base.Theme.AppCompat.Light.DarkActionBar theme as the actionBarPopupTheme attribute value.
  13. My app's theme Theme.AppCompat.Light.DarkActionBar was a child of the found Base.Theme.AppCompat.Light.DarkActionBar so I could use that attribute in my styles.xml without problems.
  14. As it's seen in the example code above I created a child theme from the mentioned ThemeOverlay.AppCompat.Light and changed the android:textColorSecondary attribute.

https://i.imgur.com/LNfKdzC.png

How to detect browser using angularjs?

Not sure why you specify that it has to be within Angular. It's easily accomplished through JavaScript. Look at the navigator object.

Just open up your console and inspect navigator. It seems what you're specifically looking for is .userAgent or .appVersion.

I don't have IE9 installed, but you could try this following code

//Detect if IE 9
if(navigator.appVersion.indexOf("MSIE 9.")!=-1)

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I had a similar problem with a new ASP.NET Core application a while ago. Turns out one of the referenced libraries used a version of Newtonsoft.Json that was lower than 9.0.0.0. So I upgraded the version for that library and the problem was solved. Not sure if you'll be able to do the same here

Android Camera : data intent returns null

The following code works for me:

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2);

And here is the result:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{ 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    if(resultCode == RESULT_OK)
    {
        Uri selectedImage = imageReturnedIntent.getData();
        ImageView photo = (ImageView) findViewById(R.id.add_contact_label_photo);
        Bitmap mBitmap = null;
        try
        {
            mBitmap = Media.getBitmap(this.getContentResolver(), selectedImage);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Difference between [routerLink] and routerLink

Assume that you have

const appRoutes: Routes = [
  {path: 'recipes', component: RecipesComponent }
];

<a routerLink ="recipes">Recipes</a>

It means that clicking Recipes hyperlink will jump to http://localhost:4200/recipes

Assume that the parameter is 1

<a [routerLink] = "['/recipes', parameter]"></a>

It means that passing dynamic parameter, 1 to the link, then you navigate to http://localhost:4200/recipes/1

How does the Spring @ResponseBody annotation work?

First of all, the annotation doesn't annotate List. It annotates the method, just as RequestMapping does. Your code is equivalent to

@RequestMapping(value="/orders", method=RequestMethod.GET)
@ResponseBody
public List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

Now what the annotation means is that the returned value of the method will constitute the body of the HTTP response. Of course, an HTTP response can't contain Java objects. So this list of accounts is transformed to a format suitable for REST applications, typically JSON or XML.

The choice of the format depends on the installed message converters, on the values of the produces attribute of the @RequestMapping annotation, and on the content type that the client accepts (that is available in the HTTP request headers). For example, if the request says it accepts XML, but not JSON, and there is a message converter installed that can transform the list to XML, then XML will be returned.

Bash: If/Else statement in one line

Use grep -vc to ignore grep in the ps output and count the lines simultaneously.

if [[ $(ps aux | grep process | grep -vc grep)  > 0 ]] ; then echo 1; else echo 0 ; fi

Check if record exists from controller in Rails

When you call Business.where(:user_id => current_user.id) you will get an array. This Array may have no objects or one or many objects in it, but it won't be null. Thus the check == nil will never be true.

You can try the following:

if Business.where(:user_id => current_user.id).count == 0

So you check the number of elements in the array and compare them to zero.

or you can try:

if Business.find_by_user_id(current_user.id).nil?

this will return one or nil.

List of all unique characters in a string?

char_seen = []
for char in string:
    if char not in char_seen:
        char_seen.append(char)
print(''.join(char_seen))

This will preserve the order in which alphabets are coming,

output will be

abcd

How to cancel an $http request in AngularJS?

This enhances the accepted answer by decorating the $http service with an abort method as follows ...

'use strict';
angular.module('admin')
  .config(["$provide", function ($provide) {

$provide.decorator('$http', ["$delegate", "$q", function ($delegate, $q) {
  var getFn = $delegate.get;
  var cancelerMap = {};

  function getCancelerKey(method, url) {
    var formattedMethod = method.toLowerCase();
    var formattedUrl = encodeURI(url).toLowerCase().split("?")[0];
    return formattedMethod + "~" + formattedUrl;
  }

  $delegate.get = function () {
    var cancelerKey, canceler, method;
    var args = [].slice.call(arguments);
    var url = args[0];
    var config = args[1] || {};
    if (config.timeout == null) {
      method = "GET";
      cancelerKey = getCancelerKey(method, url);
      canceler = $q.defer();
      cancelerMap[cancelerKey] = canceler;
      config.timeout = canceler.promise;
      args[1] = config;
    }
    return getFn.apply(null, args);
  };

  $delegate.abort = function (request) {
    console.log("aborting");
    var cancelerKey, canceler;
    cancelerKey = getCancelerKey(request.method, request.url);
    canceler = cancelerMap[cancelerKey];

    if (canceler != null) {
      console.log("aborting", cancelerKey);

      if (request.timeout != null && typeof request.timeout !== "number") {

        canceler.resolve();
        delete cancelerMap[cancelerKey];
      }
    }
  };

  return $delegate;
}]);
  }]);

WHAT IS THIS CODE DOING?

To cancel a request a "promise" timeout must be set. If no timeout is set on the HTTP request then the code adds a "promise" timeout. (If a timeout is set already then nothing is changed).

However, to resolve the promise we need a handle on the "deferred". We thus use a map so we can retrieve the "deferred" later. When we call the abort method, the "deferred" is retrieved from the map and then we call the resolve method to cancel the http request.

Hope this helps someone.

LIMITATIONS

Currently this only works for $http.get but you can add code for $http.post and so on

HOW TO USE ...

You can then use it, for example, on state change, as follows ...

rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
  angular.forEach($http.pendingRequests, function (request) {
        $http.abort(request);
    });
  });

JavaScript for detecting browser language preference

I can't find a single reference that state that it's possible without involving the serverside.

MSDN on:

From browserLanguage:

In Microsoft Internet Explorer 4.0 and earlier, the browserLanguage property reflects the language of the installed browser's user interface. For example, if you install a Japanese version of Windows Internet Explorer on an English operating system, browserLanguage would be ja.

In Internet Explorer 5 and later, however, the browserLanguage property reflects the language of the operating system regardless of the installed language version of Internet Explorer. However, if Microsoft Windows 2000 MultiLanguage version is installed, the browserLanguage property indicates the language set in the operating system's current menus and dialogs, as found in the Regional Options of the Control Panel. For example, if you install a Japanese version of Internet Explorer 5 on an English (United Kingdom) operating system, browserLanguage would be en-gb. If you install Windows 2000 MultiLanguage version and set the language of the menus and dialogs to French, browserLanguage would be fr, even though you have a Japanese version of Internet Explorer.

Note This property does not indicate the language or languages set by the user in Language Preferences, located in the Internet Options dialog box.

Furthermore, it looks like browserLanguage is deprecated cause IE8 doesn't list it

How can I replace a regex substring match in Javascript?

I would get the part before and after what you want to replace and put them either side.

Like:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

var matches = str.match(regex);

var result = matches[1] + "1" + matches[2];

// With ES6:
var result = `${matches[1]}1${matches[2]}`;

How do I check that a Java String is not all whitespaces?

StringUtils.isEmptyOrWhitespaceOnly(<your string>)

will check : - is it null - is it only space - is it empty string ""

https://www.programcreek.com/java-api-examples/?class=com.mysql.jdbc.StringUtils&method=isEmptyOrWhitespaceOnly

Microsoft Excel ActiveX Controls Disabled?

It was KB2553154. Microsoft needs to release a fix. As a developer of Excel applications we can't go to all our clients computers and delete files off them. We are getting blamed for something Microsoft caused.

How to run a task when variable is undefined in ansible?

From the ansible docs: If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:

tasks:

- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
  when: foo is defined

- fail: msg="Bailing out. this play requires 'bar'"
  when: bar is not defined

So in your case, when: deployed_revision is not defined should work

SQL Server: Maximum character length of object names

128 characters. This is the max length of the sysname datatype (nvarchar(128)).

What is git fast-forwarding?

In Git, to "fast forward" means to update the HEAD pointer in such a way that its new value is a direct descendant of the prior value. In other words, the prior value is a parent, or grandparent, or grandgrandparent, ...

Fast forwarding is not possible when the new HEAD is in a diverged state relative to the stream you want to integrate. For instance, you are on master and have local commits, and git fetch has brought new upstream commits into origin/master. The branch now diverges from its upstream and cannot be fast forwarded: your master HEAD commit is not an ancestor of origin/master HEAD. To simply reset master to the value of origin/master would discard your local commits. The situation requires a rebase or merge.

If your local master has no changes, then it can be fast-forwarded: simply updated to point to the same commit as the latestorigin/master. Usually, no special steps are needed to do fast-forwarding; it is done by merge or rebase in the situation when there are no local commits.

Is it ok to assume that fast-forward means all commits are replayed on the target branch and the HEAD is set to the last commit on that branch?

No, that is called rebasing, of which fast-forwarding is a special case when there are no commits to be replayed (and the target branch has new commits, and the history of the target branch has not been rewritten, so that all the commits on the target branch have the current one as their ancestor.)

How do I enable NuGet Package Restore in Visual Studio?

I had to remove packages folder close and re-open (VS2015) solution. I was not migrating and I did not have packages checked into source control. All I can say is something got messed up and this fixed it.

Nodejs send file in response

You need use Stream to send file (archive) in a response, what is more you have to use appropriate Content-type in your response header.

There is an example function that do it:

const fs = require('fs');

// Where fileName is name of the file and response is Node.js Reponse. 
responseFile = (fileName, response) => {
  const filePath =  "/path/to/archive.rar" // or any file format

  // Check if file specified by the filePath exists 
  fs.exists(filePath, function(exists){
      if (exists) {     
        // Content-type is very interesting part that guarantee that
        // Web browser will handle response in an appropriate manner.
        response.writeHead(200, {
          "Content-Type": "application/octet-stream",
          "Content-Disposition": "attachment; filename=" + fileName
        });
        fs.createReadStream(filePath).pipe(response);
      } else {
        response.writeHead(400, {"Content-Type": "text/plain"});
        response.end("ERROR File does not exist");
      }
    });
  }
}

The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.

"application/octet-stream" is defined as "arbitrary binary data" in RFC 2046, purpose of this content-type is to be saved to disk - it is what you really need.

"filename=[name of file]" specifies name of file which will be downloaded.

For more information please see this stackoverflow topic.

React.js: Set innerHTML vs dangerouslySetInnerHTML

Based on (dangerouslySetInnerHTML).

It's a prop that does exactly what you want. However they name it to convey that it should be use with caution

JQuery create a form and add elements to it programmatically

The 2nd line should be written as:

$form.append('<input type="button" value="button">');

Nginx -- static file serving confusion with root & alias

server {
    server_name xyz.com;
    root /home/ubuntu/project_folder/;

    client_max_body_size 10M;
    access_log  /var/log/nginx/project.access.log;
    error_log  /var/log/nginx/project.error.log;

    location /static {
        index index.html;
    }

    location /media {
        alias /home/ubuntu/project/media/;
    }
}

Server block to live the static page on nginx.

How to sort a data frame by alphabetic order of a character variable in R?

Well, I've got no problem here :

df <- data.frame(v=1:5, x=sample(LETTERS[1:5],5))
df

#   v x
# 1 1 D
# 2 2 A
# 3 3 B
# 4 4 C
# 5 5 E

df <- df[order(df$x),]
df

#   v x
# 2 2 A
# 3 3 B
# 4 4 C
# 1 1 D
# 5 5 E

HTTP client timeout and server timeout

According to https://bugzilla.mozilla.org/show_bug.cgi?id=592284, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.

How to detect if JavaScript is disabled?

A technique I've used in the past is to use JavaScript to write a session cookie that simply acts as a flag to say that JavaScript is enabled. Then the server-side code looks for this cookie and if it's not found takes action as appropriate. Of course this technique does rely on cookies being enabled!

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

It is possible, as long as you know what instantiations you are going to need.

Add the following code at the end of stack.cpp and it'll work :

template class stack<int>;

All non-template methods of stack will be instantiated, and linking step will work fine.

matching query does not exist Error in Django

I also had this problem. It was caused by the development server not deleting the django session after a debug abort in Aptana, with subsequent database deletion. (Meaning the id of a non-existent database record was still present in the session the next time the development server started)

To resolve this during development, I used

request.session.flush()

HTML button calling an MVC Controller and Action method

Razor syntax is here:

<input type="button" value="Create" onclick="location.href='@Url.Action("Create", "User")'" />

Whitespace Matching Regex - Java

Java has evolved since this issue was first brought up. You can match all manner of unicode space characters by using the \p{Zs} group.

Thus if you wanted to replace one or more exotic spaces with a plain space you could do this:

String txt = "whatever my string is";
txt.replaceAll("\\p{Zs}+", " ")

Also worth knowing, if you've used the trim() string function you should take a look at the (relatively new) strip(), stripLeading(), and stripTrailing() functions on strings. The can help you trim off all sorts of squirrely white space characters. For more information on what what space is included, see Java's Character.isWhitespace() function.

Git push existing repo to a new and different remote repo server?

Here is a manual way to do git remote set-url origin [new repo URL]:

  1. Clone the repository: git clone <old remote>
  2. Create a GitHub repository
  3. Open <repository>/.git/config

    $ git config -e
    
    [core]
        repositoryformatversion = 0
        filemode = false
        bare = false
        logallrefupdates = true
        symlinks = false
        ignorecase = true
    [remote "origin"]
        url = <old remote>
        fetch = +refs/heads/*:refs/remotes/origin/*
    [branch "master"]
        remote = origin
        merge = refs/heads/master
    

    and change the remote (the url option)

    [remote "origin"]
        url = <new remote>
        fetch = +refs/heads/*:refs/remotes/origin/*
    
  4. Push the repository to GitHub: git push

You can also use both/multiple remotes.

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

Create a one to many relationship using SQL Server

If you are not using SSMS then here is the syntax:

ALTER TABLE <table_name>
ADD <constraint_name> FOREIGN KEY 
(<column_name1> ,
<column_name2> )
REFERENCES <table_name>
(<column_name1> ,
<column_name2>)

http://infogoal.com/sql/sql-add-foreignkey.htm

update query with join on two tables

Using table aliases in the join condition:

update addresses a
set cid = b.id 
from customers b 
where a.id = b.id

How to make a Qt Widget grow with the window size?

The accepted answer (its image) is wrong, at least now in QT5. Instead you should assign a layout to the root object/widget (pointing to the aforementioned image, it should be the MainWindow instead of centralWidget). Also note that you must have at least one QObject created beneath it for this to work. Do this and your ui will become responsive to window resizing.

MySQL set current date in a DATETIME field on insert

Using Now() is not a good idea. It only save the current time and date. It will not update the the current date and time, when you update your data. If you want to add the time once, The default value =Now() is best option. If you want to use timestamp. and want to update the this value, each time that row is updated. Then, trigger is best option to use.

  1. http://www.mysqltutorial.org/sql-triggers.aspx
  2. http://www.tutorialspoint.com/plsql/plsql_triggers.htm

These two toturial will help to implement the trigger.

how to remove the first two columns in a file using shell (awk, sed, whatever)

Its pretty straight forward to do it with only shell

while read A B C; do
echo "$C"
done < oldfile >newfile

"Eliminate render-blocking CSS in above-the-fold content"

How I got a 99/100 on Google Page Speed (for mobile)

TLDR: Compress and embed your entire css script between your <style></style> tags.


I've been chasing down that elusive 100/100 score for about a week now. Like you, the last remaining item was was eliminating "render-blocking css for above the fold content."

Surely there is an easy solve?? Nope. I tried out Filament group's loadCSS solution. Too much .js for my liking.

What about async attributes for css (like js)? They don't exist.

I was ready to give up. Then it dawned on me. If linking the script was blocking the render, what if I instead embedded my entire css in the head instead. That way there was nothing to block.

It seemed absolutely WRONG to embed 1263 lines of CSS in my style tag. But I gave it a whirl. I compressed it (and prefixed it) first using:

postcss -u autoprefixer --autoprefixer.browsers 'last 2 versions' -u cssnano --cssnano.autoprefixer false *.css -d min/ See the NPM postcss package.

Now it was just one LONG line of space-less css. I plopped the css in <style>your;great-wall-of-china-long;css;here</style> tags on my home page. Then I re-analyzed with page speed insights.

I went from 90/100 to 99/100 on mobile!!!

This goes against everything in me (and probably you). But it SOLVED the problem. I'm just using it on my home page for now and including the compressed css programmatically via a PHP include.

YMMV (your mileage may vary) pending on the length of your css. Google may ding you for too much above the fold content. But don't assume; test!

Notes

  1. I'm only doing this on my home page for now so people get a FAST render on my most important page.

  2. Your css won't get cached. I'm not too worried though. The second they hit another page on my site, the .css will get cached (see Note 1).

How to remove blank lines from a Unix file

awk 'NF' filename

awk 'NF > 0' filename

sed -i '/^$/d' filename

awk '!/^$/' filename

awk '/./' filename

The NF also removes lines containing only blanks or tabs, the regex /^$/ does not.

How to only find files in a given directory, and ignore subdirectories using bash

Is there any particular reason that you need to use find? You can just use ls to find files that match a pattern in a directory.

ls /dev/abc-*

If you do need to use find, you can use the -maxdepth 1 switch to only apply to the specified directory.

JQuery window scrolling event?

Check if the user has scrolled past the header ad, then display the footer ad.

if($(your header ad).position().top < 0) { $(your footer ad).show() }

Am I correct at what you are looking for?

NSCameraUsageDescription in iOS 10.0 runtime crash?

For those who are still getting the error even though you added proper keys into Info.plist:

Make sure you are adding the key into correct Info.plist. Newer version of xCode, apparently has 3 Info.plist.

One is under folder with your app's name which solved problem for me.

Second is under YourappnameTests and third one is under YourappnameUITests.

Hope it helps.

ASP.NET Button to redirect to another page

You can either do a Response.Redirect("YourPage.aspx"); or a Server.Transfer("YourPage.aspx"); on your button click event. So it's gonna be like the following:

protected void btnConfirm_Click(object sender, EventArgs e)
{
    Response.Redirect("YourPage.aspx");
    //or
    Server.Transfer("YourPage.aspx");
}

[] and {} vs list() and dict(), which is better?

A box bracket pair denotes one of a list object, or an index subscript, my_List[x].

A curly brace pair denotes a dictionary object.

a_list = ['on', 'off', 1, 2]

a_dict = { on: 1, off: 2 }

How to delete parent element using jQuery

You could also use this:

$(this)[0].parentNode.remove();

Practical uses of git reset --soft?

A great reason to use 'git reset --soft <sha1>' is to move HEAD in a bare repo.

If you try to use the --mixed or --hard option, you'll get an error since you're trying to modify and working tree and/or index that does not exist.

Note: You will need to do this directly from the bare repo.

Note Again: You will need to make sure the branch you want to reset in the bare repo is the active branch. If not, follow VonC's answer on how to update the active branch in a bare repo when you have direct access to the repo.

How do I add an existing directory tree to a project in Visual Studio?

You can use a symbolic link. This makes modifying the file in one project modify it in the other (as it's actually the same file).

To do this:

  1. Open cmd prompt as administrator
  2. mklink /d [current project directory name] [directory in other project it should point to]

This has it's drawbacks and pitfalls, but I use it on occasion for duplicate libraries that need different names.

Edit for Anoop: Steps to add to Visual Studio:

  1. Create link in the project folder using the steps above.
  2. In Visual Studio... select project in Solution Explorer.
  3. At the top of Solution Explorer... click the Show All Files button (may need to click it twice if already active).
  4. The link will now show in your project... right-click and choose Include In Project.

These are the steps I follow and works for a couple different projects.

How do I automatically update a timestamp in PostgreSQL

You'll need to write an insert trigger, and possible an update trigger if you want it to change when the record is changed. This article explains it quite nicely:

http://www.revsys.com/blog/2006/aug/04/automatically-updating-a-timestamp-column-in-postgresql/

CREATE OR REPLACE FUNCTION update_modified_column()   
RETURNS TRIGGER AS $$
BEGIN
    NEW.modified = now();
    RETURN NEW;   
END;
$$ language 'plpgsql';

Apply the trigger like this:

CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON customer FOR EACH ROW EXECUTE PROCEDURE  update_modified_column();

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

How do we change the URL of a working GitLab install?

You did everything correctly!

You might also change the email configuration, depending on if the email server is also the same server. The email configuration is in gitlab.yml for the mails sent by GitLab and also the admin-email.

How to determine CPU and memory consumption from inside a process?

Linux

In Linux, this information is available in the /proc file system. I'm not a big fan of the text file format used, as each Linux distribution seems to customize at least one important file. A quick look as the source to 'ps' reveals the mess.

But here is where to find the information you seek:

/proc/meminfo contains the majority of the system-wide information you seek. Here it looks like on my system; I think you are interested in MemTotal, MemFree, SwapTotal, and SwapFree:

Anderson cxc # more /proc/meminfo
MemTotal:      4083948 kB
MemFree:       2198520 kB
Buffers:         82080 kB
Cached:        1141460 kB
SwapCached:          0 kB
Active:        1137960 kB
Inactive:       608588 kB
HighTotal:     3276672 kB
HighFree:      1607744 kB
LowTotal:       807276 kB
LowFree:        590776 kB
SwapTotal:     2096440 kB
SwapFree:      2096440 kB
Dirty:              32 kB
Writeback:           0 kB
AnonPages:      523252 kB
Mapped:          93560 kB
Slab:            52880 kB
SReclaimable:    24652 kB
SUnreclaim:      28228 kB
PageTables:       2284 kB
NFS_Unstable:        0 kB
Bounce:              0 kB
CommitLimit:   4138412 kB
Committed_AS:  1845072 kB
VmallocTotal:   118776 kB
VmallocUsed:      3964 kB
VmallocChunk:   112860 kB
HugePages_Total:     0
HugePages_Free:      0
HugePages_Rsvd:      0
Hugepagesize:     2048 kB

For CPU utilization, you have to do a little work. Linux makes available overall CPU utilization since system start; this probably isn't what you are interested in. If you want to know what the CPU utilization was for the last second, or 10 seconds, then you need to query the information and calculate it yourself.

The information is available in /proc/stat, which is documented pretty well at http://www.linuxhowtos.org/System/procstat.htm; here is what it looks like on my 4-core box:

Anderson cxc #  more /proc/stat
cpu  2329889 0 2364567 1063530460 9034 9463 96111 0
cpu0 572526 0 636532 265864398 2928 1621 6899 0
cpu1 590441 0 531079 265949732 4763 351 8522 0
cpu2 562983 0 645163 265796890 682 7490 71650 0
cpu3 603938 0 551790 265919440 660 0 9040 0
intr 37124247
ctxt 50795173133
btime 1218807985
processes 116889
procs_running 1
procs_blocked 0

First, you need to determine how many CPUs (or processors, or processing cores) are available in the system. To do this, count the number of 'cpuN' entries, where N starts at 0 and increments. Don't count the 'cpu' line, which is a combination of the cpuN lines. In my example, you can see cpu0 through cpu3, for a total of 4 processors. From now on, you can ignore cpu0..cpu3, and focus only on the 'cpu' line.

Next, you need to know that the fourth number in these lines is a measure of idle time, and thus the fourth number on the 'cpu' line is the total idle time for all processors since boot time. This time is measured in Linux "jiffies", which are 1/100 of a second each.

But you don't care about the total idle time; you care about the idle time in a given period, e.g., the last second. Do calculate that, you need to read this file twice, 1 second apart.Then you can do a diff of the fourth value of the line. For example, if you take a sample and get:

cpu  2330047 0 2365006 1063853632 9035 9463 96114 0

Then one second later you get this sample:

cpu  2330047 0 2365007 1063854028 9035 9463 96114 0

Subtract the two numbers, and you get a diff of 396, which means that your CPU had been idle for 3.96 seconds out of the last 1.00 second. The trick, of course, is that you need to divide by the number of processors. 3.96 / 4 = 0.99, and there is your idle percentage; 99% idle, and 1% busy.

In my code, I have a ring buffer of 360 entries, and I read this file every second. That lets me quickly calculate the CPU utilization for 1 second, 10 seconds, etc., all the way up to 1 hour.

For the process-specific information, you have to look in /proc/pid; if you don't care abut your pid, you can look in /proc/self.

CPU used by your process is available in /proc/self/stat. This is an odd-looking file consisting of a single line; for example:

19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2
 7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364
8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0

The important data here are the 13th and 14th tokens (0 and 770 here). The 13th token is the number of jiffies that the process has executed in user mode, and the 14th is the number of jiffies that the process has executed in kernel mode. Add the two together, and you have its total CPU utilization.

Again, you will have to sample this file periodically, and calculate the diff, in order to determine the process's CPU usage over time.

Edit: remember that when you calculate your process's CPU utilization, you have to take into account 1) the number of threads in your process, and 2) the number of processors in the system. For example, if your single-threaded process is using only 25% of the CPU, that could be good or bad. Good on a single-processor system, but bad on a 4-processor system; this means that your process is running constantly, and using 100% of the CPU cycles available to it.

For the process-specific memory information, you ahve to look at /proc/self/status, which looks like this:

Name:   whatever
State:  S (sleeping)
Tgid:   19340
Pid:    19340
PPid:   19115
TracerPid:      0
Uid:    0       0       0       0
Gid:    0       0       0       0
FDSize: 256
Groups: 0 1 2 3 4 6 10 11 20 26 27
VmPeak:   676252 kB
VmSize:   651352 kB
VmLck:         0 kB
VmHWM:    420300 kB
VmRSS:    420296 kB
VmData:   581028 kB
VmStk:       112 kB
VmExe:     11672 kB
VmLib:     76608 kB
VmPTE:      1244 kB
Threads:        77
SigQ:   0/36864
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: fffffffe7ffbfeff
SigIgn: 0000000010001000
SigCgt: 20000001800004fc
CapInh: 0000000000000000
CapPrm: 00000000ffffffff
CapEff: 00000000fffffeff
Cpus_allowed:   0f
Mems_allowed:   1
voluntary_ctxt_switches:        6518
nonvoluntary_ctxt_switches:     6598

The entries that start with 'Vm' are the interesting ones:

  • VmPeak is the maximum virtual memory space used by the process, in kB (1024 bytes).
  • VmSize is the current virtual memory space used by the process, in kB. In my example, it's pretty large: 651,352 kB, or about 636 megabytes.
  • VmRss is the amount of memory that have been mapped into the process' address space, or its resident set size. This is substantially smaller (420,296 kB, or about 410 megabytes). The difference: my program has mapped 636 MB via mmap(), but has only accessed 410 MB of it, and thus only 410 MB of pages have been assigned to it.

The only item I'm not sure about is Swapspace currently used by my process. I don't know if this is available.

How to run Maven from another directory (without cd to project dir)?

You can try this:

pushd ../
maven install [...]
popd

Install numpy on python3.3 - Install pip for python3

From the terminal run:

  sudo apt-get install python3-numpy

This package contains Numpy for Python 3.

For scipy:

 sudo apt-get install python3-scipy

For for plotting graphs use pylab:

 sudo apt-get install python3-matplotlib

Find all zero-byte files in directory and subdirectories

No, you don't have to bother grep.

find $dir -size 0 ! -name "*.xml"

How to handle windows file upload using Selenium WebDriver?

There is a simpler way to solve this then what Slanec described. Hes solution works when you are using an English keyboard, if not you will have a hard time trying to "map" the key for special characters.

Instead of robot.keyPress and robot.keyRelease every single key you can use Toolkit to copy the String to the clipboard and then paste it.

    StringSelection s = new StringSelection("Path to the file");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(s, null);
    Robot robot = new Robot();
    robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
    robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER);
    robot.keyPress(java.awt.event.KeyEvent.VK_CONTROL);
    robot.keyPress(java.awt.event.KeyEvent.VK_V);
    robot.keyRelease(java.awt.event.KeyEvent.VK_CONTROL);
    Thread.sleep(3000);
    robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);

How should we manage jdk8 stream for null values

If you just want to filter null values out of a stream, you can simply use a method reference to java.util.Objects.nonNull(Object). From its documentation:

This method exists to be used as a Predicate, filter(Objects::nonNull)

For example:

List<String> list = Arrays.asList( null, "Foo", null, "Bar", null, null);

list.stream()
    .filter( Objects::nonNull )  // <-- Filter out null values
    .forEach( System.out::println );

This will print:

Foo
Bar

Are there any log file about Windows Services Status?

The most likely place to find this sort of information is in the event viewer (under Administrative tools in XP or run eventvwr) This is where most services log warnings errors etc.

Remove all elements contained in another array

Proper way to remove all elements contained in another array is to make source array same object by remove only elements:

Array.prototype.removeContained = function(array) {
  var i, results;
  i = this.length;
  results = [];
  while (i--) {
    if (array.indexOf(this[i]) !== -1) {
      results.push(this.splice(i, 1));
    }
  }
  return results;
};

Or CoffeeScript equivalent:

Array.prototype.removeContained = (array) ->
  i = @length
  @splice i, 1 while i-- when array.indexOf(@[i]) isnt -1

Testing inside chrome dev tools:

19:33:04.447 a=1
19:33:06.354 b=2
19:33:07.615 c=3
19:33:09.981 arr = [a,b,c]
19:33:16.460 arr1 = arr

19:33:20.317 arr1 === arr
19:33:20.331 true

19:33:43.592 arr.removeContained([a,c])
19:33:52.433 arr === arr1
19:33:52.438 true

Using Angular framework is the best way to keep pointer to source object when you update collections without large amount of watchers and reloads.

Can I have H2 autocreate a schema in an in-memory database?

If you are using spring with application.yml the following will work for you

spring: datasource: url: jdbc:h2:mem:mydb;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS calendar

How do I implement a callback in PHP?

One nifty trick that I've recently found is to use PHP's create_function() to create an anonymous/lambda function for one-shot use. It's useful for PHP functions like array_map(), preg_replace_callback(), or usort() that use callbacks for custom processing. It looks pretty much like it does an eval() under the covers, but it's still a nice functional-style way to use PHP.

Generate sql insert script from excel worksheet

I have a reliable way to generate SQL inserts batly,and you can modify partial parameters in processing.It helps me a lot in my work, for example, copy one hundreds data to database with incompatible structure and fields count. IntellIJ DataGrip , the powerful tool i use. DG can batly receive data from WPS office or MS Excel by column or line. after copying, DG can export data as SQL inserts.

I got error "The DELETE statement conflicted with the REFERENCE constraint"

You are trying to delete a row that is referenced by another row (possibly in another table).

You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.

Docker remove <none> TAG images

docker images | grep none | awk '{ print $3; }' | xargs docker rmi

You can try this simply

How to pass a JSON array as a parameter in URL

I know this could be a later post, but, for new visitors I will share my solution, as the OP was asking for a way to pass a JSON object via GET (not POST as suggested in other answers).

  1. Take the JSON object and convert it to string (JSON.stringify)
  2. Take the string and encode it in Base64 (you can find some useful info on this here
  3. Append it to the URL and make the GET call
  4. Reverse the process. decode and parse it into an object

I have used this in some cases where I only can do GET calls and it works. Also, this solution is practically cross language.

How to check if any fields in a form are empty in php

Specify POST method in form
<form name="registrationform" action="register.php" method="post">


your form code

</form>

"Invalid signature file" when attempting to run a .jar

Compare the folder META-INF in new jar with old jar (before you added new libraries). It is possibility that there will be new files. If yes, you can remove them. It should helps. Regards, 999michal

How to check if a string "StartsWith" another string?

Another alternative with .lastIndexOf:

haystack.lastIndexOf(needle, 0) === 0

This looks backwards through haystack for an occurrence of needle starting from index 0 of haystack. In other words, it only checks if haystack starts with needle.

In principle, this should have performance advantages over some other approaches:

  • It doesn't search the entire haystack.
  • It doesn't create a new temporary string and then immediately discard it.

How to copy a collection from one database to another in MongoDB

Using pymongo, you need to have both databases on same mongod, I did the following:


db = original database
db2 = database to be copied to

cursor = db["<collection to copy from>"].find()
for data in cursor:
    db2["<new collection>"].insert(data)

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

There's one big difference between CLOCK_REALTIME and MONOTONIC. CLOCK_REALTIME can jump forward or backward according to NTP. By default, NTP allows the clock rate to be speeded up or slowed down by up to 0.05%, but NTP cannot cause the monotonic clock to jump forward or backward.

How to ping multiple servers and return IP address and Hostnames using batch script?

Parsing pingtest.txt for each HOST name and result with batch is difficult because the name and result are on different lines.

It is much easier to test the result (the returned error code) of each PING command directly instead of redirecting to a file. It is also more efficient to enclose the entire construct in parens and redirect the final output just once.

>result.txt (
  for /f %%i in (testservers.txt) do ping -n 1 %%i >nul && echo %%i UP||echo %%i DOWN
)

mongodb service is not starting up

just re-installed mongo and it worked. No collections lost. Easiest solution atleast for me

How do you detect where two line segments intersect?

Finding the correct intersection of two line segments is a non-trivial task with lots of edge cases. Here's a well documented, working and tested solution in Java.

In essence, there are three things that can happen when finding the intersection of two line segments:

  1. The segments do not intersect

  2. There is a unique intersection point

  3. The intersection is another segment

NOTE: In the code, I assume that a line segment (x1, y1), (x2, y2) with x1 = x2 and y1 = y2 is a valid line segment. Mathematically speaking, a line segment consists of distinct points, but I am allowing segments to be points in this implementation for completeness.

Code is taken from my github repo

/**
 * This snippet finds the intersection of two line segments.
 * The intersection may either be empty, a single point or the
 * intersection is a subsegment there's an overlap.
 */

import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;

import java.util.ArrayList;
import java.util.List;

public class LineSegmentLineSegmentIntersection {

  // Small epsilon used for double value comparison.
  private static final double EPS = 1e-5;

  // 2D Point class.
  public static class Pt {
    double x, y;
    public Pt(double x, double y) {
      this.x = x; 
      this.y = y;
    }
    public boolean equals(Pt pt) {
      return abs(x - pt.x) < EPS && abs(y - pt.y) < EPS;
    }
  }

  // Finds the orientation of point 'c' relative to the line segment (a, b)
  // Returns  0 if all three points are collinear.
  // Returns -1 if 'c' is clockwise to segment (a, b), i.e right of line formed by the segment.
  // Returns +1 if 'c' is counter clockwise to segment (a, b), i.e left of line
  // formed by the segment.
  public static int orientation(Pt a, Pt b, Pt c) {
    double value = (b.y - a.y) * (c.x - b.x) - 
                   (b.x - a.x) * (c.y - b.y);
    if (abs(value) < EPS) return 0;
    return (value > 0) ? -1 : +1;
  }

  // Tests whether point 'c' is on the line segment (a, b).
  // Ensure first that point c is collinear to segment (a, b) and
  // then check whether c is within the rectangle formed by (a, b)
  public static boolean pointOnLine(Pt a, Pt b, Pt c) {
    return orientation(a, b, c) == 0 && 
           min(a.x, b.x) <= c.x && c.x <= max(a.x, b.x) && 
           min(a.y, b.y) <= c.y && c.y <= max(a.y, b.y);
  }

  // Determines whether two segments intersect.
  public static boolean segmentsIntersect(Pt p1, Pt p2, Pt p3, Pt p4) {

    // Get the orientation of points p3 and p4 in relation
    // to the line segment (p1, p2)
    int o1 = orientation(p1, p2, p3);
    int o2 = orientation(p1, p2, p4);
    int o3 = orientation(p3, p4, p1);
    int o4 = orientation(p3, p4, p2);

    // If the points p1, p2 are on opposite sides of the infinite
    // line formed by (p3, p4) and conversly p3, p4 are on opposite
    // sides of the infinite line formed by (p1, p2) then there is
    // an intersection.
    if (o1 != o2 && o3 != o4) return true;

    // Collinear special cases (perhaps these if checks can be simplified?)
    if (o1 == 0 && pointOnLine(p1, p2, p3)) return true;
    if (o2 == 0 && pointOnLine(p1, p2, p4)) return true;
    if (o3 == 0 && pointOnLine(p3, p4, p1)) return true;
    if (o4 == 0 && pointOnLine(p3, p4, p2)) return true;

    return false;
  }

  public static List<Pt> getCommonEndpoints(Pt p1, Pt p2, Pt p3, Pt p4) {

    List<Pt> points = new ArrayList<>();

    if (p1.equals(p3)) {
      points.add(p1);
      if (p2.equals(p4)) points.add(p2);

    } else if (p1.equals(p4)) {
      points.add(p1);
      if (p2.equals(p3)) points.add(p2);

    } else if (p2.equals(p3)) {
      points.add(p2);
      if (p1.equals(p4)) points.add(p1);

    } else if (p2.equals(p4)) {
      points.add(p2);
      if (p1.equals(p3)) points.add(p1);
    }

    return points;
  }

  // Finds the intersection point(s) of two line segments. Unlike regular line 
  // segments, segments which are points (x1 = x2 and y1 = y2) are allowed.
  public static Pt[] lineSegmentLineSegmentIntersection(Pt p1, Pt p2, Pt p3, Pt p4) {

    // No intersection.
    if (!segmentsIntersect(p1, p2, p3, p4)) return new Pt[]{};

    // Both segments are a single point.
    if (p1.equals(p2) && p2.equals(p3) && p3.equals(p4))
      return new Pt[]{p1};

    List<Pt> endpoints = getCommonEndpoints(p1, p2, p3, p4);
    int n = endpoints.size();

    // One of the line segments is an intersecting single point.
    // NOTE: checking only n == 1 is insufficient to return early
    // because the solution might be a sub segment.
    boolean singleton = p1.equals(p2) || p3.equals(p4);
    if (n == 1 && singleton) return new Pt[]{endpoints.get(0)};

    // Segments are equal.
    if (n == 2) return new Pt[]{endpoints.get(0), endpoints.get(1)};

    boolean collinearSegments = (orientation(p1, p2, p3) == 0) && 
                                (orientation(p1, p2, p4) == 0);

    // The intersection will be a sub-segment of the two
    // segments since they overlap each other.
    if (collinearSegments) {

      // Segment #2 is enclosed in segment #1
      if (pointOnLine(p1, p2, p3) && pointOnLine(p1, p2, p4))
        return new Pt[]{p3, p4};

      // Segment #1 is enclosed in segment #2
      if (pointOnLine(p3, p4, p1) && pointOnLine(p3, p4, p2))
        return new Pt[]{p1, p2};

      // The subsegment is part of segment #1 and part of segment #2.
      // Find the middle points which correspond to this segment.
      Pt midPoint1 = pointOnLine(p1, p2, p3) ? p3 : p4;
      Pt midPoint2 = pointOnLine(p3, p4, p1) ? p1 : p2;

      // There is actually only one middle point!
      if (midPoint1.equals(midPoint2)) return new Pt[]{midPoint1};

      return new Pt[]{midPoint1, midPoint2};
    }

    /* Beyond this point there is a unique intersection point. */

    // Segment #1 is a vertical line.
    if (abs(p1.x - p2.x) < EPS) {
      double m = (p4.y - p3.y) / (p4.x - p3.x);
      double b = p3.y - m * p3.x;
      return new Pt[]{new Pt(p1.x, m * p1.x + b)};
    }

    // Segment #2 is a vertical line.
    if (abs(p3.x - p4.x) < EPS) {
      double m = (p2.y - p1.y) / (p2.x - p1.x);
      double b = p1.y - m * p1.x;
      return new Pt[]{new Pt(p3.x, m * p3.x + b)};
    }

    double m1 = (p2.y - p1.y) / (p2.x - p1.x);
    double m2 = (p4.y - p3.y) / (p4.x - p3.x);
    double b1 = p1.y - m1 * p1.x;
    double b2 = p3.y - m2 * p3.x;
    double x = (b2 - b1) / (m1 - m2);
    double y = (m1 * b2 - m2 * b1) / (m1 - m2);

    return new Pt[]{new Pt(x, y)};
  }

}

Here is a simple usage example:

  public static void main(String[] args) {

    // Segment #1 is (p1, p2), segment #2 is (p3, p4)
    Pt p1, p2, p3, p4;

    p1 = new Pt(-2, 4); p2 = new Pt(3, 3);
    p3 = new Pt(0, 0);  p4 = new Pt(2, 4);
    Pt[] points = lineSegmentLineSegmentIntersection(p1, p2, p3, p4);
    Pt point = points[0];

    // Prints: (1.636, 3.273)
    System.out.printf("(%.3f, %.3f)\n", point.x, point.y);

    p1 = new Pt(-10, 0); p2 = new Pt(+10, 0);
    p3 = new Pt(-5, 0);  p4 = new Pt(+5, 0);
    points = lineSegmentLineSegmentIntersection(p1, p2, p3, p4);
    Pt point1 = points[0], point2 = points[1];

    // Prints: (-5.000, 0.000) (5.000, 0.000)
    System.out.printf("(%.3f, %.3f) (%.3f, %.3f)\n", point1.x, point1.y, point2.x, point2.y);
  }

can't access mysql from command line mac

On OSX 10.11, you can sudo nano /etc/paths and add the path(s) you want here, one per line. Way simpler than figuring which of ~/.bashrc, /etc/profile, '~/.bash_profile` etc... you should add to. Besides, why export and append $PATH to itself when you can just go and modify PATH directly...?

jQuery Ajax requests are getting cancelled without being sent

I had the cancelled in Firefox. Some ajax-calls working perfectly fine for me, but it failed for the coworker who actually had to use it.

When I checked this out via the Chrome tricks mentioned above, I found nothing suspicious. When checking it in firebug, it showed the 'loading' animation after the two mallicous calls, and no result tab.

The solution was mega simple: go to history, find the website, rightclick -> forget website.
Forget, not delete.

After that, no problems anymore. My guess is it has something to do with the .htaccess.

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

How to extract a single value from JSON response?

Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist

You could also add some logic to test for the key if you want as well.

if 'name' in resp_dict:
    resp_dict['name']
else:
    # do something else here.

Upload Image using POST form data in Python-requests

I confronted similar issue when I wanted to post image file to a rest API from Python (Not wechat API though). The solution for me was to use 'data' parameter to post the file in binary data instead of 'files'. Requests API reference

data = open('your_image.png','rb').read()
r = requests.post(your_url,data=data)

Hope this works for your case.

How to edit a JavaScript alert box title?

I had a similar issue when I wanted to change the box title and button title of the default confirm box. I have gone for the Jquery Ui dialog plugin http://jqueryui.com/dialog/#modal-confirmation

When I had the following:

function testConfirm() {
  if (confirm("Are you sure you want to delete?")) {
    //some stuff
  }
}

I have changed it to:

function testConfirm() {

  var $dialog = $('<div></div>')
    .html("Are you sure you want to delete?")
    .dialog({
      resizable: false,
      title: "Confirm Deletion",
      modal: true,
      buttons: {
        Cancel: function() {
          $(this).dialog("close");
        },
        "Delete": function() {
          //some stuff
          $(this).dialog("close");
        }
      }
    });

  $dialog.dialog('open');
}

Can be seen working here https://jsfiddle.net/5aua4wss/2/

Hope that helps.

CSS set li indent

Also try:

ul {
  list-style-position: inside;
}

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

We can try by using latest jQuery library. I got the same issue. I used jQuery-1.4.2.min before and getting the error. After that I used version 1.9.1 and it works. Thanks

Difference between return and exit in Bash functions

If you convert a Bash script into a function, you typically replace exit N with return N. The code that calls the function will treat the return value the same as it would an exit code from a subprocess.

Using exit inside the function will force the entire script to end.

Bootstrap 3 Collapse show state with Chevron icon

Thanks to biggates and steakpi. As answer of question Dreamonic, I made a little changes to make all headers clickable (not only title string and gluphs) and took off underline from link. To force an icons appear on same line I added h4 at the end of CSS instructions. Here is the modified code:

<div class="panel-group" id="accordion">
  <div class="panel panel-default">
    <div class="panel-heading">      
        <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
          <h4 class="panel-title">Collapsible Group Item #1</h4>
        </a>      
    </div>
    <div id="collapseOne" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading">      
        <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">
          <h4 class="panel-title">Collapsible Group Item #2</h4>
        </a>      
    </div>
    <div id="collapseTwo" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading">      
        <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
          <h4 class="panel-title">Collapsible Group Item #3</h4>
        </a>      
    </div>
    <div id="collapseThree" class="panel-collapse collapse">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>

And the modified CSS:

.panel-heading .accordion-toggle h4:after {
    /* symbol for "opening" panels */
    font-family: 'Glyphicons Halflings';  
    content: "\e114";    
    float: right;        
    color: grey;        
    overflow: no-display;
}
.panel-heading .accordion-toggle.collapsed h4:after {
    /* symbol for "collapsed" panels */
    content: "\e080";    
}
a.accordion-toggle{
    text-decoration: none;
}

Razor View Engine : An expression tree may not contain a dynamic operation

In this link explain about @model, see a excerpt:

@model (lowercase "m") is a reserved keyword in Razor views to declare the model type at the top of your view. You have put the namespace too, e.g.: @model MyNamespace.Models.MyModel

Later in the file, you can reference the attribute you want with @Model.Attribute (uppercase "M").

How to get the indices list of all NaN value in numpy array?

np.isnan combined with np.argwhere

x = np.array([[1,2,3,4],
              [2,3,np.nan,5],
              [np.nan,5,2,3]])
np.argwhere(np.isnan(x))

output:

array([[1, 2],
       [2, 0]])

How to plot a histogram using Matplotlib in Python with a list of data?

If you want a histogram, you don't need to attach any 'names' to x-values, as on x-axis you would have data bins:

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

np.random.seed(42)
x = np.random.normal(size=1000)

plt.hist(x, density=True, bins=30)  # density=False would make counts
plt.ylabel('Probability')
plt.xlabel('Data');

enter image description here

Note, the number of bins=30 was chosen arbitrarily, and there is Freedman–Diaconis rule to be more scientific in choosing the "right" bin width:

![enter image description here , where IQR is Interquartile range and n is total number of datapoints to plot

So, according to this rule one may calculate number of bins as:

q25, q75 = np.percentile(x,[.25,.75])
bin_width = 2*(q75 - q25)*len(x)**(-1/3)
bins = round((x.max() - x.min())/bin_width)
print("Freedman–Diaconis number of bins:", bins)
plt.hist(x, bins = bins);

Freedman–Diaconis number of bins: 82

enter image description here

And finally you can make your histogram a bit fancier with PDF line, titles, and legend:

import scipy.stats as st

plt.hist(x, density=True, bins=82, label="Data")
mn, mx = plt.xlim()
plt.xlim(mn, mx)
kde_xs = np.linspace(mn, mx, 300)
kde = st.gaussian_kde(x)
plt.plot(kde_xs, kde.pdf(kde_xs), label="PDF")
plt.legend(loc="upper left")
plt.ylabel('Probability')
plt.xlabel('Data')
plt.title("Histogram");

enter image description here

However, if you have limited number of data points, like in OP, a bar plot would make more sense to represent your data. Then you may attach labels to x-axis:

x = np.arange(3)
plt.bar(x, height=[1,2,3])
plt.xticks(x, ['a','b','c'])

enter image description here

How to easily get network path to the file you are working on?

I found a way to display the Document Location module in Office 2010.

File -> Options -> Quick Access Toolbar

From the Choose commands list select All Commands find "Document Location" press the "Add>>" button.

press OK.

Viola, the file path is at the top of your 2010 office document.

how to draw smooth curve through N points using javascript HTML5 canvas?

I decide to add on, rather than posting my solution to another post. Below are the solution that I build, may not be perfect, but so far the output are good.

Important: it will pass through all the points!

If you have any idea, to make it better, please share to me. Thanks.

Here are the comparison of before after:

enter image description here

Save this code to HTML to test it out.

_x000D_
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    <body>_x000D_
     <canvas id="myCanvas" width="1200" height="700" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>_x000D_
     <script>_x000D_
      var cv = document.getElementById("myCanvas");_x000D_
      var ctx = cv.getContext("2d");_x000D_
    _x000D_
      function gradient(a, b) {_x000D_
       return (b.y-a.y)/(b.x-a.x);_x000D_
      }_x000D_
    _x000D_
      function bzCurve(points, f, t) {_x000D_
       //f = 0, will be straight line_x000D_
       //t suppose to be 1, but changing the value can control the smoothness too_x000D_
       if (typeof(f) == 'undefined') f = 0.3;_x000D_
       if (typeof(t) == 'undefined') t = 0.6;_x000D_
    _x000D_
       ctx.beginPath();_x000D_
       ctx.moveTo(points[0].x, points[0].y);_x000D_
    _x000D_
       var m = 0;_x000D_
       var dx1 = 0;_x000D_
       var dy1 = 0;_x000D_
    _x000D_
       var preP = points[0];_x000D_
       for (var i = 1; i < points.length; i++) {_x000D_
        var curP = points[i];_x000D_
        nexP = points[i + 1];_x000D_
        if (nexP) {_x000D_
         m = gradient(preP, nexP);_x000D_
         dx2 = (nexP.x - curP.x) * -f;_x000D_
         dy2 = dx2 * m * t;_x000D_
        } else {_x000D_
         dx2 = 0;_x000D_
         dy2 = 0;_x000D_
        }_x000D_
        ctx.bezierCurveTo(preP.x - dx1, preP.y - dy1, curP.x + dx2, curP.y + dy2, curP.x, curP.y);_x000D_
        dx1 = dx2;_x000D_
        dy1 = dy2;_x000D_
        preP = curP;_x000D_
       }_x000D_
       ctx.stroke();_x000D_
      }_x000D_
    _x000D_
      // Generate random data_x000D_
      var lines = [];_x000D_
      var X = 10;_x000D_
      var t = 40; //to control width of X_x000D_
      for (var i = 0; i < 100; i++ ) {_x000D_
       Y = Math.floor((Math.random() * 300) + 50);_x000D_
       p = { x: X, y: Y };_x000D_
       lines.push(p);_x000D_
       X = X + t;_x000D_
      }_x000D_
    _x000D_
      //draw straight line_x000D_
      ctx.beginPath();_x000D_
      ctx.setLineDash([5]);_x000D_
      ctx.lineWidth = 1;_x000D_
      bzCurve(lines, 0, 1);_x000D_
    _x000D_
      //draw smooth line_x000D_
      ctx.setLineDash([0]);_x000D_
      ctx.lineWidth = 2;_x000D_
      ctx.strokeStyle = "blue";_x000D_
      bzCurve(lines, 0.3, 1);_x000D_
     </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

generate days from date range

For anyone who wants this as a saved view (MySQL doesn't support nested select statements in views):

create view zero_to_nine as
    select 0 as n union all 
    select 1 union all 
    select 2 union all 
    select 3 union all 
    select 4 union all 
    select 5 union all 
    select 6 union all 
    select 7 union all 
    select 8 union all 
    select 9;

create view date_range as
    select curdate() - INTERVAL (a.n + (10 * b.n) + (100 * c.n)) DAY as date
    from zero_to_nine as a
    cross join zero_to_nine as b
    cross join zero_to_nine as c;

You can then do

select * from date_range

to get

date
---
2017-06-06
2017-06-05
2017-06-04
2017-06-03
2017-06-02
...

APT command line interface-like yes/no input?

I modified fmark's answer to by python 2/3 compatible more pythonic.

See ipython's utility module if you are interested in something with more error handling

# PY2/3 compatibility
from __future__ import print_function
# You could use the six package for this
try:
    input_ = raw_input
except NameError:
    input_ = input

def query_yes_no(question, default=True):
    """Ask a yes/no question via standard input and return the answer.

    If invalid input is given, the user will be asked until
    they acutally give valid input.

    Args:
        question(str):
            A question that is presented to the user.
        default(bool|None):
            The default value when enter is pressed with no value.
            When None, there is no default value and the query
            will loop.
    Returns:
        A bool indicating whether user has entered yes or no.

    Side Effects:
        Blocks program execution until valid input(y/n) is given.
    """
    yes_list = ["yes", "y"]
    no_list = ["no", "n"]

    default_dict = {  # default => prompt default string
        None: "[y/n]",
        True: "[Y/n]",
        False: "[y/N]",
    }

    default_str = default_dict[default]
    prompt_str = "%s %s " % (question, default_str)

    while True:
        choice = input_(prompt_str).lower()

        if not choice and default is not None:
            return default
        if choice in yes_list:
            return True
        if choice in no_list:
            return False

        notification_str = "Please respond with 'y' or 'n'"
        print(notification_str)

jQuery Get Selected Option From Dropdown

$('nameofDropDownList').prop('selectedIndex', whateverNumberasInt);

Imagine the DDL as an array with indexes, you are selecting one index. Choose the one which you want to set it to with your JS.

How to rename a table in SQL Server?

When using sp_rename which works like in above answers, check also which objects are affected after renaming, that reference that table, because you need to change those too

I took a code example for table dependencies at Pinal Dave's blog here

USE AdventureWorks
GO
SELECT
referencing_schema_name = SCHEMA_NAME(o.SCHEMA_ID),
referencing_object_name = o.name,
referencing_object_type_desc = o.type_desc,
referenced_schema_name,
referenced_object_name = referenced_entity_name,
referenced_object_type_desc = o1.type_desc,
referenced_server_name, referenced_database_name
--,sed.* -- Uncomment for all the columns
FROM
sys.sql_expression_dependencies sed
INNER JOIN
sys.objects o ON sed.referencing_id = o.[object_id]
LEFT OUTER JOIN
sys.objects o1 ON sed.referenced_id = o1.[object_id]
WHERE
referenced_entity_name = 'Customer'

So, all these dependent objects needs to be updated also

Or use some add-in if you can, some of them have feature to rename object, and all depend,ent objects too

Best practice to run Linux service as a different user

Some things to watch out for:

  • As you mentioned, su will prompt for a password if you are already the target user
  • Similarly, setuid(2) will fail if you are already the target user (on some OSs)
  • setuid(2) does not install privileges or resource controls defined in /etc/limits.conf (Linux) or /etc/user_attr (Solaris)
  • If you go the setgid(2)/setuid(2) route, don't forget to call initgroups(3) -- more on this here

I generally use /sbin/su to switch to the appropriate user before starting daemons.

Can't find bundle for base name /Bundle, locale en_US

If you are running the .java file in Eclipse you need to add the resource path in the build path . after that you will not see this error

Java - Check if input is a positive integer, negative integer, natural number and so on.

If you really have to avoid operators then use Math.signum()

Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.

EDIT : As per the comments, this works for only double and float values. For integer values you can use the method:

Integer.signum(int i)

Java Returning method which returns arraylist?

Assuming you have something like so:

public class MyFirstClass {
   ...
   public ArrayList<Integer> myNumbers()    {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(11);
    numbers.add(3);
    return(numbers);
   }
   ...
}

You can call that method like so:

public class MySecondClass {
    ...
    MyFirstClass m1 = new MyFirstClass();
    List<Integer> myList = m1.myNumbers();
    ...
}

Since the method you are trying to call is not static, you will have to create an instance of the class which provides this method. Once you create the instance, you will then have access to the method.

Note, that in the code example above, I used this line: List<Integer> myList = m1.myNumbers();. This can be changed by the following: ArrayList<Integer> myList = m1.myNumbers();. However, it is usually recommended to program to an interface, and not to a concrete implementation, so my suggestion for the method you are using would be to do something like so:

public List<Integer> myNumbers()    {
    List<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(11);
    numbers.add(3);
    return(numbers);
   }

This will allow you to assign the contents of that list to whatever implements the List interface.

RegEx match open tags except XHTML self-contained tags

Here's the solution:

<?php
// here's the pattern:
$pattern = '/<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*(\/>|>)/';

// a string to parse:
$string = 'Hello, try clicking <a href="#paragraph">here</a>
    <br/>and check out.<hr />
    <h2>title</h2>
    <a name ="paragraph" rel= "I\'m an anchor"></a>
    Fine, <span title=\'highlight the "punch"\'>thanks<span>.
    <div class = "clear"></div>
    <br>';

// let's get the occurrences:
preg_match_all($pattern, $string, $matches, PREG_PATTERN_ORDER);

// print the result:
print_r($matches[0]);
?>

To test it deeply, I entered in the string auto-closing tags like:

  1. <hr />
  2. <br/>
  3. <br>

I also entered tags with:

  1. one attribute
  2. more than one attribute
  3. attributes which value is bound either into single quotes or into double quotes
  4. attributes containing single quotes when the delimiter is a double quote and vice versa
  5. "unpretty" attributes with a space before the "=" symbol, after it and both before and after it.

Should you find something which does not work in the proof of concept above, I am available in analyzing the code to improve my skills.

<EDIT> I forgot that the question from the user was to avoid the parsing of self-closing tags. In this case the pattern is simpler, turning into this:

$pattern = '/<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*>/';

The user @ridgerunner noticed that the pattern does not allow unquoted attributes or attributes with no value. In this case a fine tuning brings us the following pattern:

$pattern = '/<(\w+)(\s+(\w+)(\s*\=\s*(\'|"|)(.*?)\\5\s*)?)*\s*>/';

</EDIT>

Understanding the pattern

If someone is interested in learning more about the pattern, I provide some line:

  1. the first sub-expression (\w+) matches the tag name
  2. the second sub-expression contains the pattern of an attribute. It is composed by:
    1. one or more whitespaces \s+
    2. the name of the attribute (\w+)
    3. zero or more whitespaces \s* (it is possible or not, leaving blanks here)
    4. the "=" symbol
    5. again, zero or more whitespaces
    6. the delimiter of the attribute value, a single or double quote ('|"). In the pattern, the single quote is escaped because it coincides with the PHP string delimiter. This sub-expression is captured with the parentheses so it can be referenced again to parse the closure of the attribute, that's why it is very important.
    7. the value of the attribute, matched by almost anything: (.*?); in this specific syntax, using the greedy match (the question mark after the asterisk) the RegExp engine enables a "look-ahead"-like operator, which matches anything but what follows this sub-expression
    8. here comes the fun: the \4 part is a backreference operator, which refers to a sub-expression defined before in the pattern, in this case, I am referring to the fourth sub-expression, which is the first attribute delimiter found
    9. zero or more whitespaces \s*
    10. the attribute sub-expression ends here, with the specification of zero or more possible occurrences, given by the asterisk.
  3. Then, since a tag may end with a whitespace before the ">" symbol, zero or more whitespaces are matched with the \s* subpattern.
  4. The tag to match may end with a simple ">" symbol, or a possible XHTML closure, which makes use of the slash before it: (/>|>). The slash is, of course, escaped since it coincides with the regular expression delimiter.

Small tip: to better analyze this code it is necessary looking at the source code generated since I did not provide any HTML special characters escaping.

SQL how to make null values come last when sorting ascending

If you're using MariaDB, they mention the following in the NULL Values documentation.

Ordering

When you order by a field that may contain NULL values, any NULLs are considered to have the lowest value. So ordering in DESC order will see the NULLs appearing last. To force NULLs to be regarded as highest values, one can add another column which has a higher value when the main field is NULL. Example:

SELECT col1 FROM tab ORDER BY ISNULL(col1), col1;

Descending order, with NULLs first:

SELECT col1 FROM tab ORDER BY IF(col1 IS NULL, 0, 1), col1 DESC;

All NULL values are also regarded as equivalent for the purposes of the DISTINCT and GROUP BY clauses.

The above shows two ways to order by NULL values, you can combine these with the ASC and DESC keywords as well. For example the other way to get the NULL values first would be:

SELECT col1 FROM tab ORDER BY ISNULL(col1) DESC, col1;
--                                         ^^^^

What is the backslash character (\\)?

If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.

Console.WriteLine(@"Mango \ Nightangle");

Don't you just wish Java had something like this ;-)

How to convert a pymongo.cursor.Cursor into a dict?

to_dict() Convert a SON document to a normal Python dictionary instance.

This is trickier than just dict(...) because it needs to be recursive.

http://api.mongodb.org/python/current/api/bson/son.html

How to perform a real time search and filter on a HTML table

Datatable JS plugin is also one good alternate to accomedate search feature for html table

var table = $('#example').DataTable();

// #myInput is a <input type="text"> element
$('#myInput').on( 'keyup', function () {
    table.search( this.value ).draw();
} );

https://datatables.net/examples/basic_init/zero_configuration.html

Python method for reading keypress?

I was also trying to achieve this. From above codes, what I understood was that you can call getch() function multiple times in order to get both bytes getting from the function. So the ord() function is not necessary if you are just looking to use with byte objects.

while True :
    if m.kbhit() :
        k = m.getch()
        if b'\r' == k :
            break
        elif k == b'\x08'or k == b'\x1b':
            # b'\x08' => BACKSPACE
            # b'\x1b' => ESC
            pass
        elif k == b'\xe0' or k == b'\x00':
            k = m.getch()
            if k in [b'H',b'M',b'K',b'P',b'S',b'\x08']:
                # b'H' => UP ARROW
                # b'M' => RIGHT ARROW
                # b'K' => LEFT ARROW
                # b'P' => DOWN ARROW
                # b'S' => DELETE
                pass
            else:
                print(k.decode(),end='')
        else:
            print(k.decode(),end='')

This code will work print any key until enter key is pressed in CMD or IDE (I was using VS CODE) You can customize inside the if for specific keys if needed

How to pass anonymous types as parameters?

If you know, that your results implements a certain interface you could use the interface as datatype:

public void LogEmployees<T>(IEnumerable<T> list)
{
    foreach (T item in list)
    {

    }
}

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

What are queues in jQuery?

This thread helped me a lot with my problem, but I've used $.queue in a different way and thought I would post what I came up with here. What I needed was a sequence of events (frames) to be triggered, but the sequence to be built dynamically. I have a variable number of placeholders, each of which should contain an animated sequence of images. The data is held in an array of arrays, so I loop through the arrays to build each sequence for each of the placeholders like this:

/* create an empty queue */
var theQueue = $({});
/* loop through the data array */
for (var i = 0; i < ph.length; i++) {
    for (var l = 0; l < ph[i].length; l++) {
        /* create a function which swaps an image, and calls the next function in the queue */
        theQueue.queue("anim", new Function("cb", "$('ph_"+i+"' img').attr('src', '/images/"+i+"/"+l+".png');cb();"));
        /* set the animation speed */
        theQueue.delay(200,'anim');
    }
}
/* start the animation */
theQueue.dequeue('anim');

This is a simplified version of the script I have arrived at, but should show the principle - when a function is added to the queue, it is added using the Function constructor - this way the function can be written dynamically using variables from the loop(s). Note the way the function is passed the argument for the next() call, and this is invoked at the end. The function in this case has no time dependency (it doesn't use $.fadeIn or anything like that), so I stagger the frames using $.delay.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

Just had a similar issue when I ran pod install, I saw the following warnings/errors (related to CLANG_CXX_LIBRARY):

The Error/Warning from Cocoapods

[!] The `Project [Debug]` target overrides the `CLANG_CXX_LIBRARY` build setting defined in `Pods/Target Support Files/Pods/Pods.debug.xcconfig'. This can lead to problems with the CocoaPods installation
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

[!] The `Project [Release]` target overrides the `CLANG_CXX_LIBRARY` build setting defined in `Pods/Target Support Files/Pods/Pods.release.xcconfig'. This can lead to problems with the CocoaPods installation
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

The Fix

  1. Select your Project so you can see the Build Settings.
  2. Select your Target (AppName under Targets)
  3. Find C++ Standard Library (It will probably be in BOLD - This means it's overridden).
  4. Select the Line (So it's highlighted Blue), and press ? + DELETE (Command + Backspace)

The line should not be bolded anymore and if you run pod install the warnings/errors should have disappeared.


Visual Aid

CLANG_CXX_LIBRARY Error/Warning with Cocoapods

Get current URL with jQuery?

All browsers support Javascript window object. It defines the window of the browser.

The global objects and functions become part of the window object automatically.

All global variables are window objects properties and all global functions are its methods.

The whole HTML document is a window property too.

So you can use window.location object to get all url related attributes.

Javascript

_x000D_
_x000D_
console.log(window.location.host);     //returns host_x000D_
console.log(window.location.hostname);    //returns hostname_x000D_
console.log(window.location.pathname);         //return path_x000D_
console.log(window.location.href);       //returns full current url_x000D_
console.log(window.location.port);         //returns the port_x000D_
console.log(window.location.protocol)     //returns the protocol
_x000D_
_x000D_
_x000D_

JQuery

_x000D_
_x000D_
console.log("host = "+$(location).attr('host'));_x000D_
console.log("hostname = "+$(location).attr('hostname'));_x000D_
console.log("pathname = "+$(location).attr('pathname')); _x000D_
console.log("href = "+$(location).attr('href'));   _x000D_
console.log("port = "+$(location).attr('port'));   _x000D_
console.log("protocol = "+$(location).attr('protocol'));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How do you obtain a Drawable object from a resource id in android package?

best way is

 button.setBackgroundResource(android.R.drawable.ic_delete);

OR this for Drawable left and something like that for right etc.

int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);

and

getResources().getDrawable() is now deprecated

What is the difference between UTF-8 and ISO-8859-1?

  • ASCII: 7 bits. 128 code points.

  • ISO-8859-1: 8 bits. 256 code points.

  • UTF-8: 8-32 bits (1-4 bytes). 1,112,064 code points.

Both ISO-8859-1 and UTF-8 are backwards compatible with ASCII, but UTF-8 is not backwards compatible with ISO-8859-1:

#!/usr/bin/env python3

c = chr(0xa9)
print(c)
print(c.encode('utf-8'))
print(c.encode('iso-8859-1'))

Output:

©
b'\xc2\xa9'
b'\xa9'

Get child node index

Use binary search algorithm to improve the performace when the node has large quantity siblings.

function getChildrenIndex(ele){
    //IE use Element.sourceIndex
    if(ele.sourceIndex){
        var eles = ele.parentNode.children;
        var low = 0, high = eles.length-1, mid = 0;
        var esi = ele.sourceIndex, nsi;
        //use binary search algorithm
        while (low <= high) {
            mid = (low + high) >> 1;
            nsi = eles[mid].sourceIndex;
            if (nsi > esi) {
                high = mid - 1;
            } else if (nsi < esi) {
                low = mid + 1;
            } else {
                return mid;
            }
        }
    }
    //other browsers
    var i=0;
    while(ele = ele.previousElementSibling){
        i++;
    }
    return i;
}

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

I think i understand what the reason of your error. First you click auto AUTO INCREMENT field then select it as a primary key.

The Right way is First You have to select it as a primary key then you have to click auto AUTO INCREMENT field.

Very easy. Thanks

APK signing error : Failed to read key from keystore

Removing double-quotes solve my problem, now its:

DEBUG_STORE_PASSWORD=androiddebug
DEBUG_KEY_ALIAS=androiddebug
DEBUG_KEY_PASSWORD=androiddebug

Command-line svn for Windows?

You can get SVN command-line tools with TortoiseSVN 1.7 or later or get a 6.5mb standalone package from VisualSVN.

Starting with TortoiseSVN 1.7, its installer provides you with an option to install the command-line tools.

It also makes sense to check the Apache Subversion "Binary Packages" page. xD

How to view file diff in git before commit

If you want to see what you haven't git added yet:

git diff myfile.txt

or if you want to see already added changes

git diff --cached myfile.txt

How can I get the current user directory?

May be this will be a good solution: taking in account whether this is Vista/Win7 or XP and without using environment variables:

string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName;
if ( Environment.OSVersion.Version.Major >= 6 ) {
    path = Directory.GetParent(path).ToString();
}

Though using the environment variable is much more clear.

Replace multiple strings at once

There is no way to do this in one method call, you'll have to either chain calls together, or write a function that manually does what you need.

var s = "<>\n";
s = s.replace("<", "&lt;");
s = s.replace(">", "&gt;");
s = s.replace("\n", "<br/>");

How to modify a specified commit?

You can use git rebase. For example, if you want to modify commit bbc643cd, run

$ git rebase --interactive 'bbc643cd^'

Please note the caret ^ at the end of the command, because you need actually to rebase back to the commit before the one you wish to modify.

In the default editor, modify pick to edit in the line mentioning 'bbc643cd'.

Save the file and exit: git will interpret and automatically execute the commands in the file. You will find yourself in the previous situation in which you just had created commit bbc643cd.

At this point, bbc643cd is your last commit and you can easily amend it: make your changes and then commit them with the command:

$ git commit --all --amend --no-edit

After that, type:

$ git rebase --continue

to return back to the previous HEAD commit.

WARNING: Note that this will change the SHA-1 of that commit as well as all children -- in other words, this rewrites the history from that point forward. You can break repos doing this if you push using the command git push --force

Print multiple arguments in Python

Use: .format():

print("Total score for {0} is {1}".format(name, score))

Or:

// Recommended, more readable code

print("Total score for {n} is {s}".format(n=name, s=score))

Or:

print("Total score for" + name + " is " + score)

Or:

`print("Total score for %s is %d" % (name, score))`

How to create JSON string in JavaScript?

json strings can't have line breaks in them. You'd have to make it all one line: {"key":"val","key2":"val2",etc....}.

But don't generate JSON strings yourself. There's plenty of libraries that do it for you, the biggest of which is jquery.

Append integer to beginning of list in Python

>>>var=7
>>>array = [1,2,3,4,5,6]
>>>array.insert(0,var)
>>>array
[7, 1, 2, 3, 4, 5, 6]

How it works:

array.insert(index, value)

Insert an item at a given position. The first argument is the index of the element before which to insert, so array.insert(0, x) inserts at the front of the list, and array.insert(len(array), x) is equivalent to array.append(x).Negative values are treated as being relative to the end of the array.

How to recover Git objects damaged by hard disk failure?

Here are two functions that may help if your backup is corrupted, or you have a few partially corrupted backups as well (this may happen if you backup the corrupted objects).

Run both in the repo you're trying to recover.

Standard warning: only use if you're really desperate and you have backed up your (corrupted) repo. This might not resolve anything, but at least should highlight the level of corruption.

fsck_rm_corrupted() {
    corrupted='a'
    while [ "$corrupted" ]; do
        corrupted=$(                                  \
        git fsck --full --no-dangling 2>&1 >/dev/null \
            | grep 'stored in'                          \
            | sed -r 's:.*(\.git/.*)\).*:\1:'           \
        )
        echo "$corrupted"
        rm -f "$corrupted"
    done
}

if [ -z "$1" ]  || [ ! -d "$1" ]; then
    echo "'$1' is not a directory. Please provide the directory of the git repo"
    exit 1
fi

pushd "$1" >/dev/null
fsck_rm_corrupted
popd >/dev/null

and

unpack_rm_corrupted() {
    corrupted='a'
    while [ "$corrupted" ]; do
        corrupted=$(                                  \
        git unpack-objects -r < "$1" 2>&1 >/dev/null \
            | grep 'stored in'                          \
            | sed -r 's:.*(\.git/.*)\).*:\1:'           \
        )
        echo "$corrupted"
        rm -f "$corrupted"
    done
}

if [ -z "$1" ]  || [ ! -d "$1" ]; then
    echo "'$1' is not a directory. Please provide the directory of the git repo"
    exit 1
fi

for p in $1/objects/pack/pack-*.pack; do
    echo "$p"
    unpack_rm_corrupted "$p"
done

Find object by id in an array of JavaScript objects

Use Array.prototype.filter() function.

DEMO: https://jsfiddle.net/sumitridhal/r0cz0w5o/4/

JSON

var jsonObj =[
 {
  "name": "Me",
  "info": {
   "age": "15",
   "favColor": "Green",
   "pets": true
  }
 },
 {
  "name": "Alex",
  "info": {
   "age": "16",
   "favColor": "orange",
   "pets": false
  }
 },
{
  "name": "Kyle",
  "info": {
   "age": "15",
   "favColor": "Blue",
   "pets": false
  }
 }
];

FILTER

var getPerson = function(name){
    return jsonObj.filter(function(obj) {
      return obj.name === name;
    });
}

running a command as a super user from a python script

Another way is to make your user a password-less sudo user.

Type the following on command line:

sudo visudo

Then add the following and replace the <username> with yours:

<username> ALL=(ALL) NOPASSWD: ALL

This will allow the user to execute sudo command without having to ask for password (including application launched by the said user. This might be a security risk though

How can I "reset" an Arduino board?

After scratching my head about this problem, here is a very simple solution that works anytime:

  • Unplug your USB cable
  • Go in Device Manager
  • Click on Ports (COM & LPT)
  • Right click on Arduino....(COMx)
  • Properties
  • Port Settings
  • Put Flow Control to HARDWARE
  • Create an empty sketch (Optional)
  • Connect the USB cable
  • Upload (Ctrl + U)

// Empty sketch to fix the upload problem
// Created by Eric Phenix
// Nov 2014

void setup()
{
}

// The loop routine runs over and over again forever:
void loop()
{
    delay(1000);
}

Et voila!

Purpose of ESI & EDI registers?

There are a few operations you can only do with DI/SI (or their extended counterparts, if you didn't learn ASM in 1985). Among these are

REP STOSB
REP MOVSB
REP SCASB

Which are, respectively, operations for repeated (= mass) storing, loading and scanning. What you do is you set up SI and/or DI to point at one or both operands, perhaps put a count in CX and then let 'er rip. These are operations that work on a bunch of bytes at a time, and they kind of put the CPU in automatic. Because you're not explicitly coding loops, they do their thing more efficiently (usually) than a hand-coded loop.

Just in case you're wondering: Depending on how you set the operation up, repeated storing can be something simple like punching the value 0 into a large contiguous block of memory; MOVSB is used, I think, to copy data from one buffer (well, any bunch of bytes) to another; and SCASB is used to look for a byte that matches some search criterion (I'm not sure if it's only searching on equality, or what – you can look it up :) )

That's most of what those regs are for.

jquery input select all on focus

i using FF 16.0.2 and jquery 1.8.3, all the code in the answer didn't work.
I use code like this and work.

$("input[type=text]").focus().select();

Partition Function COUNT() OVER possible using DISTINCT

Necromancing:

It's relativiely simple to emulate a COUNT DISTINCT over PARTITION BY with MAX via DENSE_RANK:

;WITH baseTable AS
(
    SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR3' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR2' AS ADR
)
,CTE AS
(
    SELECT RM, ADR, DENSE_RANK() OVER(PARTITION BY RM ORDER BY ADR) AS dr 
    FROM baseTable
)
SELECT
     RM
    ,ADR

    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY ADR) AS cnt1 
    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM) AS cnt2 
    -- Not supported
    --,COUNT(DISTINCT CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY CTE.ADR) AS cntDist
    ,MAX(CTE.dr) OVER (PARTITION BY CTE.RM ORDER BY CTE.RM) AS cntDistEmu 
FROM CTE

Note:
This assumes the fields in question are NON-nullable fields.
If there is one or more NULL-entries in the fields, you need to subtract 1.

Select mySQL based only on month and year

$q="SELECT * FROM projects WHERE YEAR(date) = 2012 AND MONTH(date) = 1;

MySQL show status - active or total connections?

SHOW STATUS WHERE `variable_name` = 'Threads_connected';

This will show you all the open connections.

how to get GET and POST variables with JQuery?

My approach:

var urlParams;
(window.onpopstate = function () {
var match,
      pl     = /\+/g,  Regex for replacing addition symbol with a space
       search = /([^&=]+)=?([^&]*)/g,
      decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
       query  = window.location.search.substring(1);
   urlParams = {};
   while (match = search.exec(query))
    urlParams[decode(match[1])] = decode(match[2]);
})();