Programs & Examples On #Natsort

Swift days between two NSDates

easier option would be to create a extension on Date

public extension Date {

        public var currentCalendar: Calendar {
            return Calendar.autoupdatingCurrent
        }

        public func daysBetween(_ date: Date) -> Int {
            let components = currentCalendar.dateComponents([.day], from: self, to: date)
            return components.day!
        }
    }

Check if a folder exist in a directory and create them using C#

This should work

if(!Directory.Exists(@"C:\MP_Upload")) {
    Directory.CreateDirectory(@"C:\MP_Upload");
}

CSS3 selector :first-of-type with class name?

No, it's not possible using just one selector. The :first-of-type pseudo-class selects the first element of its type (div, p, etc). Using a class selector (or a type selector) with that pseudo-class means to select an element if it has the given class (or is of the given type) and is the first of its type among its siblings.

Unfortunately, CSS doesn't provide a :first-of-class selector that only chooses the first occurrence of a class. As a workaround, you can use something like this:

.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }

Explanations and illustrations for the workaround are given here and here.

How to have git log show filenames like svn log -v

git show is also a great command.

It's kind of like svn diff, but you can pass it a commit guid and see that diff.

Java logical operator short-circuiting

The && and || operators "short-circuit", meaning they don't evaluate the right-hand side if it isn't necessary.

The & and | operators, when used as logical operators, always evaluate both sides.

There is only one case of short-circuiting for each operator, and they are:

  • false && ... - it is not necessary to know what the right-hand side is because the result can only be false regardless of the value there
  • true || ... - it is not necessary to know what the right-hand side is because the result can only be true regardless of the value there

Let's compare the behaviour in a simple example:

public boolean longerThan(String input, int length) {
    return input != null && input.length() > length;
}

public boolean longerThan(String input, int length) {
    return input != null & input.length() > length;
}

The 2nd version uses the non-short-circuiting operator & and will throw a NullPointerException if input is null, but the 1st version will return false without an exception.

How to process POST data in Node.js?

On form fields like these

   <input type="text" name="user[name]" value="MyName">
   <input type="text" name="user[email]" value="[email protected]">

some of the above answers will fail because they only support flat data.

For now I am using the Casey Chu answer but with the "qs" instead of the "querystring" module. This is the module "body-parser" uses as well. So if you want nested data you have to install qs.

npm install qs --save

Then replace the first line like:

//var qs = require('querystring');
var qs = require('qs'); 

function (request, response) {
    if (request.method == 'POST') {
        var body = '';

        request.on('data', function (data) {
            body += data;

            // Too much POST data, kill the connection!
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6)
                request.connection.destroy();
        });

        request.on('end', function () {
            var post = qs.parse(body);
            console.log(post.user.name); // should work
            // use post['blah'], etc.
        });
    }
}

How good is Java's UUID.randomUUID?

Many of the answers discuss how many UUIDs would have to be generated to reach a 50% chance of a collision. But a 50%, 25%, or even 1% chance of collision is worthless for an application where collision must be (virtually) impossible.

Do programmers routinely dismiss as "impossible" other events that can and do occur?

When we write data to a disk or memory and read it back again, we take for granted that the data are correct. We rely on the device's error correction to detect any corruption. But the chance of undetected errors is actually around 2-50.

Wouldn't it make sense to apply a similar standard to random UUIDs? If you do, you will find that an "impossible" collision is possible in a collection of around 100 billion random UUIDs (236.5).

This is an astronomical number, but applications like itemized billing in a national healthcare system, or logging high frequency sensor data on a large array of devices could definitely bump into these limits. If you are writing the next Hitchhiker's Guide to the Galaxy, don't try to assign UUIDs to each article!

Node Version Manager (NVM) on Windows

First off, I use nvm on linux machine.

When looking at the documentation for nvm at https://www.npmjs.org/package/nvm, it recommendations that you install nvm globally using the -g switch.

npm install -g nvm

Also there is a . in the path variable that they recommend.

export PATH=./node_modules/.bin:$PATH

so maybe your path should be

C:\Program Files (x86)\nodejs\node_modules\npm\\.bin

Node.js: for each … in not working

There's no for each in in the version of ECMAScript supported by Node.js, only supported by firefox currently.

The important thing to note is that JavaScript versions are only relevant to Gecko (Firefox's engine) and Rhino (which is always a few versions behind). Node uses V8 which follows ECMAScript specifications

Clearing my form inputs after submission

since you are using jquery library, i would advise you utilize the reset() method.

Firstly, add an id attribute to the form tag

<form id='myForm'>

Then on completion, clear your input fields as:

$('#myForm')[0].reset();

Unit Tests not discovered in Visual Studio 2017

I was facing the same issue, in my case in order to resolved

  1. I opened the windows console (windows key + cmd).
  2. Navigate to the folder where the project was created.
  3. Executed the command "dotnet test" it is basically the same test that visual studio executes but when you run it thru console it allows you to see the complete trace.
  4. I got this error message "TestClass attribute defined on non-public class MSTest.TestController.BaseTest"
  5. So I went to the test case and mark it as public, build again and my tests are being displayed correctly

How to add composite primary key to table

If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.

enter image description here

What is the difference between Release and Debug modes in Visual Studio?

Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager... (it's on the Build menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.

Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.

The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #defines and a few other things. For a C++ project, you get a much bigger variety of things to tweak.

In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.

How to set a header in an HTTP response?

Header fields are not copied to subsequent requests. You should use either cookie for this (addCookie method) or store "REMOTE_USER" in session (which you can obtain with getSession method).

Java abstract interface

Why is it necessary for an interface to be "declared" abstract?

It's not.

public abstract interface Interface {
       \___.__/
           |
           '----> Neither this...

    public void interfacing();
    public abstract boolean interfacing(boolean really);
           \___.__/
               |
               '----> nor this, are necessary.
}

Interfaces and their methods are implicitly abstract and adding that modifier makes no difference.

Is there other rules that applies with an abstract interface?

No, same rules apply. The method must be implemented by any (concrete) implementing class.

If abstract is obsolete, why is it included in Java? Is there a history for abstract interface?

Interesting question. I dug up the first edition of JLS, and even there it says "This modifier is obsolete and should not be used in new Java programs".

Okay, digging even further... After hitting numerous broken links, I managed to find a copy of the original Oak 0.2 Specification (or "manual"). Quite interesting read I must say, and only 38 pages in total! :-)

Under Section 5, Interfaces, it provides the following example:

public interface Storing {
    void freezeDry(Stream s) = 0;
    void reconstitute(Stream s) = 0;
}

And in the margin it says

In the future, the " =0" part of declaring methods in interfaces may go away.

Assuming =0 got replaced by the abstract keyword, I suspect that abstract was at some point mandatory for interface methods!


Related article: Java: Abstract interfaces and abstract interface methods

How to get the list of all database users

Go for this:

 SELECT name,type_desc FROM sys.sql_logins

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

How to prevent sticky hover effects for buttons on touch devices

It can be accomplished by swapping an HTML class. It should be less prone to glitches than removing the whole element, especially with large, image links etc.

We can also decide whether we want hover states to be triggered when scrolling with touch (touchmove) or even add a timeout to delay them.

The only significant change in our code will be using additional HTML class such as <a class='hover'></a> on elements that implement the new behaviour.

HTML

<a class='my-link hover' href='#'>
    Test
</a>

CSS

.my-link:active, // :active can be turned off to disable hover state on 'touchmove'
.my-link.hover:hover {

    border: 2px dotted grey;
}

JS (with jQuery)

$('.hover').bind('touchstart', function () {

   var $el;
   $el = $(this);
   $el.removeClass('hover'); 

   $el.hover(null, function () {
      $el.addClass('hover');
   });
});

Example

https://codepen.io/mattrcouk/pen/VweajZv

-

I don’t have any device with both mouse and touch to test it properly, though.

Convert double to string

Try c.ToString("F6");

(For a full explanation of numeric formatting, see MSDN)

Unicode characters in URLs

For me this is the correct way, This just worked:

    $linker = rawurldecode("$link");
    <a href="<?php echo $link;?>"   target="_blank"><?php echo $linker ;?></a>

This worked, and now links are displayed properly:

http://newspaper.annahar.com/article/121638-????--????-???-??-??????-?????-????-??????-??????-????-??????-?????-????????

Link found on:

http://www.galeriejaninerubeiz.com/newsite/news

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

I wouldn't use JavaScript navigator.userAgent or $.browser (which uses navigator.userAgent) since it can be spoofed.

To target Internet Explorer 9, 10 and 11 (Note: also the latest Chrome):

@media screen and (min-width:0\0) { 
    /* Enter CSS here */
}

To target Internet Explorer 10:

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    /* IE10+ CSS here */
}

To target Edge Browser:

@supports (-ms-accelerator:true) {
  .selector { property:value; } 
}

Sources:

Is embedding background image data into CSS as Base64 good or bad practice?

One of the things I would suggest is to have two separate stylesheets: One with your regular style definitions and another one that contains your images in base64 encoding.

You have to include the base stylesheet before the image stylesheet of course.

This way you will assure that you're regular stylesheet is downloaded and applied as soon as possible to the document, yet at the same time you profit from reduced http-requests and other benefits data-uris give you.

How to measure elapsed time

There are many ways to achieve this, but the most important consideration to measure elapsed time is to use System.nanoTime() and TimeUnit.NANOSECONDS as the time unit. Why should I do this? Well, it is because System.nanoTime() method returns a high-resolution time source, in nanoseconds since some reference point (i.e. Java Virtual Machine's start up).

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

For the same reason, it is recommended to avoid the use of the System.currentTimeMillis() method for measuring elapsed time. This method returns the wall-clock time, which may change based on many factors. This will be negative for your measurements.

Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

So here you have one solution based on the System.nanoTime() method, another one using Guava, and the final one Apache Commons Lang

public class TimeBenchUtil
{
    public static void main(String[] args) throws InterruptedException
    {
        stopWatch();
        stopWatchGuava();
        stopWatchApacheCommons();
    }

    public static void stopWatch() throws InterruptedException
    {
        long endTime, timeElapsed, startTime = System.nanoTime();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);

        /* ... the code being measured ends ... */

        endTime = System.nanoTime();

        // get difference of two nanoTime values
        timeElapsed = endTime - startTime;

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }

    public static void stopWatchGuava() throws InterruptedException
    {
        // Creates and starts a new stopwatch
        Stopwatch stopwatch = Stopwatch.createStarted();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);
        /* ... the code being measured ends ... */

        stopwatch.stop(); // optional

        // get elapsed time, expressed in milliseconds
        long timeElapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }

    public static void stopWatchApacheCommons() throws InterruptedException
    {
        StopWatch stopwatch = new StopWatch();
        stopwatch.start();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);

        /* ... the code being measured ends ... */

        stopwatch.stop();    // Optional

        long timeElapsed = stopwatch.getNanoTime();

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }
}

Cannot push to Git repository on Bitbucket

Just need config file under ~/.ssh directory
ref : https://confluence.atlassian.com/bitbucket/set-up-ssh-for-git-728138079.html
add bellow configuration in config file

Host bitbucket.org
 IdentityFile ~/.ssh/<privatekeyfile>

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

I think this need to be run from the Management Shell rather than the console, it sounds like the module isn't being imported into the Powershell console. You can add the module by running:

Add-PSSnapin Microsoft.Sharepoint.Powershell

in the Powershell console.

How to parse/read a YAML file into a Python object?

From http://pyyaml.org/wiki/PyYAMLDocumentation:

add_path_resolver(tag, path, kind) adds a path-based implicit tag resolver. A path is a list of keys that form a path to a node in the representation graph. Paths elements can be string values, integers, or None. The kind of a node can be str, list, dict, or None.

#!/usr/bin/env python
import yaml

class Person(yaml.YAMLObject):
  yaml_tag = '!person'

  def __init__(self, name):
    self.name = name

yaml.add_path_resolver('!person', ['Person'], dict)

data = yaml.load("""
Person:
  name: XYZ
""")

print data
# {'Person': <__main__.Person object at 0x7f2b251ceb10>}

print data['Person'].name
# XYZ

laravel Eloquent ORM delete() method

Laravel Eloquent provides destroy() function in which returns boolean value. So if a record exists on the database and deleted you'll get true otherwise false.

Here's an example using Laravel Tinker shell.

delete operation result

In this case, your code should look like this:

public function destroy($id)
    {
        $res = User::destroy($id);
        if ($res) {
            return response()->json([
                'status' => '1',
                'msg' => 'success'
            ]);
        } else {
            return response()->json([
                'status' => '0',
                'msg' => 'fail'
            ]);
        }
    }

More info about Laravel Eloquent Deleting Models

How to remove all white space from the beginning or end of a string?

take a look at Trim() which returns a new string with whitespace removed from the beginning and end of the string it is called on.

Understanding The Modulus Operator %

As you say, the % sign is used to take the modulus (division remainder).

In w3schools' JavaScript Arithmetic page we can read in the Remainder section what I think to be a great explanation

In arithmetic, the division of two integers produces a quotient and a remainder.

In mathematics, the result of a modulo operation is the remainder of an arithmetic division.

So, in your specific case, when you try to divide 7 bananas into a group of 5 bananas, you're able to create 1 group of 5 (quotient) and you'll be left with 2 bananas (remainder).

If 5 bananas into a group of 7, you won't be able to and so you're left with again the 5 bananas (remainder).

What is /dev/null 2>&1?

Edit /etc/conf.apf. Set DEVEL_MODE="0". DEVEL_MODE set to 1 will add a cron job to stop apf after 5 minutes.

How to select bottom most rows?

"Tom H" answer above is correct and it works for me in getting Bottom 5 rows.

SELECT [KeyCol1], [KeyCol2], [Col3]
FROM
(SELECT TOP 5 [KeyCol1],
       [KeyCol2],
       [Col3]
  FROM [dbo].[table_name]
  ORDER BY [KeyCol1],[KeyCol2] DESC) SOME_ALAIS
  ORDER BY [KeyCol1],[KeyCol2] ASC

Thanks.

n-grams in python, four, five, six grams?

A more elegant approach to build bigrams with python’s builtin zip(). Simply convert the original string into a list by split(), then pass the list once normally and once offset by one element.

string = "I really like python, it's pretty awesome."

def find_bigrams(s):
    input_list = s.split(" ")
    return zip(input_list, input_list[1:])

def find_ngrams(s, n):
  input_list = s.split(" ")
  return zip(*[input_list[i:] for i in range(n)])

find_bigrams(string)

[('I', 'really'), ('really', 'like'), ('like', 'python,'), ('python,', "it's"), ("it's", 'pretty'), ('pretty', 'awesome.')]

Show/Hide Table Rows using Javascript classes

It's difficult to figure out what you're trying to do with this sample but you're actually on the right track thinking about using classes. I've created a JSFiddle to help demonstrate a slightly better way (I hope) of doing this.

Here's the fiddle: link.

What you do is, instead of working with IDs, you work with classes. In your code sample, there are Oranges and Apples. I treat them as product categories (as I don't really know what your purpose is), with their own ids. So, I mark the product <tr>s with class="cat1" or class="cat2".

I also mark the links with a simple .toggler class. It's not good practice to have onclick attributes on elements themselves. You should 'bind' the events on page load using JavaScript. I do this using jQuery.

$(".toggler").click(function(e){
    // you handle the event here
});

With this format, you are binding an event handler to the click event of links with class toggler. In my code, I add a data-prod-cat attribute to the toggler links to specify which product rows they should control. (The reason for my using a data-* attribute is explained here. You can Google 'html5 data attributes' for more information.)

In the event handler, I do this:

$('.cat'+$(this).attr('data-prod-cat')).toggle();

With this code, I'm actually trying to create a selector like $('.cat1') so I can select rows for a specific product category, and change their visibility. I use $(this).attr('data-prod-cat') this to access the data-prod-cat attribute of the link the user clicks. I use the jQuery toggle function, so that I don't have to write logic like if visible, then hide element, else make it visible like you do in your JS code. jQuery deals with that. The toggle function does what it says and toggles the visibility of the specified element(s).

I hope this was explanatory enough.

Cannot access a disposed object - How to fix?

Stopping the timer doesn't mean that it won't be called again, depending on when you stop the timer, the timer_tick may still be queued on the message loop for the form. What will happen is that you'll get one more tick that you may not be expecting. What you can do is in your timer_tick, check the Enabled property of your timer before executing the Timer_Tick method.

How to get the difference between two arrays in JavaScript?

Here is how I get two arrays difference. Pure and clean.

It will return a object that contain [add list] and [remove list].

  function getDiff(past, now) {
        let ret = { add: [], remove: [] };
        for (var i = 0; i < now.length; i++) {
          if (past.indexOf(now[i]) < 0)
            ret['add'].push(now[i]);
        }
        for (var i = 0; i < past.length; i++) {
          if (now.indexOf(past[i]) < 0)
            ret['remove'].push(past[i]);
        }
        return ret;
      }

How do I get DOUBLE_MAX?

INT_MAX is just a definition in limits.h. You don't make it clear whether you need to store an integer or floating point value. If integer, and using a 64-bit compiler, use a LONG (LLONG for 32-bit).

Detect Android phone via Javascript / jQuery

;(function() {
    var redirect = false
    if (navigator.userAgent.match(/iPhone/i)) {
        redirect = true
    }
    if (navigator.userAgent.match(/iPod/i)) {
        redirect = true
    }
    var isAndroid = /(android)/i.test(navigator.userAgent)
    var isMobile = /(mobile)/i.test(navigator.userAgent)
    if (isAndroid && isMobile) {
        redirect = true
    }
    if (redirect) {
        window.location.replace('jQueryMobileSite')
    }
})()

Conversion between UTF-8 ArrayBuffer and String

The methods readAsArrayBuffer and readAsText from a FileReader object converts a Blob object to an ArrayBuffer or to a DOMString asynchronous.

A Blob object type can be created from a raw text or byte array, for example.

let blob = new Blob([text], { type: "text/plain" });

let reader = new FileReader();
reader.onload = event =>
{
    let buffer = event.target.result;
};
reader.readAsArrayBuffer(blob);

I think it's better to pack up this in a promise:

function textToByteArray(text)
{
    let blob = new Blob([text], { type: "text/plain" });
    let reader = new FileReader();
    let done = function() { };

    reader.onload = event =>
    {
        done(new Uint8Array(event.target.result));
    };
    reader.readAsArrayBuffer(blob);

    return { done: function(callback) { done = callback; } }
}

function byteArrayToText(bytes, encoding)
{
    let blob = new Blob([bytes], { type: "application/octet-stream" });
    let reader = new FileReader();
    let done = function() { };

    reader.onload = event =>
    {
        done(event.target.result);
    };

    if(encoding) { reader.readAsText(blob, encoding); } else { reader.readAsText(blob); }

    return { done: function(callback) { done = callback; } }
}

let text = "\uD83D\uDCA9 = \u2661";
textToByteArray(text).done(bytes =>
{
    console.log(bytes);
    byteArrayToText(bytes, 'UTF-8').done(text => 
    {
        console.log(text); //  = ?
    });
});

How to remove button shadow (android)

Using this as the background for your button might help, change the color to your needs

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape android:shape="rectangle">
            <solid android:color="@color/app_theme_light" />
            <padding
                android:left="8dp"
                android:top="4dp"
                android:right="8dp"
                android:bottom="4dp" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/app_theme_dark" />
            <padding
                android:left="8dp"
                android:top="4dp"
                android:right="8dp"
                android:bottom="4dp" />
        </shape>
    </item>
</selector>

Visual Studio window which shows list of methods

I found how to turn the drop down on as shown in the first answer (@ChrisF):

Go to Options->Text Editor->(your language)

and tick "Navigation bar" in the display section.

Is it possible to serialize and deserialize a class in C++?

Boost is a good suggestion. But if you would like to roll your own, it's not so hard.

Basically you just need a way to build up a graph of objects and then output them to some structured storage format (JSON, XML, YAML, whatever). Building up the graph is as simple as utilizing a marking recursive decent object algorithm and then outputting all the marked objects.

I wrote an article describing a rudimentary (but still powerful) serialization system. You may find it interesting: Using SQLite as an On-disk File Format, Part 2.

How to center a component in Material-UI and make it responsive?

Since you are going to use this in a login page. Here is a code I used in a Login page using Material-UI

<Grid
  container
  spacing={0}
  direction="column"
  alignItems="center"
  justify="center"
  style={{ minHeight: '100vh' }}
>

  <Grid item xs={3}>
    <LoginForm />
  </Grid>   

</Grid> 

this will make this login form at the center of the screen.

But still IE doesn't support the Material-UI Grid and you will see some misplaced content in IE.

Hope this will help you.

How do I disable form resizing for users?

Change the FormBorderStyle to one of the fixed values: FixedSingle, Fixed3D, FixedDialog or FixedToolWindow.

The FormBorderStyle property is under the Appearance category.

Or check this:

// Define the border style of the form to a dialog box.
form1.FormBorderStyle = FormBorderStyle.FixedDialog;

// Set the MaximizeBox to false to remove the maximize box.
form1.MaximizeBox = false;

// Set the MinimizeBox to false to remove the minimize box.
form1.MinimizeBox = false;

// Set the start position of the form to the center of the screen.
form1.StartPosition = FormStartPosition.CenterScreen;

// Display the form as a modal dialog box.
form1.ShowDialog();

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Generally...

Hibernate is used for handling database operations. There is a rich set of database utility functionality, which reduces your number of lines of code. Especially you have to read @Annotation of hibernate. It is an ORM framework and persistence layer.

Spring provides a rich set of the Injection based working mechanism. Currently, Spring is well-known. You have to also read about Spring AOP. There is a bridge between Struts and Hibernate. Mainly Spring provides this kind of utility.

Struts2 provides action based programming. There are a rich set of Struts tags. Struts prove action based programming so you have to maintain all the relevant control of your view.

In Addition, Tapestry is a different framework for Java. In which you have to handle only .tml (template file). You have to create two main files for any class. One is JAVA class and another one is its template. Both names are same. Tapestry automatically calls related classes.

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Put this in C2 and copy down

=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")

Then if the value in A isn't in B the cell in column C will say "not in B".

Cross-Origin Request Blocked

You need other headers, not only access-control-allow-origin. If your request have the "Access-Control-Allow-Origin" header, you must copy it into the response headers, If doesn't, you must check the "Origin" header and copy it into the response. If your request doesn't have Access-Control-Allow-Origin not Origin headers, you must return "*".

You can read the complete explanation here: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server

and this is the function I'm using to write cross domain headers:

func writeCrossDomainHeaders(w http.ResponseWriter, req *http.Request) {
    // Cross domain headers
    if acrh, ok := req.Header["Access-Control-Request-Headers"]; ok {
        w.Header().Set("Access-Control-Allow-Headers", acrh[0])
    }
    w.Header().Set("Access-Control-Allow-Credentials", "True")
    if acao, ok := req.Header["Access-Control-Allow-Origin"]; ok {
        w.Header().Set("Access-Control-Allow-Origin", acao[0])
    } else {
        if _, oko := req.Header["Origin"]; oko {
            w.Header().Set("Access-Control-Allow-Origin", req.Header["Origin"][0])
        } else {
            w.Header().Set("Access-Control-Allow-Origin", "*")
        }
    }
    w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
    w.Header().Set("Connection", "Close")

}

Wildcards in a Windows hosts file

Here is the total configuration for those trying to accomplish the goal (wildcards in dev environment ie, XAMPP -- this example assumes all sites pointing to same codebase)

hosts file (add an entry)

file: %SystemRoot%\system32\drivers\etc\hosts

127.0.0.1   example.local

httpd.conf configuration (enable vhosts)

file: \XAMPP\etc\httpd.conf

# Virtual hosts
Include etc\extra\httpd-vhosts.conf

httpd-vhosts.conf configuration

file: XAMPP\etc\extra\httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "\path_to_XAMPP\htdocs"
    ServerName example.local
    ServerAlias *.example.local
#    SetEnv APP_ENVIRONMENT development
#    ErrorLog "logs\example.local-error_log"
#    CustomLog "logs\example.local-access_log" common
</VirtualHost>

restart apache

create pac file:

save as whatever.pac wherever you want to and then load the file in the browser's network>proxy>auto_configuration settings (reload if you alter this)

function FindProxyForURL(url, host) {
  if (shExpMatch(host, "*example.local")) {
    return "PROXY example.local";
  }
  return "DIRECT";
}

How do I determine whether my calculation of pi is accurate?

Since I'm the current world record holder for the most digits of pi, I'll add my two cents:

Unless you're actually setting a new world record, the common practice is just to verify the computed digits against the known values. So that's simple enough.

In fact, I have a webpage that lists snippets of digits for the purpose of verifying computations against them: http://www.numberworld.org/digits/Pi/


But when you get into world-record territory, there's nothing to compare against.

Historically, the standard approach for verifying that computed digits are correct is to recompute the digits using a second algorithm. So if either computation goes bad, the digits at the end won't match.

This does typically more than double the amount of time needed (since the second algorithm is usually slower). But it's the only way to verify the computed digits once you've wandered into the uncharted territory of never-before-computed digits and a new world record.


Back in the days where supercomputers were setting the records, two different AGM algorithms were commonly used:

These are both O(N log(N)^2) algorithms that were fairly easy to implement.

However, nowadays, things are a bit different. In the last three world records, instead of performing two computations, we performed only one computation using the fastest known formula (Chudnovsky Formula):

Enter image description here

This algorithm is much harder to implement, but it is a lot faster than the AGM algorithms.

Then we verify the binary digits using the BBP formulas for digit extraction.

Enter image description here

This formula allows you to compute arbitrary binary digits without computing all the digits before it. So it is used to verify the last few computed binary digits. Therefore it is much faster than a full computation.

The advantage of this is:

  1. Only one expensive computation is needed.

The disadvantage is:

  1. An implementation of the Bailey–Borwein–Plouffe (BBP) formula is needed.
  2. An additional step is needed to verify the radix conversion from binary to decimal.

I've glossed over some details of why verifying the last few digits implies that all the digits are correct. But it is easy to see this since any computation error will propagate to the last digits.


Now this last step (verifying the conversion) is actually fairly important. One of the previous world record holders actually called us out on this because, initially, I didn't give a sufficient description of how it worked.

So I've pulled this snippet from my blog:

N = # of decimal digits desired
p = 64-bit prime number

Enter image description here

Compute A using base 10 arithmetic and B using binary arithmetic.

Enter image description here

If A = B, then with "extremely high probability", the conversion is correct.


For further reading, see my blog post Pi - 5 Trillion Digits.

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

Your Event.hbm.xml says:

<set name="attendees" cascade="all">
    <key column="attendeeId" />
    <one-to-many class="Attendee" />
</set>

In plain english, this means that the column Attendee.attendeeId is the foreign key for the association attendees and points to the primary key of Event.

When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.

Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.

Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event-end as inverse.

Table with 100% width with equal size columns

ALL YOU HAVE TO DO:

HTML:

<table id="my-table"><tr>
<td> CELL 1 With a lot of text in it</td>
<td> CELL 2 </td>
<td> CELL 3 </td>
<td> CELL 4 With a lot of text in it </td>
<td> CELL 5 </td>
</tr></table>

CSS:

#my-table{width:100%;} /*or whatever width you want*/
#my-table td{width:2000px;} /*something big*/

if you have th you need to set it too like this:

#my-table th{width:2000px;}

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

Turns out for me this error was actually telling the truth - I was trying to resize a Null image, which was usually the 'last' frame of a video file, so the assertion was valid.

Now I have an extra step before attempting the resize operation, which is to do the assertion myself:

def getSizedFrame(width, height):
"""Function to return an image with the size I want"""    
    s, img = self.cam.read()

    # Only process valid image frames
    if s:
            img = cv2.resize(img, (width, height), interpolation = cv2.INTER_AREA)
    return s, img

Now I don't see the error.

Python Socket Receive Large Amount of Data

Most of the answers describe some sort of recvall() method. If your bottleneck when receiving data is creating the byte array in a for loop, I benchmarked three approaches of allocating the received data in the recvall() method:

Byte string method:

arr = b''
while len(arr) < msg_len:
    arr += sock.recv(max_msg_size)

List method:

fragments = []
while True: 
    chunk = sock.recv(max_msg_size)
    if not chunk: 
        break
    fragments.append(chunk)
arr = b''.join(fragments)

Pre-allocated bytearray method:

arr = bytearray(msg_len)
pos = 0
while pos < msg_len:
    arr[pos:pos+max_msg_size] = sock.recv(max_msg_size)
    pos += max_msg_size

Results:

enter image description here

Directory index forbidden by Options directive

It means there's no default document in that directory (index.html, index.php, etc...). On most webservers, that would mean it would show a listing of the directory's contents. But showing that directory is forbidden by server configuration (Options -Indexes)

C# ASP.NET Send Email via TLS

I was almost using the same technology as you did, however I was using my app to connect an Exchange Server via Office 365 platform on WinForms. I too had the same issue as you did, but was able to accomplish by using code which has slight modification of what others have given above.

SmtpClient client = new SmtpClient(exchangeServer, 587);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send(msg);

I had to use the Port 587, which is of course the default port over TSL and the did the authentication.

How to call base.base.method()?

As can be seen from previous posts, one can argue that if class functionality needs to be circumvented then something is wrong in the class architecture. That might be true, but one cannot always restructure or refactor the class structure on a large mature project. The various levels of change management might be one problem, but to keep existing functionality operating the same after refactoring is not always a trivial task, especially if time constraints apply. On a mature project it can be quite an undertaking to keep various regression tests from passing after a code restructure; there are often obscure "oddities" that show up. We had a similar problem in some cases inherited functionality should not execute (or should perform something else). The approach we followed below, was to put the base code that need to be excluded in a separate virtual function. This function can then be overridden in the derived class and the functionality excluded or altered. In this example "Text 2" can be prevented from output in the derived class.

public class Base
{
    public virtual void Foo()
    {
        Console.WriteLine("Hello from Base");
    }
}

public class Derived : Base
{
    public override void Foo()
    {
        base.Foo();
        Console.WriteLine("Text 1");
        WriteText2Func();
        Console.WriteLine("Text 3");
    }

    protected virtual void WriteText2Func()
    {  
        Console.WriteLine("Text 2");  
    }
}

public class Special : Derived
{
    public override void WriteText2Func()
    {
        //WriteText2Func will write nothing when 
        //method Foo is called from class Special.
        //Also it can be modified to do something else.
    }
}

node.js http 'get' request with query string parameters

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured network.

how to get 2 digits after decimal point in tsql?

Try cast result to numeric

CAST(sum(cast(datediff(second, IEC.CREATE_DATE, IEC.STATUS_DATE) as float) / 60)
    AS numeric(10,2)) TotalSentMinutes

Input

1
2
3

Output

1.00
2.00
3.00

Converting Java objects to JSON with Jackson

To convert your object in JSON with Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

Difference between hamiltonian path and euler path

Graph Theory Definitions

(In descending order of generality)

  • Walk: a sequence of edges where the end of one edge marks the beginning of the next edge

  • Trail: a walk which does not repeat any edges. All trails are walks.

  • Path: a walk where each vertex is traversed at most once. (paths used to refer to open walks, the definition has changed now) The property of traversing vertices at most once means that edges are also crossed at most once, hence all paths are trails.

Hamiltonian paths & Eulerian trails

  • Hamiltonian path: visits every vertex in the graph (exactly once, because it is a path)

  • Eulerian trail: visits every edge in the graph exactly once (because it is a trail, vertices may well be crossed more than once.)

php timeout - set_time_limit(0); - don't work

I usually use set_time_limit(30) within the main loop (so each loop iteration is limited to 30 seconds rather than the whole script).

I do this in multiple database update scripts, which routinely take several minutes to complete but less than a second for each iteration - keeping the 30 second limit means the script won't get stuck in an infinite loop if I am stupid enough to create one.

I must admit that my choice of 30 seconds for the limit is somewhat arbitrary - my scripts could actually get away with 2 seconds instead, but I feel more comfortable with 30 seconds given the actual application - of course you could use whatever value you feel is suitable.

Hope this helps!

How to get a specific output iterating a hash in Ruby?

You can also refine Hash::each so it will support recursive enumeration. Here is my version of Hash::each(Hash::each_pair) with block and enumerator support:

module HashRecursive
    refine Hash do
        def each(recursive=false, &block)
            if recursive
                Enumerator.new do |yielder|
                    self.map do |key, value|
                        value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
                        yielder << [[key], value]
                    end
                end.entries.each(&block)
            else
                super(&block)
            end
        end
        alias_method(:each_pair, :each)
    end
end

using HashRecursive

Here are usage examples of Hash::each with and without recursive flag:

hash = {
    :a => {
        :b => {
            :c => 1,
            :d => [2, 3, 4]
        },
        :e => 5
    },
    :f => 6
}

p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2

p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6

hash.each do |key, value|
    puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6

hash.each(true) do |key, value|
    puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6

hash.each_pair(recursive=true) do |key, value|
    puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6

Here is example from the question itself:

hash = {
    1   =>  ["a", "b"], 
    2   =>  ["c"], 
    3   =>  ["a", "d", "f", "g"], 
    4   =>  ["q"]
}

hash.each(recursive=false) do |key, value|
    puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]

Also take a look at my recursive version of Hash::merge(Hash::merge!) here.

Converting year and month ("yyyy-mm" format) to a date?

Since dates correspond to a numeric value and a starting date, you indeed need the day. If you really need your data to be in Date format, you can just fix the day to the first of each month manually by pasting it to the date:

month <- "2009-03"
as.Date(paste(month,"-01",sep=""))

How to copy a char array in C?

c functions below only ... c++ you have to do char array then use a string copy then user the string tokenizor functions... c++ made it a-lot harder to do anythng

#include <iostream>
#include <fstream>
#include <cstring>
#define TRUE 1
#define FALSE 0
typedef int Bool;
using namespace std;
Bool PalTrueFalse(char str[]);
int main(void)
{
char string[1000], ch;
int i = 0;
cout<<"Enter a message: ";

while((ch = getchar()) != '\n') //grab users input string untill 
{                               //Enter is pressed
    if (!isspace(ch) && !ispunct(ch)) //Cstring functions checking for
    {                                //spaces and punctuations of all kinds
        string[i] = tolower(ch); 
        i++;
    }
}
string[i] = '\0';  //hitting null deliminator once users input
cout<<"Your string: "<<string<<endl; 
if(PalTrueFalse(string)) //the string[i] user input is passed after
                        //being cleaned into the null function.
    cout<<"is a "<<"Palindrome\n"<<endl;
else
   cout<<"Not a palindrome\n"<<endl;
return 0;
}

Bool PalTrueFalse(char str[])
{
int left = 0;
int right = strlen(str)-1;
while (left<right)
{
   if(str[left] != str[right]) //comparing most outer values of string
       return FALSE;          //to inner values.
   left++;
   right--;
}
return TRUE;
}

Convert a number range to another range, maintaining ratio

Here's some short Python functions for your copy and paste ease, including a function to scale an entire list.

def scale_number(unscaled, to_min, to_max, from_min, from_max):
    return (to_max-to_min)*(unscaled-from_min)/(from_max-from_min)+to_min

def scale_list(l, to_min, to_max):
    return [scale_number(i, to_min, to_max, min(l), max(l)) for i in l]

Which can be used like so:

scale_list([1,3,4,5], 0, 100)

[0.0, 50.0, 75.0, 100.0]

In my case I wanted to scale a logarithmic curve, like so:

scale_list([math.log(i+1) for i in range(5)], 0, 50)

[0.0, 21.533827903669653, 34.130309724299266, 43.06765580733931, 50.0]

Print string and variable contents on the same line in R

Easiest way to do this is to use paste()

> paste("Today is", date())
[1] "Today is Sat Feb 21 15:25:18 2015"

paste0() would result in the following:

> paste0("Today is", date())
[1] "Today isSat Feb 21 15:30:46 2015"

Notice there is no default seperator between the string and x. Using a space at the end of the string is a quick fix:

> paste0("Today is ", date())
[1] "Today is Sat Feb 21 15:32:17 2015"

Then combine either function with print()

> print(paste("This is", date()))
[1] "This is Sat Feb 21 15:34:23 2015"

Or

> print(paste0("This is ", date()))
[1] "This is Sat Feb 21 15:34:56 2015"

As other users have stated, you could also use cat()

Nested iframes, AKA Iframe Inception

I think the best way to reach your div:

var your_element=$('iframe#uploads').children('iframe').children('div#element');

It should work well.

How to change the default message of the required field in the popover of form-control in bootstrap?

And for all input and select:

$("input[required], select[required]").attr("oninvalid", "this.setCustomValidity('Required!')");
$("input[required], select[required]").attr("oninput", "setCustomValidity('')");

How to test if a double is zero?

In Java, 0 is the same as 0.0, and doubles default to 0 (though many advise always setting them explicitly for improved readability). I have checked and foo.x == 0 and foo.x == 0.0 are both true if foo.x is zero

How do I read configuration settings from Symfony2 config.yml?

In order to be able to expose some configuration parameters for your bundle you should consult the documentation for doing so. It's fairly easy to do :)

Here's the link: How to expose a Semantic Configuration for a Bundle

Build an iOS app without owning a mac?

Short answer : theoretically YES, but this has to be a VERY GOOD friend of yours, but again, you might prefer to buy a used mac-mini

TLDR : You will need this Mac for a really long time, depending on your app requirements, your development skills, and your luck with Apple. For example:

  1. You might need some days to set up Xcode and the required SDKs and Libraries.
  2. It might take some time to get that Developer Account, sometimes you can wait too much even to get your request reviewed.
  3. When you submit your application for the first time, you will have to wait sometime, maybe up to several weeks, or even months, to get your app reviewed.
  4. Each time your app gets rejected, you will need to find and fix your issues (without much help from Apple, other that pointing out the guideline rule that you broke ), then re-submit your app for review, and wait again.
  5. Each time you try to apply a patch for your already deployed app, you will have to get your app reviewed and there is a chance that your previously legit app, now breaks a new guideline, so you re-submit and wait

So, from my experience the development of an iOS app is a very lengthy procedure, without even considering the actual code-development time. Can you borrow a Mac for that long ?

Java - Change int to ascii

If you first convert the int to a char, you will have your ascii code.

For example:

    int iAsciiValue = 9; // Currently just the number 9, but we want Tab character
    // Put the tab character into a string
    String strAsciiTab = Character.toString((char) iAsciiValue);

Using Excel as front end to Access database (with VBA)

I do this all the time. If you're using ADO, you're not really using Access, but Jet, the underlying database. That means anybody with Excel can use the app - Access not required. Oh I should mention, the place I work bought a bunch of Office Small Business licenses - no Access. Prior to working here, I would have assumed that anyone who had Excel would also have Access. Not so.

I create one class for every table in Access. I very rarely run queries through ADO, instead I keep that logic in the class modules. I read in with a SELECT statement and write out with and UPDATE or INSERT using the Execute method of the ADODB.Connection object.

See http://www.dailydoseofexcel.com/archives/2008/12/21/vba-framework-ii/

if you want to see how I set up my code.

To answer your questions: It will be a small learning curve for you if you already know Excel VBA, but there will be some learning to do; you will pay a performance penalty over doing it all in Access, but it's not that bad and only you can decide if it's worth it; and you can have multiple people accessing the database.

Hot to get all form elements values using jQuery?

You can use a serialize() function of JQuery:

    var datastring = $("#preview_form").serialize();
        $.ajax({
            type: "POST",
            url: "your url.php",
            data: datastring,
            success: function(data) {
                 alert('Data send');
            }
        });

And read in PHP:

echo $_POST['datastring']['dialog_box_textarea_1'];
echo $_POST['datastring']['radiobutton_1'];
........

And get ***data-**** to tag HTML5 you can see this example:

<div id="texto" data-author="Ricardo Miranda" data-date="2012-06-21">
<h4>Lorem ipsum</h4>
  <p>
    Lorem ipsum dolor sit amet, ius integre eligendi et,
    sea ut expetendis conclusionemque,
    mel at ornatus invenire. His ad moderatius definiebas omittantur,
    liber saepe albucius sea cu.
    Audire tamquam dolores vis ne, mediocrem consulatu eum ex.
    Duo te agam saepe convenire, et fugit iisque his.
 </p>

<script type="text/javascript">
$(function() {
    alert("The text is write " + $('#texto').data('author'));
});

And

<div id="texto" data-author='{"nombre":"Ricardo","apellido":"Miranda"}' data-date="2012-06-21">
   ...
</div>

<script type="text/javascript">
$(function() {
    alert("The text is write " + $('#texto').data('author').apellido + ", " +
        ('#texto').data('author').nombre);
});
</script>

JavaScript string newline character?

You can use `` quotes (wich are below Esc button) with ES6. So you can write something like this:

var text = `fjskdfjslfjsl
skfjslfkjsldfjslfjs
jfsfkjslfsljs`;

How do I merge changes to a single file, rather than merging commits?

I came across the same problem. To be precise, I have two branches A and B with the same files but a different programming interface in some files. Now the methods of file f, which is independent of the interface differences in the two branches, were changed in branch B, but the change is important for both branches. Thus, I need to merge just file f of branch B into file f of branch A.

A simple command already solved the problem for me if I assume that all changes are committed in both branches A and B:

git checkout A

git checkout --patch B f

The first command switches into branch A, into where I want to merge B's version of the file f. The second command patches the file f with f of HEAD of B. You may even accept/discard single parts of the patch. Instead of B you can specify any commit here, it does not have to be HEAD.

Community edit: If the file f on B does not exist on A yet, then omit the --patch option. Otherwise, you'll get a "No Change." message.

Right HTTP status code to wrong input

409 Conflict could be an acceptable solution.

According to: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

The doc continues with an example:

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.


In my case, I would like to PUT a string, that must be unique, to a database via an API. Before adding it to the database, I am checking that it is not already in the database.

If it is, I will return "Error: The string is already in the database", 409.

I believe this is what the OP wanted: an error code suitable for when the data does not pass the server's criteria.

Using <style> tags in the <body> with other HTML

Because this is HTML is not valid does not have any affect on the outcome ... it just means that the HTML does adhere to the standard (merely for organizational purposes). For the sake of being valid it could have been written this way:

<html>
<head>
<style type="text/css">
  p.first {color:blue}
  p.second {color:green}
</style>
</head>
<body>
<p class="first" style="color:green;">Hello World</p>
<p class="second" style="color:blue;">Hello World</p>

My guess is that the browser applies the last style it comes across.

Create dynamic URLs in Flask with url_for()

url_for in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without url_for, if there is a change in the root URL of your app then you have to change it in every page where the link is present.

Syntax: url_for('name of the function of the route','parameters (if required)')

It can be used as:

@app.route('/index')
@app.route('/')
def index():
    return 'you are in the index page'

Now if you have a link the index page:you can use this:

<a href={{ url_for('index') }}>Index</a>

You can do a lot o stuff with it, for example:

@app.route('/questions/<int:question_id>'):    #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):  
    return ('you asked for question{0}'.format(question_id))

For the above we can use:

<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>

Like this you can simply pass the parameters!

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

In my case URI, as it was defined on FB, was fine, but I was using Spring Security and it was adding ;jsessionid=0B9A5E71DAA32A01A3CD351E6CA1FCDD to my URI so, it caused the mismatching.

https://m.facebook.com/v2.5/dialog/oauth?client_id=your-fb-id-code&response_type=code&redirect_uri=https://localizator.org/auth/facebook;jsessionid=0B9A5E71DAA32A01A3CD351E6CA1FCDD&scope=email&state=b180578a-007b-48bc-bd81-4b08c6989e18

In order to avoid the URL rewriting I added disable-url-rewriting="true" to Spring Security config, in this way:

<http auto-config="true" access-denied-page="/security/accessDenied" use-expressions="true"
      disable-url-rewriting="true" entry-point-ref="authenticationEntryPoint"/> 

And it fixed my problem.

Javascript querySelector vs. getElementById

"Better" is subjective.

querySelector is the newer feature.

getElementById is better supported than querySelector.

querySelector is better supported than getElementsByClassName.

querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

You need to pick the appropriate tool for any given task.

(In the above, for querySelector read querySelector / querySelectorAll).

Get div's offsetTop positions in React

Eugene's answer uses the correct function to get the data, but for posterity I'd like to spell out exactly how to use it in React v0.14+ (according to this answer):

  import ReactDOM from 'react-dom';
  //...
  componentDidMount() {
    var rect = ReactDOM.findDOMNode(this)
      .getBoundingClientRect()
  }

Is working for me perfectly, and I'm using the data to scroll to the top of the new component that just mounted.

Get Selected value from dropdown using JavaScript

Maybe it's the comma in your if condition.

function answers() {
var answer=document.getElementById("mySelect");
 if(answer[answer.selectedIndex].value == "To measure time.") {
  alert("That's correct!"); 
 }
}

You can also write it like this.

function answers(){
 document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}

Javascript: How to loop through ALL DOM elements on a page?

As always the best solution is to use recursion:

loop(document);
function loop(node){
    // do some thing with the node here
    var nodes = node.childNodes;
    for (var i = 0; i <nodes.length; i++){
        if(!nodes[i]){
            continue;
        }

        if(nodes[i].childNodes.length > 0){
            loop(nodes[i]);
        }
    }
}

Unlike other suggestions, this solution does not require you to create an array for all the nodes, so its more light on the memory. More importantly, it finds more results. I am not sure what those results are, but when testing on chrome it finds about 50% more nodes compared to document.getElementsByTagName("*");

How can I parse a CSV string with JavaScript, which contains comma in data?

According to this blog post, this function should do it:

String.prototype.splitCSV = function(sep) {
  for (var foo = this.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--) {
    if (foo[x].replace(/'\s+$/, "'").charAt(foo[x].length - 1) == "'") {
      if ((tl = foo[x].replace(/^\s+'/, "'")).length > 1 && tl.charAt(0) == "'") {
        foo[x] = foo[x].replace(/^\s*'|'\s*$/g, '').replace(/''/g, "'");
      } else if (x) {
        foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));
      } else foo = foo.shift().split(sep).concat(foo);
    } else foo[x].replace(/''/g, "'");
  } return foo;
};

You would call it like so:

var string = "'string, duppi, du', 23, lala";
var parsed = string.splitCSV();
alert(parsed.join("|"));

This jsfiddle kind of works, but it looks like some of the elements have spaces before them.

How do I enable C++11 in gcc?

If you are using sublime then this code may work if you add it in build as code for building system. You can use this link for more information.

{
    "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\"",
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "selector": "source.c, source.c++",

    "variants":
    [
        {
            "name": "Run",
            "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
        }
    ]
}

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

If you're USING a date then I strongly advise that you use jodatime, http://joda-time.sourceforge.net/. Using System.currentTimeMillis() for fields that are dates sounds like a very bad idea because you'll end up with a lot of useless code.

Both date and calendar are seriously borked, and Calendar is definitely the worst performer of them all.

I'd advise you to use System.currentTimeMillis() when you are actually operating with milliseconds, for instance like this

 long start = System.currentTimeMillis();
    .... do something ...
 long elapsed = System.currentTimeMillis() -start;

MS Access: how to compact current database in VBA

For Access 2013, you could just do

Sendkeys "%fic"

This is the same as typing ALT, F, I, C on your keyboard.

It's probably a different sequence of letters for different versions, but the "%" symbol means "ALT", so keep that in the code. you may just need to change the letters, depending on what letters appear when you press ALT

Letters that appear when pressing ALT in Access 2013

Finding the type of an object in C++

You are looking for dynamic_cast<B*>(pointer)

Adding HTML entities using CSS content

Use the hex code for a non-breaking space. Something like this:

.breadcrumbs a:before {
    content: '>\00a0';
}

How to set variable from a SQL query?

SELECT @ModelID = modelid
FROM Models
WHERE areaid = 'South Coast'

If your select statement returns multiple values, your variable is assigned the last value that is returned.

For reference on using SELECT with variables: http://msdn.microsoft.com/en-us/library/aa259186%28SQL.80%29.aspx

What does int argc, char *argv[] mean?

Both of

int main(int argc, char *argv[]);
int main();

are legal definitions of the entry point for a C or C++ program. Stroustrup: C++ Style and Technique FAQ details some of the variations that are possible or legal for your main function.

How do I correctly clone a JavaScript object?

Simple recursive method to clone an object. Also could use lodash.clone.

_x000D_
_x000D_
let clone = (obj) => {_x000D_
 let obj2 = Array.isArray(obj) ? [] : {};_x000D_
 for(let k in obj) {_x000D_
          obj2[k] = (typeof obj[k] === 'object' ) ? clone(obj[k]) :  obj[k];_x000D_
        }_x000D_
        return obj2;_x000D_
    }_x000D_
_x000D_
let w = { name: "Apple", types: ["Fuji", "Gala"]};_x000D_
let x = clone(w);_x000D_
w.name = "Orange";_x000D_
w.types = ["Navel"];_x000D_
console.log(x);_x000D_
console.log(w);
_x000D_
_x000D_
_x000D_

In C#, how to check whether a string contains an integer?

        string text = Console.ReadLine();
        bool isNumber = false;

        for (int i = 0; i < text.Length; i++)
        {
            if (char.IsDigit(text[i]))
            {
                isNumber = true;
                break;
            }
        }

        if (isNumber)
        {
            Console.WriteLine("Text contains number.");
        }
        else
        {
            Console.WriteLine("Text doesn't contain number.");
        }

        Console.ReadKey();

Or Linq:

        string text = Console.ReadLine();

        bool isNumberOccurance =text.Any(letter => char.IsDigit(letter));
        Console.WriteLine("{0}",isDigitPresent ? "Text contains number." : "Text doesn't contain number.");
        Console.ReadKey();

Automatically start forever (node) on system restart

I wrote a script that does exactly this:

https://github.com/chovy/node-startup

I have not tried with forever, but you can customize the command it runs, so it should be straight forward:

/etc/init.d/node-app start
/etc/init.d/node-app restart
/etc/init.d/node-app stop

How would you do a "not in" query with LINQ?

 DynamicWebsiteEntities db = new DynamicWebsiteEntities();
    var data = (from dt_sub in db.Subjects_Details
                                //Sub Query - 1
                            let sub_s_g = (from sg in db.Subjects_In_Group
                                           where sg.GroupId == groupId
                                           select sg.SubjectId)
                            //Where Cause
                            where !sub_s_g.Contains(dt_sub.Id) && dt_sub.IsLanguage == false
                            //Order By Cause
                            orderby dt_sub.Subject_Name

                            select dt_sub)
                           .AsEnumerable();
                  
                                SelectList multiSelect = new SelectList(data, "Id", "Subject_Name", selectedValue);

    //======================================OR===========================================

    var data = (from dt_sub in db.Subjects_Details

                               
                            //Where Cause
                            where !(from sg in db.Subjects_In_Group
                                           where sg.GroupId == groupId
                                           select sg.SubjectId).Contains(dt_sub.Id) && dt_sub.IsLanguage == false

                            //Order By Cause
                            orderby dt_sub.Subject_Name

                            select dt_sub)

                           .AsEnumerable();

How to programmatically set cell value in DataGridView?

Try this way:

dataGridView.CurrentCell.Value = newValue;

dataGridView.EndEdit();

dataGridView.CurrentCell.Value = newValue;

dataGridView.EndEdit();

Need to write two times...

Android Studio: Unable to start the daemon process

Sometimes You just open too much applications in Windows and make the gradle have no enough memory to start the daemon process.So when you come across with this situation,you can just close some applications such as Chrome and so on. Then restart your android studio.

How to create range in Swift?

(1..<10)

returns...

Range = 1..<10

What should be the values of GOPATH and GOROOT?

If you are using the distro go, you should point to where the include files are, for example:

$ rpm -ql golang | grep include
/usr/lib/golang/include

(This is for Fedora 20)

I get Access Forbidden (Error 403) when setting up new alias

I finally got it to work.

I'm not sure if the spaces in the path were breaking things but I changed the workspace of my Aptana installation to something without spaces.

Then I uninstalled XAMPP and reinstalled it because I was thinking maybe I made a typo somewhere without noticing and figured I should be working from scratch.

Turns out Windows 7 has a service somewhere that uses port 80 which blocks apache from starting (giving it the -1) error. So I changed the port it listens to port 8080, no more conflict.

Finally I restarted my computer, for some reason XAMPP doesn't like me messing with ini files and just restarting apache wasn't doing the trick.

Anyway, this has been the most frustrating day ever so I really hope my answer ends up helping someone out!

Asserting successive calls to a mock method

You can use the Mock.call_args_list attribute to compare parameters to previous method calls. That in conjunction with Mock.call_count attribute should give you full control.

Easiest way to detect Internet connection on iOS?

Alamofire

If you are already using Alamofire for all the RESTful Api, here is what you can benifit from that.

You can add following class to your app, and call MNNetworkUtils.main.isConnected() to get a boolean on whether its connected or not.

#import Alamofire

class MNNetworkUtils {
  static let main = MNNetworkUtils()
  init() {
    manager = NetworkReachabilityManager(host: "google.com")
    listenForReachability()
  }

  private let manager: NetworkReachabilityManager?
  private var reachable: Bool = false
  private func listenForReachability() {
    self.manager?.listener = { [unowned self] status in
      switch status {
      case .notReachable:
        self.reachable = false
      case .reachable(_), .unknown:
        self.reachable = true
      }
    }
    self.manager?.startListening()
  }

  func isConnected() -> Bool {
    return reachable
  }
}

This is a singleton class. Every time, when user connect or disconnect the network, it will override self.reachable to true/false correctly, because we start listening for the NetworkReachabilityManager on singleton initialization.

Also in order to monitor reachability, you need to provide a host, currently I am using google.com feel free to change to any other hosts or one of yours if needed.

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

Another way to do this would be to by using map.

>>> a
[1, 2, 3]
>>> b
[4, 5, 6]
>>> for i,j in map(None,a,b):
    ...   print i,j
    ...
1 4
2 5
3 6

One difference in using map compared to zip is, with zip the length of new list is
same as the length of shortest list. For example:

>>> a
[1, 2, 3, 9]
>>> b
[4, 5, 6]
>>> for i,j in zip(a,b):
    ...   print i,j
    ...
1 4
2 5
3 6

Using map on same data:

>>> for i,j in map(None,a,b):
    ...   print i,j
    ...

    1 4
    2 5
    3 6
    9 None

Get unique values from arraylist in java

ArrayList values = ... // your values
Set uniqueValues = new HashSet(values); //now unique

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

for this small example:

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send(**b**'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')

while True:
    data = mysock.recv(512)
    if ( len(data) < 1 ) :
        break
    print (data);

mysock.close()

adding the "b" before 'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n' solved my problem

Can I dispatch an action in reducer?

redux-loop takes a cue from Elm and provides this pattern.

m2e error in MavenArchiver.getManifest()

I had also faced the same issue and it got resolved by commenting the version element in POM.xml as show.

org.apache.maven.archiver.[MavenArchiver](https://maven.apache.org/shared/maven-archiver/apidocs/org/apache/maven/archiver/MavenArchiver.html).getManifest(org.apache.maven.project.MavenProject, org.apache.maven.archiver.MavenArchiveConfiguration)

<plugins>
  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <!-- <version>3.5.1</version> -->
    <configuration>
      <source>1.7</source>
      <target>1.7</target>
    </configuration>
  </plugin>
  <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <!-- <version>3.1.0</version> -->
    <configuration>
      <warSourceDirectory>WebContent</warSourceDirectory>
      <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
  </plugin>
</plugins>

HTML5 best practices; section/header/aside/article elements

I'd suggest reading the W3 wiki page about structuring HTML5:

<header> Used to contain the header content of a site. <footer> Contains the footer content of a site. <nav> Contains the navigation menu, or other navigation functionality for the page.

<article> Contains a standalone piece of content that would make
sense if syndicated as an RSS item, for example a news item.

<section> Used to either group different articles into different
purposes or subjects, or to define the different sections of a single article.

<aside> Defines a block of content that is related to the main content around it, but not central to the flow of it.

They include an image that I've cleaned up here:

html5

In code, this looks like so:

<body>
  <header></header>    
  <nav></nav>    
  <section id="sidebar"></section>    
  <section id="content"></section>    
  <aside></aside>    
  <footer></footer>
</body>

Let's explore some of the HTML5 elements in more detail.

<section>

The <section> element is for containing distinct different areas of functionality or subjects area, or breaking an article or story up into different sections. So in this case: "sidebar1" contains various useful links that will persist on every page of the site, such as "subscribe to RSS" and "Buy music from store". "main" contains the main content of this page, which is blog posts. On other pages of the site, this content will change. It is a fairly generic element, but still has way more semantic meaning than the plain old <div>.

<article>

<article> is related to <section>, but is distinctly different. Whereas <section> is for grouping distinct sections of content or functionality, <article> is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then <article> is suitable for marking them up. In our example, <section id="main"> contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore <article> is perfect for them:

<section id="main">
    <article><!-- first blog post --></article>        
    <article><!-- second blog post --></article>        
    <article><!-- third blog post --></article>
</section>

Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:

<article>
  <section id="introduction"></section>      
  <section id="content"></section>
  <section id="summary"></section>
</article>

<header> and <footer>

as we already mentioned above, the purpose of the <header> and <footer> elements is to wrap header and footer content, respectively. In our particular example the <header> element contains a logo image, and the <footer> element contains a copyright notice, but you could add more elaborate content if you wished. Also note that you can have more than one header and footer on each page - as well as the top level header and footer we have just discussed, you could also have a <header> and <footer> element nested inside each <article>, in which case they would just apply to that particular article. Adding to our above example:

<article>
  <header></header>    
  <section id="introduction"></section>      
  <section id="content"></section>      
  <section id="summary"></section>      
  <footer></footer>
</article>

<nav>

The <nav> element is for marking up the navigation links or other constructs (eg a search form) that will take you to different pages of the current site, or different areas of the current page. Other links, such as sponsored links, do not count. You can of course include headings and other structuring elements inside the <nav>, but it's not compulsory.

<aside>

you may have noticed that we used an <aside> element to markup the 2nd sidebar: the one containing latest gigs and contact details. This is perfectly appropriate, as <aside> is for marking up pieces of information that are related to the main flow, but don't fit in to it directly. And the main content in this case is all about the band! Other good choices for an <aside> would be information about the author of the blog post(s), a band biography, or a band discography with links to buy their albums.

Where does that leave <div>?

So, with all these great new elements to use on our pages, the days of the humble <div> are numbered, surely? NO. In fact, the <div> still has a perfectly valid use. You should use it when there is no other more suitable element available for grouping an area of content, which will often be when you are purely using an element to group content together for styling/visual purposes. A common example is using a <div> to wrap all of the content on the page, and then using CSS to centre all the content in the browser window, or apply a specific background image to the whole content.

Programmatically generate video or animated GIF in Python?

Installation

pip install imageio-ffmpeg
pip install imageio

Code

import imageio
images = []
for filename in filenames:
    images.append(imageio.imread(filename))
imageio.mimsave('movie.mp4', images)

Quality is raised and size is reduced from 8Mb to 80Kb when saving as mp4 than gif

JavaScript alert box with timer

If you are looking for an alert that dissapears after an interval you could try the jQuery UI Dialog widget.

Delete the first five characters on any line of a text file in Linux with sed

Use cut:

cut -c6-

This prints each line of the input starting at column 6 (the first column is 1).

ScalaTest in sbt: is there a way to run a single test without tags?

Here's the Scalatest page on using the runner and the extended discussion on the -t and -z options.

This post shows what commands work for a test file that uses FunSpec.

Here's the test file:

package com.github.mrpowers.scalatest.example

import org.scalatest.FunSpec

class CardiBSpec extends FunSpec {

  describe("realName") {

    it("returns her birth name") {
      assert(CardiB.realName() === "Belcalis Almanzar")
    }

  }

  describe("iLike") {

    it("works with a single argument") {
      assert(CardiB.iLike("dollars") === "I like dollars")
    }

    it("works with multiple arguments") {
      assert(CardiB.iLike("dollars", "diamonds") === "I like dollars, diamonds")
    }

    it("throws an error if an integer argument is supplied") {
      assertThrows[java.lang.IllegalArgumentException]{
        CardiB.iLike()
      }
    }

    it("does not compile with integer arguments") {
      assertDoesNotCompile("""CardiB.iLike(1, 2, 3)""")
    }

  }

}

This command runs the four tests in the iLike describe block (from the SBT command line):

testOnly *CardiBSpec -- -z iLike

You can also use quotation marks, so this will also work:

testOnly *CardiBSpec -- -z "iLike"

This will run a single test:

testOnly *CardiBSpec -- -z "works with multiple arguments"

This will run the two tests that start with "works with":

testOnly *CardiBSpec -- -z "works with"

I can't get the -t option to run any tests in the CardiBSpec file. This command doesn't run any tests:

testOnly *CardiBSpec -- -t "works with multiple arguments"

Looks like the -t option works when tests aren't nested in describe blocks. Let's take a look at another test file:

class CalculatorSpec extends FunSpec {
  it("adds two numbers") {
    assert(Calculator.addNumbers(3, 4) === 7)
  }
}

-t can be used to run the single test:

testOnly *CalculatorSpec -- -t "adds two numbers"

-z can also be used to run the single test:

testOnly *CalculatorSpec -- -z "adds two numbers"

See this repo if you'd like to run these examples. You can find more info on running tests here.

What is the difference between user and kernel modes in operating systems?

What

Basically the difference between kernel and user modes is not OS dependent and is achieved only by restricting some instructions to be run only in kernel mode by means of hardware design. All other purposes like memory protection can be done only by that restriction.

How

It means that the processor lives in either the kernel mode or in the user mode. Using some mechanisms the architecture can guarantee that whenever it is switched to the kernel mode the OS code is fetched to be run.

Why

Having this hardware infrastructure these could be achieved in common OSes:

  • Protecting user programs from accessing whole the memory, to not let programs overwrite the OS for example,
  • preventing user programs from performing sensitive instructions such as those that change CPU memory pointer bounds, to not let programs break their memory bounds for example.

How to check if pytorch is using the GPU?

Simply from command prompt or Linux environment run the following command.

python -c 'import torch; print(torch.cuda.is_available())'

The above should print True

python -c 'import torch; print(torch.rand(2,3).cuda())'

This one should print the following:

tensor([[0.7997, 0.6170, 0.7042], [0.4174, 0.1494, 0.0516]], device='cuda:0')

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Best way to incorporate Volley (or other library) into Android Studio project

For incorporate volley in android studio,

  1. paste the following command in terminal (
    git clone https://android.googlesource.com/platform/frameworks/volley ) and run it.

    Refer android developer tutorial for this.

    It will create a folder name volley in the src directory.
  2. Then go to android studio and right click on the project.
  3. choose New -> Module from the list.
  4. Then click on import existing Project from the below list.
  5. you will see a text input area namely source directory, browse the folder you downloaded (volley) and then click on finish.
  6. you will see a folder volley in your project view.
  7. the switch to android view and open the build:gradle(Module:app) file and append the following line in the dependency area:

    compile 'com.mcxiaoke.volley:library-aar:1.0.0'

  8. Now synchronise your project and also build your project.

When should I use the new keyword in C++?

There is an important difference between the two.

Everything not allocated with new behaves much like value types in C# (and people often say that those objects are allocated on the stack, which is probably the most common/obvious case, but not always true. More precisely, objects allocated without using new have automatic storage duration Everything allocated with new is allocated on the heap, and a pointer to it is returned, exactly like reference types in C#.

Anything allocated on the stack has to have a constant size, determined at compile-time (the compiler has to set the stack pointer correctly, or if the object is a member of another class, it has to adjust the size of that other class). That's why arrays in C# are reference types. They have to be, because with reference types, we can decide at runtime how much memory to ask for. And the same applies here. Only arrays with constant size (a size that can be determined at compile-time) can be allocated with automatic storage duration (on the stack). Dynamically sized arrays have to be allocated on the heap, by calling new.

(And that's where any similarity to C# stops)

Now, anything allocated on the stack has "automatic" storage duration (you can actually declare a variable as auto, but this is the default if no other storage type is specified so the keyword isn't really used in practice, but this is where it comes from)

Automatic storage duration means exactly what it sounds like, the duration of the variable is handled automatically. By contrast, anything allocated on the heap has to be manually deleted by you. Here's an example:

void foo() {
  bar b;
  bar* b2 = new bar();
}

This function creates three values worth considering:

On line 1, it declares a variable b of type bar on the stack (automatic duration).

On line 2, it declares a bar pointer b2 on the stack (automatic duration), and calls new, allocating a bar object on the heap. (dynamic duration)

When the function returns, the following will happen: First, b2 goes out of scope (order of destruction is always opposite of order of construction). But b2 is just a pointer, so nothing happens, the memory it occupies is simply freed. And importantly, the memory it points to (the bar instance on the heap) is NOT touched. Only the pointer is freed, because only the pointer had automatic duration. Second, b goes out of scope, so since it has automatic duration, its destructor is called, and the memory is freed.

And the barinstance on the heap? It's probably still there. No one bothered to delete it, so we've leaked memory.

From this example, we can see that anything with automatic duration is guaranteed to have its destructor called when it goes out of scope. That's useful. But anything allocated on the heap lasts as long as we need it to, and can be dynamically sized, as in the case of arrays. That is also useful. We can use that to manage our memory allocations. What if the Foo class allocated some memory on the heap in its constructor, and deleted that memory in its destructor. Then we could get the best of both worlds, safe memory allocations that are guaranteed to be freed again, but without the limitations of forcing everything to be on the stack.

And that is pretty much exactly how most C++ code works. Look at the standard library's std::vector for example. That is typically allocated on the stack, but can be dynamically sized and resized. And it does this by internally allocating memory on the heap as necessary. The user of the class never sees this, so there's no chance of leaking memory, or forgetting to clean up what you allocated.

This principle is called RAII (Resource Acquisition is Initialization), and it can be extended to any resource that must be acquired and released. (network sockets, files, database connections, synchronization locks). All of them can be acquired in the constructor, and released in the destructor, so you're guaranteed that all resources you acquire will get freed again.

As a general rule, never use new/delete directly from your high level code. Always wrap it in a class that can manage the memory for you, and which will ensure it gets freed again. (Yes, there may be exceptions to this rule. In particular, smart pointers require you to call new directly, and pass the pointer to its constructor, which then takes over and ensures delete is called correctly. But this is still a very important rule of thumb)

Combining two Series into a DataFrame in pandas

Pandas will automatically align these passed in series and create the joint index They happen to be the same here. reset_index moves the index to a column.

In [2]: s1 = Series(randn(5),index=[1,2,4,5,6])

In [4]: s2 = Series(randn(5),index=[1,2,4,5,6])

In [8]: DataFrame(dict(s1 = s1, s2 = s2)).reset_index()
Out[8]: 
   index        s1        s2
0      1 -0.176143  0.128635
1      2 -1.286470  0.908497
2      4 -0.995881  0.528050
3      5  0.402241  0.458870
4      6  0.380457  0.072251

Truncating long strings with CSS: feasible yet?

Update: text-overflow: ellipsis is now supported as of Firefox 7 (released September 27th 2011). Yay! My original answer follows as a historical record.

Justin Maxwell has cross browser CSS solution. It does come with the downside however of not allowing the text to be selected in Firefox. Check out his guest post on Matt Snider's blog for the full details on how this works.

Note this technique also prevents updating the content of the node in JavaScript using the innerHTML property in Firefox. See the end of this post for a workaround.

CSS

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    -moz-binding: url('assets/xml/ellipsis.xml#ellipsis');
}

ellipsis.xml file contents

<?xml version="1.0"?>
<bindings
  xmlns="http://www.mozilla.org/xbl"
  xmlns:xbl="http://www.mozilla.org/xbl"
  xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
>
    <binding id="ellipsis">
        <content>
            <xul:window>
                <xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
            </xul:window>
        </content>
    </binding>
</bindings>

Updating node content

To update the content of a node in a way that works in Firefox use the following:

var replaceEllipsis(node, content) {
    node.innerHTML = content;
    // use your favorite framework to detect the gecko browser
    if (YAHOO.env.ua.gecko) {
        var pnode = node.parentNode,
            newNode = node.cloneNode(true);

        pnode.replaceChild(newNode, node);
    }
};

See Matt Snider's post for an explanation of how this works.

Debugging in Maven?

If you are using Netbeans, there is a nice shortcut to this. Just define a goal exec:java and add the property jpda.listen=maven Netbeans screenshot

Tested on Netbeans 7.3

The network path was not found

There may be some reasons like:

  1. Wrong SQL connection string.
  2. SQL Server in services is not running.
  3. Distributed Transaction Coordinator service is not running.

First try to connect from SQL Server Management Studio to your Remote database. If it connects it means problem is at the code side or at Visual Studio side if you are using the one.

Check the connectionstring, if the problem persists, check these two services:

  1. Distributed Transaction Coordinator service
  2. SQL Server services.

Go in services.msc and search and start these two services.

The above answer works for the Exception: [Win32Exception (0x80004005): The network path was not found]

How do I get client IP address in ASP.NET CORE?

In project.json add a dependency to:

"Microsoft.AspNetCore.HttpOverrides": "1.0.0"

In Startup.cs, in the Configure() method add:

  app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor |
            ForwardedHeaders.XForwardedProto
        });  

And, of course:

using Microsoft.AspNetCore.HttpOverrides;

Then, I could get the ip by using:

Request.HttpContext.Connection.RemoteIpAddress

In my case, when debugging in VS I got always IpV6 localhost, but when deployed on an IIS I got always the remote IP.

Some useful links: How do I get client IP address in ASP.NET CORE? and RemoteIpAddress is always null

The ::1 is maybe because of:

Connections termination at IIS, which then forwards to Kestrel, the v.next web server, so connections to the web server are indeed from localhost. (https://stackoverflow.com/a/35442401/5326387)

How to correctly link php-fpm and Nginx Docker containers?

As previous answers have solved for, but should be stated very explicitly: the php code needs to live in the php-fpm container, while the static files need to live in the nginx container. For simplicity, most people have just attached all the code to both, as I have also done below. If the future, I will likely separate out these different parts of the code in my own projects as to minimize which containers have access to which parts.

Updated my example files below with this latest revelation (thank you @alkaline )

This seems to be the minimum setup for docker 2.0 forward (because things got a lot easier in docker 2.0)

docker-compose.yml:

version: '2'
services:
  php:
    container_name: test-php
    image: php:fpm
    volumes:
      - ./code:/var/www/html/site
  nginx:
    container_name: test-nginx
    image: nginx:latest
    volumes:
      - ./code:/var/www/html/site
      - ./site.conf:/etc/nginx/conf.d/site.conf:ro
    ports:
      - 80:80

(UPDATED the docker-compose.yml above: For sites that have css, javascript, static files, etc, you will need those files accessible to the nginx container. While still having all the php code accessible to the fpm container. Again, because my base code is a messy mix of css, js, and php, this example just attaches all the code to both containers)

In the same folder:

site.conf:

server
{
    listen   80;
    server_name site.local.[YOUR URL].com;

    root /var/www/html/site;
    index index.php;

    location /
    {
        try_files $uri =404;
    }

    location ~ \.php$ {
        fastcgi_pass   test-php:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

In folder code:

./code/index.php:

<?php
phpinfo();

and don't forget to update your hosts file:

127.0.0.1 site.local.[YOUR URL].com

and run your docker-compose up

$docker-compose up -d

and try the URL from your favorite browser

site.local.[YOUR URL].com/index.php

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

The solution is already answered here above (long ago).

But the implicit question "why does it work in FF and IE but not in Chrome and Safari" is found in the error text "Not allowed to load local resource": Chrome and Safari seem to use a more strict implementation of sandboxing (for security reasons) than the other two (at this time 2011).

This applies for local access. In a (normal) server environment (apache ...) the file would simply not have been found.

pull out p-values and r-squared from a linear regression

Notice that summary(fit) generates an object with all the information you need. The beta, se, t and p vectors are stored in it. Get the p-values by selecting the 4th column of the coefficients matrix (stored in the summary object):

summary(fit)$coefficients[,4] 
summary(fit)$r.squared

Try str(summary(fit)) to see all the info that this object contains.

Edit: I had misread Chase's answer which basically tells you how to get to what I give here.

video as site background? HTML 5

I might have a solution for the video as background, stretched to the browser-width or height, (but the video will still preserve the aspect ratio, couldnt find a solution for that yet.):

Put the video right after the body-tag with style="width:100%;". Right afterwords, put a "bodydummy"-tag:

<body>
<video id="bgVideo" autoplay poster="videos/poster.png">
    <source src="videos/test-h264-640x368-highqual-winff.mp4" type="video/mp4"/>
    <source src="videos/test-640x368-webmvp8-miro.webm" type="video/webm"/>
    <source src="videos/test-640x368-theora-miro.ogv" type="video/ogg"/>    
</video>

<img id="bgImg" src="videos/poster.png" />

<!-- This image stretches exactly to the browser width/height and lies behind the video-->

<div id="bodyDummy">

Put all your content inside the bodydummy-div and put the z-indexes correctly in CSS like this:

#bgImg{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
}

#bgVideo{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
}

#bodyDummy{ 
    position: absolute;
    top: 0;
    left: 0;
    z-index: 3;
    overflow: auto;
    width: 100%;
    height: 100%;
}

Hope I could help. Let me know when you could find a solution that the video does not maintain the aspect ratio, so it could fill the whole browser window so we do not have to put a bgimage.

How do I extract data from JSON with PHP?

Intro

First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

 $data = json_decode($json);

Therein you might find:

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.


Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut

Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

Iterate over it with foreach.

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

Glazed
Chocolate with Sprinkles
Maple

Or mess about with any of the bazillion built-in array functions.


Accessing nested items

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004

Passing true as the second argument to json_decode()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key'].

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple

Accessing associative array items

When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value) syntax, eg

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}

Prints

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'


Don't know how the data is structured

Read the documentation for whatever it is you're getting the JSON from.

Look at the JSON - where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a print_r():

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

print_r($yummy);

and check the output:

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

If you can only get so far into it before you get lost - go that far and hit that with print_r():

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

Break the problem down into pieces that are easier to wrap your head around.


json_decode() returns null

This happens because either:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msg or put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.


Object property name contains a special character

Sometimes you'll have an object property name that contains something like a hyphen - or at sign @ which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

If you have an integer as property see: How to access object properties with names like integers? as reference.


Someone put JSON in your JSON

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

Data doesn't fit in memory

If your JSON is too large for json_decode() to handle at once things start to get tricky. See:


How to sort it

See: Reference: all basic ways to sort arrays and data in PHP.

How do I manage conflicts with git submodules?

If you want to use the upstream version:

rm -rf <submodule dir>
git submodule init
git submodule update

OPTION (RECOMPILE) is Always Faster; Why?

Often when there is a drastic difference from run to run of a query I find that it is often one of 5 issues.

  1. STATISTICS - Statistics are out of date. A database stores statistics on the range and distribution of the types of values in various column on tables and indexes. This helps the query engine to develop a "Plan" of attack for how it will do the query, for example the type of method it will use to match keys between tables using a hash or looking through the entire set. You can call Update Statistics on the entire database or just certain tables or indexes. This slows down the query from one run to another because when statistics are out of date, its likely the query plan is not optimal for the newly inserted or changed data for the same query (explained more later below). It may not be proper to Update Statistics immediately on a Production database as there will be some overhead, slow down and lag depending on the amount of data to sample. You can also choose to use a Full Scan or Sampling to update Statistics. If you look at the Query Plan, you can then also view the statistics on the Indexes in use such using the command DBCC SHOW_STATISTICS (tablename, indexname). This will show you the distribution and ranges of the keys that the query plan is using to base its approach on.

  2. PARAMETER SNIFFING - The query plan that is cached is not optimal for the particular parameters you are passing in, even though the query itself has not changed. For example, if you pass in a parameter which only retrieves 10 out of 1,000,000 rows, then the query plan created may use a Hash Join, however if the parameter you pass in will use 750,000 of the 1,000,000 rows, the plan created may be an index scan or table scan. In such a situation you can tell the SQL statement to use the option OPTION (RECOMPILE) or an SP to use WITH RECOMPILE. To tell the Engine this is a "Single Use Plan" and not to use a Cached Plan which likely does not apply. There is no rule on how to make this decision, it depends on knowing the way the query will be used by users.

  3. INDEXES - Its possible that the query haven't changed, but a change elsewhere such as the removal of a very useful index has slowed down the query.

  4. ROWS CHANGED - The rows you are querying drastically changes from call to call. Usually statistics are automatically updated in these cases. However if you are building dynamic SQL or calling SQL within a tight loop, there is a possibility you are using an outdated Query Plan based on the wrong drastic number of rows or statistics. Again in this case OPTION (RECOMPILE) is useful.

  5. THE LOGIC Its the Logic, your query is no longer efficient, it was fine for a small number of rows, but no longer scales. This usually involves more indepth analysis of the Query Plan. For example, you can no longer do things in bulk, but have to Chunk things and do smaller Commits, or your Cross Product was fine for a smaller set but now takes up CPU and Memory as it scales larger, this may also be true for using DISTINCT, you are calling a function for every row, your key matches don't use an index because of CASTING type conversion or NULLS or functions... Too many possibilities here.

In general when you write a query, you should have some mental picture of roughly how certain data is distributed within your table. A column for example, can have an evenly distributed number of different values, or it can be skewed, 80% of the time have a specific set of values, whether the distribution will varying frequently over time or be fairly static. This will give you a better idea of how to build an efficient query. But also when debugging query performance have a basis for building a hypothesis as to why it is slow or inefficient.

Getting Keyboard Input

You can use Scanner class

To Read from Keyboard (Standard Input) You can use Scanner is a class in java.util package.

Scanner package used for obtaining the input of the primitive types like int, double etc. and strings. It is the easiest way to read input in a Java program, though not very efficient.

  1. To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream (Keyboard).

For example, this code allows a user to read a number from System.in:

Scanner sc = new Scanner(System.in);
     int i = sc.nextInt();

Some Public methods in Scanner class.

  • hasNext() Returns true if this scanner has another token in its input.
  • nextInt() Scans the next token of the input as an int.
  • nextFloat() Scans the next token of the input as a float.
  • nextLine() Advances this scanner past the current line and returns the input that was skipped.
  • nextDouble() Scans the next token of the input as a double.
  • close() Closes this scanner.

For more details of Public methods in Scanner class.

Example:-

import java.util.Scanner;                      //importing class

class ScannerTest {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);       // Scanner object

    System.out.println("Enter your rollno");
    int rollno = sc.nextInt();
    System.out.println("Enter your name");
    String name = sc.next();
    System.out.println("Enter your fee");
    double fee = sc.nextDouble();
    System.out.println("Rollno:" + rollno + " name:" + name + " fee:" + fee);
    sc.close();                              // closing object
  }
}

How do I convert a Python program to a runnable .exe Windows program?

If it is a simple py script refer here

Else for GUI :

$ pip3 install cx_Freeze

1) Create a setup.py file and put in the same directory as of the .py file you want to convert.

2)Copy paste the following lines in the setup.py and do change the "filename.py" into the filename you specified.

from cx_Freeze import setup, Executable
setup(
    name="GUI PROGRAM",
    version="0.1",
    description="MyEXE",
    executables=[Executable("filename.py", base="Win32GUI")],
    )

3) Run the setup.py "$python setup.py build"

4)A new directory will be there there called "build". Inside it you will get your .exe file to be ready to launced directly. (Make sure you copy paste the images files and other external files into the build directory)

How to change current working directory using a batch file

Try this

chdir /d D:\Work\Root

Enjoy rooting ;)

CSS align images and text on same line

You can either use (on the h4 elements, as they are block by default)

display: inline-block;

Or you can float the elements to the left/rght

float: left;

Just don't forget to clear the floats after

clear: left;

More visual example for the float left/right option as shared below by @VSB:

_x000D_
_x000D_
<h4> _x000D_
    <div style="float:left;">Left Text</div>_x000D_
    <div style="float:right;">Right Text</div>_x000D_
    <div style="clear: left;"/>_x000D_
</h4>
_x000D_
_x000D_
_x000D_

Get page title with Selenium WebDriver using Java

You can do it easily by Assertion using Selenium Testng framework.

Steps:

1.Create Firefox browser session

2.Initialize expected title name.

3.Navigate to "www.google.com" [As per you requirement, you can change] and wait for some time (15 seconds) to load the page completely.

4.Get the actual title name using "driver.getTitle()" and store it in String variable.

5.Apply the Assertion like below, Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle ),"Page title name not matched or Problem in loading grid");

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.myapplication.Utilty;

public class PageTitleVerification
{   
private static WebDriver driver = new FirefoxDriver();

@Test
public void test01_GooglePageTitleVerify()
{               
driver.navigate().to("https://www.google.com/");
String expectedGooglePageTitle = "Google";      
Utility.waitForElementInDOM(driver, "Google Search", 15);   
//Get page title
String actualGooglePageTitlte=driver.getTitle();
System.out.println("Google page title" + actualGooglePageTitlte);   
//Verify expected page title and actual page title is same  
Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle 
),"Page title not matched or Problem in loading url page");     
}
}

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Utility {

/*Wait for an element to be present in DOM before specified time (in seconds ) has 
elapsed */
public static void waitForElementInDOM(WebDriver driver,String elementIdentifier, 
long timeOutInSeconds) 
{       
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds );
try
{
//this will wait for element to be visible for 15 seconds        
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
(elementIdentifier))); 
}
catch(NoSuchElementException e)
{           
e.printStackTrace();
}           
}
}

How can I change the value of the elements in a vector?

You might want to consider using some algorithms instead:

// read in the data:
std::copy(std::istream_iterator<double>(input), 
          std::istream_iterator<double>(),
          std::back_inserter(v));

sum = std::accumulate(v.begin(), v.end(), 0);
average = sum / v.size();

You can modify the values with std::transform, though until we get lambda expressions (C++0x) it may be more trouble than it's worth:

class difference { 
    double base;
public:
    difference(double b) : base(b) {}
    double operator()(double v) { return v-base; }
};

std::transform(v.begin(), v.end(), v.begin(), difference(average));

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

How to uninstall jupyter

For python 3.7:

  1. On windows command prompt, type: "py -m pip install pip-autoremove". You will get a successful message.
  2. Change directory, if you didn't add the following as your PATH: cd C:\Users{user_name}\AppData\Local\Programs\Python\Python37-32\Scripts To know where your package/application has been installed/located, type: "where program_name" like> where jupyter If you didn't find a location, you need to add the location in PATH.

  3. Type: pip-autoremove jupyter It will ask to type y/n to confirm the action.

How to convert an XML file to nice pandas dataframe?

Here is another way of converting a xml to pandas data frame. For example i have parsing xml from a string but this logic holds good from reading file as well.

import pandas as pd
import xml.etree.ElementTree as ET

xml_str = '<?xml version="1.0" encoding="utf-8"?>\n<response>\n <head>\n  <code>\n   200\n  </code>\n </head>\n <body>\n  <data id="0" name="All Categories" t="2018052600" tg="1" type="category"/>\n  <data id="13" name="RealEstate.com.au [H]" t="2018052600" tg="1" type="publication"/>\n </body>\n</response>'

etree = ET.fromstring(xml_str)
dfcols = ['id', 'name']
df = pd.DataFrame(columns=dfcols)

for i in etree.iter(tag='data'):
    df = df.append(
        pd.Series([i.get('id'), i.get('name')], index=dfcols),
        ignore_index=True)

df.head()

Android Studio with Google Play Services

In my case google-play-services_lib are integrate as module (External Libs) for Google map & GCM in my project.

Now, these time require to implement Google Places Autocomplete API but problem is that's code are new and my libs are old so some class not found:

following these steps...

1> Update Google play service into SDK Manager

2> select new .jar file of google play service (Sdk/extras/google/google_play_services/libproject/google-play-services_lib/libs) replace with old one

i got success...!!!

size of NumPy array

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]

8 # size

(2, 4) # shape

Confirm deletion using Bootstrap 3 modal box

$('.launchConfirm').on('click', function (e) {
    $('#confirm')
        .modal({ backdrop: 'static', keyboard: false })
        .one('click', '#delete', function (e) {
            //delete function
        });
});

FIDDLE

For your button:

<button class='btn btn-danger btn-xs launchConfirm' type="button" name="remove_levels"><span class="fa fa-times"></span> delete</button></td>

how to find my angular version in my project?

For Angular 1 or 2 (but not for Angular 4+):

You can also open the console and go to the element tab on the developer tools of whatever browser you use.

Or

Type angular.version to access the Javascript object that holds angular version.

For Angular 4+ There is are the number of ways as listed below :

Write below code in the command prompt/or in the terminal in the VS Code.

  1. ng version or ng --version (See the attachment for the reference.)
  2. ng v
  3. ng -v

In the terminal you can find the angular version as shown in the attached image : enter image description here

  1. You can also open the console and go to the element tab on the developer tools of whatever browser you use. As displayed in the below image :

enter image description here

5.Find the package.json file, You will find all the installed packages and their version.

  1. declare the variable named as 'VERSION', Import the dependencies.
import { VERSION } from '@angular/core';

// To display the version in the console.

console.log(VERSION.full); 

How to create localhost database using mysql?

removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.

Single quotes vs. double quotes in Python

' = "

/ = \ = \\

example :

f = open('c:\word.txt', 'r')
f = open("c:\word.txt", "r")
f = open("c:/word.txt", "r")
f = open("c:\\\word.txt", "r")

Results are the same

=>> no, they're not the same. A single backslash will escape characters. You just happen to luck out in that example because \k and \w aren't valid escapes like \t or \n or \\ or \"

If you want to use single backslashes (and have them interpreted as such), then you need to use a "raw" string. You can do this by putting an 'r' in front of the string

im_raw = r'c:\temp.txt'
non_raw = 'c:\\temp.txt'
another_way = 'c:/temp.txt'

As far as paths in Windows are concerned, forward slashes are interpreted the same way. Clearly the string itself is different though. I wouldn't guarantee that they're handled this way on an external device though.

How to convert float number to Binary?

Consider below example

Convert 2.625 to binary.

We will consider the integer and fractional part separately.

The integral part is easy, 2 = 10. 

For the fractional part:

0.625   × 2 =   1.25    1   Generate 1 and continue with the rest.
0.25    × 2 =   0.5     0   Generate 0 and continue.
0.5     × 2 =   1.0     1   Generate 1 and nothing remains.

So 0.625 = 0.101, and 2.625 = 10.101.

See this link for more information.

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

How to find out the server IP address (using JavaScript) that the browser is connected to?

I believe John's answer is correct. For instance, I'm using my laptop through a wifi service run by a conference centre -- I'm pretty sure that there is no way for javascript running within my browser to discover the IP address being used by the service provider. On the other hand, it may be possible to address a suitable external resource from javascript. You can write your own if your own by making an ajax call to a server which can take the IP address from the HTTP headers and return it, or try googling "find my ip". The cleanest solution is probably to capture the information before the page is served and insert it in the html returned to the user. See How to get a viewer's IP address with python? for info on how to capture the information if you are serving the page with python.

How to check for an empty object in an AngularJS view

A good and effective way is to use a "json pipe" like the following in your HTML file:

   <pre>{{ yourObject | json }}</pre>

which allows you to see clearly if the object is empty or not.

I tried quite a few ways that are showed here, but none of them worked.

How to get the nth element of a python list or a default if not available

Using Python 3.4's contextlib.suppress(exceptions) to build a getitem() method similar to getattr().

import contextlib

def getitem(iterable, index, default=None):
    """Return iterable[index] or default if IndexError is raised."""
    with contextlib.suppress(IndexError):
        return iterable[index]
    return default

IIS: Display all sites and bindings in PowerShell

Try something like this to get the format you wanted:

Get-WebBinding | % {
    $name = $_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1'
    New-Object psobject -Property @{
        Name = $name
        Binding = $_.bindinginformation.Split(":")[-1]
    }
} | Group-Object -Property Name | 
Format-Table Name, @{n="Bindings";e={$_.Group.Binding -join "`n"}} -Wrap

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

You can cast a variable that is typed as the base-class to the type of a derived class; however, by necessity this will do a runtime check, to see if the actual object involved is of the correct type.

Once created, the type of an object cannot be changed (not least, it might not be the same size). You can, however, convert an instance, creating a new instance of the second type - but you need to write the conversion code manually.

How to send JSON instead of a query string with $.ajax?

No, the dataType option is for parsing the received data.

To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

Convert an image to grayscale

Bitmap d = new Bitmap(c.Width, c.Height);

for (int i = 0; i < c.Width; i++)
{
    for (int x = 0; x < c.Height; x++)
    {
        Color oc = c.GetPixel(i, x);
        int grayScale = (int)((oc.R * 0.3) + (oc.G * 0.59) + (oc.B * 0.11));
        Color nc = Color.FromArgb(oc.A, grayScale, grayScale, grayScale);
        d.SetPixel(i, x, nc);
    }
}

This way it also keeps the alpha channel.
Enjoy.

Check for special characters (/*-+_@&$#%) in a string?

A great way using C# and Linq here:

public static bool HasSpecialCharacter(this string s)
{
    foreach (var c in s)
    {
        if(!char.IsLetterOrDigit(c))
        {
            return true;
        }
    }
    return false;
 }

And access it like this:

myString.HasSpecialCharacter();

Simplest way to form a union of two lists

I think this is all you really need to do:

var listB = new List<int>{3, 4, 5};
var listA = new List<int>{1, 2, 3, 4, 5};

var listMerged = listA.Union(listB);

'any' vs 'Object'

Object is more restrictive than any. For example:

let a: any;
let b: Object;

a.nomethod(); // Transpiles just fine
b.nomethod(); // Error: Property 'nomethod' does not exist on type 'Object'.

The Object class does not have a nomethod() function, therefore the transpiler will generate an error telling you exactly that. If you use any instead you are basically telling the transpiler that anything goes, you are providing no information about what is stored in a - it can be anything! And therefore the transpiler will allow you to do whatever you want with something defined as any.

So in short

  • any can be anything (you can call any method etc on it without compilation errors)
  • Object exposes the functions and properties defined in the Object class.

Custom Python list sorting

As a side note, here is a better alternative to implement the same sorting:

alist.sort(key=lambda x: x.foo)

Or alternatively:

import operator
alist.sort(key=operator.attrgetter('foo'))

Check out the Sorting How To, it is very useful.

Running Selenium Webdriver with a proxy in Python

The answers above and on this question either didn't work for me with Selenium 3.14 and Firefox 68.9 on Linux, or are unnecessarily complex. I needed to use a WPAD configuration, sometimes behind a proxy (on a VPN), and sometimes not. After studying the code a bit, I came up with:

from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

proxy = Proxy({'proxyAutoconfigUrl': 'http://wpad/wpad.dat'})
profile = FirefoxProfile()
profile.set_proxy(proxy)
driver = webdriver.Firefox(firefox_profile=profile)

The Proxy initialization sets proxyType to ProxyType.PAC (autoconfiguration from a URL) as a side-effect.

It also worked with Firefox's autodetect, using:

from selenium.webdriver.common.proxy import ProxyType

proxy = Proxy({'proxyType': ProxyType.AUTODETECT})

But I don't think this would work with both internal URLs (not proxied) and external (proxied) the way WPAD does. Similar proxy settings should work for manual configuration as well. The possible proxy settings can be seen in the code here.

Note that directly passing the Proxy object as proxy=proxy to the driver does NOT work--it's accepted but ignored (there should be a deprecation warning, but in my case I think Behave is swallowing it).

Python - Get path of root project structure

Try:

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

ImportError: No module named six

On Ubuntu and Debian

apt-get install python-six

does the trick.

Use sudo apt-get install python-six if you get an error saying "permission denied".

Drop all duplicate rows across multiple columns in Python Pandas

This is much easier in pandas now with drop_duplicates and the keep parameter.

import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df.drop_duplicates(subset=['A', 'C'], keep=False)

Parallel.ForEach vs Task.Factory.StartNew

In my view the most realistic scenario is when tasks have a heavy operation to complete. Shivprasad's approach focuses more on object creation/memory allocation than on computing itself. I made a research calling the following method:

public static double SumRootN(int root)
{
    double result = 0;
    for (int i = 1; i < 10000000; i++)
        {
            result += Math.Exp(Math.Log(i) / root);
        }
        return result; 
}

Execution of this method takes about 0.5sec.

I called it 200 times using Parallel:

Parallel.For(0, 200, (int i) =>
{
    SumRootN(10);
});

Then I called it 200 times using the old-fashioned way:

List<Task> tasks = new List<Task>() ;
for (int i = 0; i < loopCounter; i++)
{
    Task t = new Task(() => SumRootN(10));
    t.Start();
    tasks.Add(t);
}

Task.WaitAll(tasks.ToArray()); 

First case completed in 26656ms, the second in 24478ms. I repeated it many times. Everytime the second approach is marginaly faster.

The remote server returned an error: (403) Forbidden

Looks like problem is based on a server side.

Im my case I worked with paypal server and neither of suggested answers helped, but http://forums.iis.net/t/1217360.aspx?HTTP+403+Forbidden+error

I was facing this issue and just got the reply from Paypal technical. Add this will fix the 403 issue. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UserAgent = "[any words that is more than 5 characters]";

in_array multiple values

As a developer, you should probably start learning set operations (difference, union, intersection). You can imagine your array as one "set", and the keys you are searching for the other.

Check if ALL needles exist

function in_array_all($needles, $haystack) {
   return empty(array_diff($needles, $haystack));
}

echo in_array_all( [3,2,5], [5,8,3,1,2] ); // true, all 3, 2, 5 present
echo in_array_all( [3,2,5,9], [5,8,3,1,2] ); // false, since 9 is not present

Check if ANY of the needles exist

function in_array_any($needles, $haystack) {
   return !empty(array_intersect($needles, $haystack));
}

echo in_array_any( [3,9], [5,8,3,1,2] ); // true, since 3 is present
echo in_array_any( [4,9], [5,8,3,1,2] ); // false, neither 4 nor 9 is present

Validate decimal numbers in JavaScript - IsNumeric()

If you need to validate a special set of decimals y you can use this simple javascript:

http://codesheet.org/codesheet/x1kI7hAD

<input type="text" name="date" value="" pattern="[0-9]){1,2}(\.){1}([0-9]){2}" maxlength="6" placeholder="od npr.: 16.06" onchange="date(this);" />

The Javascript:

function date(inputField) {        
  var isValid = /^([0-9]){1,2}(\.){1}([0-9]){2}$/.test(inputField.value);   
  if (isValid) {
    inputField.style.backgroundColor = '#bfa';
  } else {
    inputField.style.backgroundColor = '#fba';
  }
  return isValid;
}

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

As for every "3rd-party" library in flavor of a JAR file which is to be used by the webapp, just copy/drop the physical JAR file in webapp's /WEB-INF/lib. It will then be available in webapp's default classpath. Also, Eclipse is smart enough to notice that. No need to hassle with buildpath. However, make sure to remove all unnecessary references you added before, else it might collide.

An alternative is to install it in the server itself by dropping the physical JAR file in server's own /lib folder. This is required when you're using server-provided JDBC connection pool data source which in turn needs the MySQL JDBC driver.

See also:

What does "static" mean in C?

If you declare a variable in a function static, its value will not be stored on the function call stack and will still be available when you call the function again.

If you declare a global variable static, its scope will be restricted to within the file in which you declared it. This is slightly safer than a regular global which can be read and modified throughout your entire program.

How to display JavaScript variables in a HTML page without document.write

innerHTML is fine and still valid. Use it all the time on projects big and small. I just flipped to an open tab in my IDE and there was one right there.

 document.getElementById("data-progress").innerHTML = "<img src='../images/loading.gif'/>";

Not much has changed in js + dom manipulation since 2005, other than the addition of more libraries. You can easily set other properties such as

   uploadElement.style.width = "100%";

How to convert a Binary String to a base 10 integer in Java

Now you want to do from binary string to Decimal but Afterword, You might be needed contrary method. It's down below.

public static String decimalToBinaryString(int value) {
    String str = "";
    while(value > 0) {
        if(value % 2 == 1) {
            str = "1"+str;
        } else {
            str = "0"+str;
        }
        value /= 2;
    }
    return str;
}

Is it possible to write to the console in colour in .NET?

class Program
{
    static void Main()
    {
        Console.BackgroundColor = ConsoleColor.Blue;
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("White on blue.");
        Console.WriteLine("Another line.");
        Console.ResetColor();
    }
}

Taken from here.

How to convert a command-line argument to int?

The approach with istringstream can be improved in order to check that no other characters have been inserted after the expected argument:

#include <sstream>

int main(int argc, char *argv[])
{
    if (argc >= 2)
    {
        std::istringstream iss( argv[1] );
        int val;

        if ((iss >> val) && iss.eof()) // Check eofbit
        {
            // Conversion successful
        }
    }

    return 0;
}

How to simulate target="_blank" in JavaScript

You can extract the href from the a tag:

window.open(document.getElementById('redirect').href);

Deck of cards JAVA

This is my implementation:

public class CardsDeck {
    private ArrayList<Card> mCards;
    private ArrayList<Card> mPulledCards;
    private Random mRandom;

public enum Suit {
    SPADES,
    HEARTS,
    DIAMONDS,
    CLUBS;
}

public enum Rank {
    TWO,
    THREE,
    FOUR,
    FIVE,
    SIX,
    SEVEN,
    EIGHT,
    NINE,
    TEN,
    JACK,
    QUEEN,
    KING,
    ACE;
}

public CardsDeck() {
    mRandom = new Random();
    mPulledCards = new ArrayList<Card>();
    mCards = new ArrayList<Card>(Suit.values().length * Rank.values().length);
    reset();
}

public void reset() {
    mPulledCards.clear();
    mCards.clear();
    /* Creating all possible cards... */
    for (Suit s : Suit.values()) {
        for (Rank r : Rank.values()) {
            Card c = new Card(s, r);
            mCards.add(c);
        }
    }
}


public static class Card {

    private Suit mSuit;
    private Rank mRank;

    public Card(Suit suit, Rank rank) {
        this.mSuit = suit;
        this.mRank = rank;
    }

    public Suit getSuit() {
        return mSuit;
    }

    public Rank getRank() {
        return mRank;
    }

    public int getValue() {
        return mRank.ordinal() + 2;
    }

    @Override
    public boolean equals(Object o) {
        return (o != null && o instanceof Card && ((Card) o).mRank == mRank && ((Card) o).mSuit == mSuit);
    }


}

/**
 * get a random card, removing it from the pack
 * @return
 */
public Card pullRandom() {
    if (mCards.isEmpty())
        return null;

    Card res = mCards.remove(randInt(0, mCards.size() - 1));
    if (res != null)
        mPulledCards.add(res);
    return res;
}

/**
 * Get a random cards, leaves it inside the pack 
 * @return
 */
public Card getRandom() {
    if (mCards.isEmpty())
        return null;

    Card res = mCards.get(randInt(0, mCards.size() - 1));
    return res;
}

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public int randInt(int min, int max) {
    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = mRandom.nextInt((max - min) + 1) + min;
    return randomNum;
}


public boolean isEmpty(){
    return mCards.isEmpty();
}
}

Get HTML5 localStorage keys

You can get keys and values like this:

for (let [key, value] of Object.entries(localStorage)) {
  console.log(`${key}: ${value}`);
}

Parse JSON in TSQL

Now there is a Native support in SQL Server (CTP3) for import, export, query and validate JSON inside T-SQL Refer to https://msdn.microsoft.com/en-us/library/dn921897.aspx

How line ending conversions work with git core.autocrlf between different operating systems

No, the @jmlane answer is wrong.

For Checkin (git add, git commit):

  1. if text property is Set, Set value to 'auto', the conversion happens enen the file has been committed with 'CRLF'
  2. if text property is Unset:nothing happens, enen for Checkout
  3. if text property is Unspecified, conversion depends on core.autocrlf
    1. if autocrlf = input or autocrlf = true, the conversion only happens when the file in the repository is 'LF', if it has been 'CRLF', nothing will happens.
    2. if autocrlf = false, nothing happens

For Checkout:

  1. if text property is Unset: nothing happens.
  2. if text property is Set, Set value to 'auto: it depends on core.autocrlf, core.eol.
    1. core.autocrlf = input : nothing happens
    2. core.autocrlf = true : the conversion only happens when the file in the repository is 'LF', 'LF' -> 'CRLF'
    3. core.autocrlf = false : the conversion only happens when the file in the repository is 'LF', 'LF' -> core.eol
  3. if text property is Unspecified, it depends on core.autocrlf.
    1. the same as 2.1
    2. the same as 2.2
    3. None, nothing happens, core.eol is not effective when text property is Unspecified

Default behavior

So the Default behavior is text property is Unspecified and core.autocrlf = false:

  1. for checkin, nothing happens
  2. for checkout, nothing happens

Conclusions

  1. if text property is set, checkin behavior is depends on itself, not on autocrlf
  2. autocrlf or core.eol is for checkout behavior, and autocrlf > core.eol

Get event listeners attached to node using addEventListener

You can obtain all jQuery events using $._data($('[selector]')[0],'events'); change [selector] to what you need.

There is a plugin that gather all events attached by jQuery called eventsReport.

Also i write my own plugin that do this with better formatting.

But anyway it seems we can't gather events added by addEventListener method. May be we can wrap addEventListener call to store events added after our wrap call.

It seems the best way to see events added to an element with dev tools.

But you will not see delegated events there. So there we need jQuery eventsReport.

UPDATE: NOW We CAN see events added by addEventListener method SEE RIGHT ANSWER TO THIS QUESTION.

jQuery datepicker to prevent past date

$("#datePicker").datePicker({startDate: new Date() });. This works for me

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

This was a problem with the user having deny privileges as well; in my haste to grant permissions I basically gave the user everything. And deny was killing it. So as soon as I removed those permissions it worked.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

This issue occurs because the Applicationhost.config file for Windows Process Activation Service (WAS) has some tags that are not compatible with the .NET Framework 4.0.

Based on your environment, you have 4 workarounds to solve this issue:

  • Updating Applicationhost.config.
  • Perform ASP.NET IIS Registration.
  • Turn on the Named Pipe Activation feature.
  • Remove ServiceModel 3.0 from IIS

Check the detailed steps for each woraround at Solving Could not load type system.servicemodel.activation.httpmodule from assembly System.ServiceModel

How to calculate difference in hours (decimal) between two dates in SQL Server?

You are probably looking for the DATEDIFF function.

DATEDIFF ( datepart , startdate , enddate )

Where you code might look like this:

DATEDIFF ( hh , startdate , enddate )

Check if a varchar is a number (TSQL)

Using SQL Server 2012+, you can use the TRY_* functions if you have specific needs. For example,

-- will fail for decimal values, but allow negative values
TRY_CAST(@value AS INT) IS NOT NULL 

-- will fail for non-positive integers; can be used with other examples below as well, or reversed if only negative desired
TRY_CAST(@value AS INT) > 0

-- will fail if a $ is used, but allow decimals to the specified precision
TRY_CAST(@value AS DECIMAL(10,2)) IS NOT NULL 

-- will allow valid currency
TRY_CAST(@value AS MONEY) IS NOT NULL  

-- will allow scientific notation to be used like 1.7E+3
TRY_CAST(@value AS FLOAT) IS NOT NULL 

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

In the examples below the client is the browser and the server is the webserver hosting the website.

Before you can understand these technologies, you have to understand classic HTTP web traffic first.

Regular HTTP:

  1. A client requests a webpage from a server.
  2. The server calculates the response
  3. The server sends the response to the client.

HTTP

Ajax Polling:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server at regular intervals (e.g. 0.5 seconds).
  3. The server calculates each response and sends it back, just like normal HTTP traffic.

Ajax Polling

Ajax Long-Polling:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server.
  3. The server does not immediately respond with the requested information but waits until there's new information available.
  4. When there's new information available, the server responds with the new information.
  5. The client receives the new information and immediately sends another request to the server, re-starting the process.

Ajax Long-Polling

HTML5 Server Sent Events (SSE) / EventSource:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection to the server.
  3. The server sends an event to the client when there's new information available.

HTML5 SSE

HTML5 Websockets:

  1. A client requests a webpage from a server using regular http (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection with the server.
  3. The server and the client can now send each other messages when new data (on either side) is available.

    • Real-time traffic from the server to the client and from the client to the server
    • You'll want to use a server that has an event loop
    • With WebSockets it is possible to connect with a server from another domain.
    • It is also possible to use a third party hosted websocket server, for example Pusher or others. This way you'll only have to implement the client side, which is very easy!
    • If you want to read more, I found these very useful: (article), (article) (tutorial).

HTML5 WebSockets

Comet:

Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications. Read more on wikipedia or this article.


Now, which one of them should I use for a realtime app (that I need to code). I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP ?

You can use PHP with WebSockets, check out Ratchet.

How to append new data onto a new line

All answers seem to work fine. If you need to do this many times, be aware that writing

hs.write(name + "\n")

constructs a new string in memory and appends that to the file.

More efficient would be

hs.write(name)
hs.write("\n")

which does not create a new string, just appends to the file.

How to declare a Fixed length Array in TypeScript

The javascript array has a constructor that accepts the length of the array:

let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]

However, this is just the initial size, there's no restriction on changing that:

arr.push(5);
console.log(arr); // [undefined × 3, 5]

Typescript has tuple types which let you define an array with a specific length and types:

let arr: [number, number, number];

arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'

Command output redirect to file and terminal

In case somebody needs to append the output and not overriding, it is possible to use "-a" or "--append" option of "tee" command :

ls 2>&1 | tee -a /tmp/ls.txt
ls 2>&1 | tee --append /tmp/ls.txt

Running Command Line in Java

import java.io.*;

Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");

Consider the following if you run into any further problems, but I'm guessing that the above will work for you:

Problems with Runtime.exec()

In Java, what is the best way to determine the size of an object?

The java.lang.instrument.Instrumentation class provides a nice way to get the size of a Java Object, but it requires you to define a premain and run your program with a java agent. This is very boring when you do not need any agent and then you have to provide a dummy Jar agent to your application.

So I got an alternative solution using the Unsafe class from the sun.misc. So, considering the objects heap alignment according to the processor architecture and calculating the maximum field offset, you can measure the size of a Java Object. In the example below I use an auxiliary class UtilUnsafe to get a reference to the sun.misc.Unsafe object.

private static final int NR_BITS = Integer.valueOf(System.getProperty("sun.arch.data.model"));
private static final int BYTE = 8;
private static final int WORD = NR_BITS/BYTE;
private static final int MIN_SIZE = 16; 

public static int sizeOf(Class src){
    //
    // Get the instance fields of src class
    // 
    List<Field> instanceFields = new LinkedList<Field>();
    do{
        if(src == Object.class) return MIN_SIZE;
        for (Field f : src.getDeclaredFields()) {
            if((f.getModifiers() & Modifier.STATIC) == 0){
                instanceFields.add(f);
            }
        }
        src = src.getSuperclass();
    }while(instanceFields.isEmpty());
    //
    // Get the field with the maximum offset
    //  
    long maxOffset = 0;
    for (Field f : instanceFields) {
        long offset = UtilUnsafe.UNSAFE.objectFieldOffset(f);
        if(offset > maxOffset) maxOffset = offset; 
    }
    return  (((int)maxOffset/WORD) + 1)*WORD; 
}
class UtilUnsafe {
    public static final sun.misc.Unsafe UNSAFE;

    static {
        Object theUnsafe = null;
        Exception exception = null;
        try {
            Class<?> uc = Class.forName("sun.misc.Unsafe");
            Field f = uc.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            theUnsafe = f.get(uc);
        } catch (Exception e) { exception = e; }
        UNSAFE = (sun.misc.Unsafe) theUnsafe;
        if (UNSAFE == null) throw new Error("Could not obtain access to sun.misc.Unsafe", exception);
    }
    private UtilUnsafe() { }
}

Can a java file have more than one class?

Yes, it can. However, there can only be one public top-level class per .java file, and public top-level classes must have the same name as the source file.

The purpose of including multiple classes in one source file is to bundle related support functionality (internal data structures, support classes, etc) together with the main public class. Note that it is always OK not to do this--the only effect is on the readability (or not) of your code.

How to copy a map?

As stated in seong's comment:

Also see http://golang.org/doc/effective_go.html#maps. The important part is really the "reference to underlying data structure". This also applies to slices.

However, none of the solutions here seem to offer a solution for a proper deep copy that also covers slices.

I've slightly altered Francesco Casula's answer to accommodate for both maps and slices.


This should cover both copying your map itself, as well as copying any child maps or slices. Both of which are affected by the same "underlying data structure" issue. It also includes a utility function for performing the same type of Deep Copy on a slice directly.

Keep in mind that the slices in the resulting map will be of type []interface{}, so when using them, you will need to use type assertion to retrieve the value in the expected type.

Example Usage

copy := CopyableMap(originalMap).DeepCopy()

Source File (util.go)

package utils

type CopyableMap   map[string]interface{}
type CopyableSlice []interface{}

// DeepCopy will create a deep copy of this map. The depth of this
// copy is all inclusive. Both maps and slices will be considered when
// making the copy.
func (m CopyableMap) DeepCopy() map[string]interface{} {
    result := map[string]interface{}{}

    for k,v := range m {
        // Handle maps
        mapvalue,isMap := v.(map[string]interface{})
        if isMap {
            result[k] = CopyableMap(mapvalue).DeepCopy()
            continue
        }

        // Handle slices
        slicevalue,isSlice := v.([]interface{})
        if isSlice {
            result[k] = CopyableSlice(slicevalue).DeepCopy()
            continue
        }

        result[k] = v
    }

    return result
}

// DeepCopy will create a deep copy of this slice. The depth of this
// copy is all inclusive. Both maps and slices will be considered when
// making the copy.
func (s CopyableSlice) DeepCopy() []interface{} {
    result := []interface{}{}

    for _,v := range s {
        // Handle maps
        mapvalue,isMap := v.(map[string]interface{})
        if isMap {
            result = append(result, CopyableMap(mapvalue).DeepCopy())
            continue
        }

        // Handle slices
        slicevalue,isSlice := v.([]interface{})
        if isSlice {
            result = append(result, CopyableSlice(slicevalue).DeepCopy())
            continue
        }

        result = append(result, v)
    }

    return result
}

Test File (util_tests.go)

package utils

import (
    "testing"

    "github.com/stretchr/testify/require"
)

func TestCopyMap(t *testing.T) {
    m1 := map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
        "c": []interface{} {
            "d", "e", map[string]interface{} {
                "f": "g",
            },
        },
    }

    m2 := CopyableMap(m1).DeepCopy()

    m1["a"] = "zzz"
    delete(m1, "b")
    m1["c"].([]interface{})[1] = "x"
    m1["c"].([]interface{})[2].(map[string]interface{})["f"] = "h"

    require.Equal(t, map[string]interface{}{
        "a": "zzz", 
        "c": []interface{} {
            "d", "x", map[string]interface{} {
                "f": "h",
            },
        },
    }, m1)
    require.Equal(t, map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
        "c": []interface{} {
            "d", "e", map[string]interface{} {
                "f": "g",
            },
        },
    }, m2)
}

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

I had the same issue. After much searching I decided to reconfigure my server in Eclipse. (ie clean it as suggested by Benson Go to Project Explorer, Servers and Delete (ensure you also delete contents on disk) Then go to Windows->Preferences->Server->Runtime Environments Remove the Tomcat server and then add it back in.

This cleans up the server.xml, webxml, context.xml files. It basically rewrites them. Something in one of mine (or multiple things) were awry and this fixes it. A bit simpler than trying to find the offending tags/lines

What operator is <> in VBA

in sql... we use it for "not equals"... I am guessing, its the same in VB aswell.

git pull while not in a git directory

This post is a bit old so could be there was a bug andit was fixed, but I just did this:

git --work-tree=/X/Y --git-dir=/X/Y/.git pull origin branch

And it worked. Took me a minute to figure out that it wanted the dotfile and the parent directory (in a standard setup those are always parent/child but not in ALL setups, so they need to be specified explicitly.

Symbol for any number of any characters in regex?

You can use this regular expression (any whitespace or any non-whitespace) as many times as possible down to and including 0.

[\s\S]*

This expression will match as few as possible, but as many as necessary for the rest of the expression.

[\s\S]*?

For example, in this regex [\s\S]*?B will match aB in aBaaaaB. But in this regex [\s\S]*B will match aBaaaaB in aBaaaaB.

USB Debugging option greyed out

After countless attempts, I found the following quote:

If you are using My KNOX, you cannot enable USB debugging mode while the container is installed. Unfortunately, you have to root your device ... - continue reading

Furthermore make sure:

  • your USB-cable works
  • your connection type is MTP (or PTP in some cases)
  • to enable USB debugging before pluging your device via USB-cable

I switched to another device without KNOX (not rooted as well) to save time. Maybe this quote will save someone some time. It was the only explanation to me in this case.

Cheers!

CSS - Syntax to select a class within an id

.navigationLevel2 li { color: #aa0000 }

Regex match one of two words

This will do:

/^(apple|banana)$/

to exclude from captured strings (e.g. $1,$2):

(?:apple|banana)