Programs & Examples On #Grok

Grok is a web framework running atop of Zope application server written in Python with aim to make Zope techonology more accessable to the masses as well as speed up the development process. Exploiting convention-over-configuration paradigm, Grok uses Zope Toolkit libraries and provides building blocks for your application along with the way to tie it all together.

Invalid Host Header when ngrok tries to connect to React dev server

I used this set up in a react app that works. I created a config file named configstrp.js that contains the following:

module.exports = {
ngrok: {
// use the local frontend port to connect
enabled: process.env.NODE_ENV !== 'production',
port: process.env.PORT || 3000,
subdomain: process.env.NGROK_SUBDOMAIN,
authtoken: process.env.NGROK_AUTHTOKEN
},   }

Require the file in the server.

const configstrp      = require('./config/configstrp.js');
const ngrok = configstrp.ngrok.enabled ? require('ngrok') : null;

and connect as such

if (ngrok) {
console.log('If nGronk')
ngrok.connect(
    {
    addr: configstrp.ngrok.port,
    subdomain: configstrp.ngrok.subdomain,
    authtoken: configstrp.ngrok.authtoken,
    host_header:3000
  },
  (err, url) => {
    if (err) {

    } else {

    }
   }
  );
 }

Do not pass a subdomain if you do not have a custom domain

ngrok command not found

For Linux :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip

For Mac :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip

For Windows:https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip

unzip it for linux and mac users move file to /usr/local/bin and execute ngrok http 80 command in the terminal

I don't have any idea about windows

pandas loc vs. iloc vs. at vs. iat?

Updated for pandas 0.20 given that ix is deprecated. This demonstrates not only how to use loc, iloc, at, iat, set_value, but how to accomplish, mixed positional/label based indexing.


loc - label based
Allows you to pass 1-D arrays as indexers. Arrays can be either slices (subsets) of the index or column, or they can be boolean arrays which are equal in length to the index or columns.

Special Note: when a scalar indexer is passed, loc can assign a new index or column value that didn't exist before.

# label based, but we can use position values
# to get the labels from the index object
df.loc[df.index[2], 'ColName'] = 3

df.loc[df.index[1:3], 'ColName'] = 3

iloc - position based
Similar to loc except with positions rather that index values. However, you cannot assign new columns or indices.

# position based, but we can get the position
# from the columns object via the `get_loc` method
df.iloc[2, df.columns.get_loc('ColName')] = 3

df.iloc[2, 4] = 3

df.iloc[:3, 2:4] = 3

at - label based
Works very similar to loc for scalar indexers. Cannot operate on array indexers. Can! assign new indices and columns.

Advantage over loc is that this is faster.
Disadvantage is that you can't use arrays for indexers.

# label based, but we can use position values
# to get the labels from the index object
df.at[df.index[2], 'ColName'] = 3

df.at['C', 'ColName'] = 3

iat - position based
Works similarly to iloc. Cannot work in array indexers. Cannot! assign new indices and columns.

Advantage over iloc is that this is faster.
Disadvantage is that you can't use arrays for indexers.

# position based, but we can get the position
# from the columns object via the `get_loc` method
IBM.iat[2, IBM.columns.get_loc('PNL')] = 3

set_value - label based
Works very similar to loc for scalar indexers. Cannot operate on array indexers. Can! assign new indices and columns

Advantage Super fast, because there is very little overhead!
Disadvantage There is very little overhead because pandas is not doing a bunch of safety checks. Use at your own risk. Also, this is not intended for public use.

# label based, but we can use position values
# to get the labels from the index object
df.set_value(df.index[2], 'ColName', 3)

set_value with takable=True - position based
Works similarly to iloc. Cannot work in array indexers. Cannot! assign new indices and columns.

Advantage Super fast, because there is very little overhead!
Disadvantage There is very little overhead because pandas is not doing a bunch of safety checks. Use at your own risk. Also, this is not intended for public use.

# position based, but we can get the position
# from the columns object via the `get_loc` method
df.set_value(2, df.columns.get_loc('ColName'), 3, takable=True)

Split data frame string column into multiple columns

Yet another approach: use rbind on out:

before <- data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))  
out <- strsplit(as.character(before$type),'_and_') 
do.call(rbind, out)

     [,1]  [,2]   
[1,] "foo" "bar"  
[2,] "foo" "bar_2"
[3,] "foo" "bar"  
[4,] "foo" "bar_2"

And to combine:

data.frame(before$attr, do.call(rbind, out))

Unicode (UTF-8) reading and writing to files in Python

except for codecs.open(), one can uses io.open() to work with Python2 or Python3 to read / write unicode file

example

import io

text = u'á'
encoding = 'utf8'

with io.open('data.txt', 'w', encoding=encoding, newline='\n') as fout:
    fout.write(text)

with io.open('data.txt', 'r', encoding=encoding, newline='\n') as fin:
    text2 = fin.read()

assert text == text2

Difference between Hashing a Password and Encrypting it

Hashing is a one-way function, meaning that once you hash a password it is very difficult to get the original password back from the hash. Encryption is a two-way function, where it's much easier to get the original text back from the encrypted text.

Plain hashing is easily defeated using a dictionary attack, where an attacker just pre-hashes every word in a dictionary (or every combination of characters up to a certain length), then uses this new dictionary to look up hashed passwords. Using a unique random salt for each hashed password stored makes it much more difficult for an attacker to use this method. They would basically need to create a new unique dictionary for every salt value that you use, slowing down their attack terribly.

It's unsafe to store passwords using an encryption algorithm because if it's easier for the user or the administrator to get the original password back from the encrypted text, it's also easier for an attacker to do the same.

What is "loose coupling?" Please provide examples

Tightly coupled code relies on a concrete implementation. If I need a list of strings in my code and I declare it like this (in Java)

ArrayList<String> myList = new ArrayList<String>();

then I'm dependent on the ArrayList implementation.

If I want to change that to loosely coupled code, I make my reference an interface (or other abstract) type.

List<String> myList = new ArrayList<String>();

This prevents me from calling any method on myList that's specific to the ArrayList implementation. I'm limited to only those methods defined in the List interface. If I decide later that I really need a LinkedList, I only need to change my code in one place, where I created the new List, and not in 100 places where I made calls to ArrayList methods.

Of course, you can instantiate an ArrayList using the first declaration and restrain yourself from not using any methods that aren't part of the List interface, but using the second declaration makes the compiler keep you honest.

Vertically aligning text next to a radio button

I think this is what you might be asking for

http://jsbin.com/ixowuw/2/

CSS

label{
  font-size:18px;
  vertical-align: middle;
}

input[type="radio"]{
  vertical-align: middle;
}

HTML

<span>
  <input type="radio" id="oddsPref" name="oddsPref" value="decimal" />
  <label>Decimal</label>
</span>

What is the difference between IQueryable<T> and IEnumerable<T>?

The primary difference is that the LINQ operators for IQueryable<T> take Expression objects instead of delegates, meaning the custom query logic it receives, e.g., a predicate or value selector, is in the form of an expression tree instead of a delegate to a method.

  • IEnumerable<T> is great for working with sequences that are iterated in-memory, but
  • IQueryable<T> allows for out-of memory things like a remote data source, such as a database or web service.

Query execution:

  • Where the execution of a query is going to be performed "in process", typically all that's required is the code (as code) to execute each part of the query.

  • Where the execution will be performed out-of-process, the logic of the query has to be represented in data such that the LINQ provider can convert it into the appropriate form for the out-of-memory execution - whether that's an LDAP query, SQL or whatever.

More in:

http://www.codeproject.com/KB/cs/646361/WhatHowWhere.jpg

What's the best practice for putting multiple projects in a git repository?

Solution 3

This is for using a single directory for multiple projects. I use this technique for some closely related projects where I often need to pull changes from one project into another. It's similar to the orphaned branches idea but the branches don't need to be orphaned. Simply start all the projects from the same empty directory state.

Start all projects from one committed empty directory

Don't expect wonders from this solution. As I see it, you are always going to have annoyances with untracked files. Git doesn't really have a clue what to do with them and so if there are intermediate files generated by a compiler and ignored by your .gitignore file, it is likely that they will be left hanging some of the time if you try rapidly swapping between - for example - your software project and a PH.D thesis project.

However here is the plan. Start as you ought to start any git projects, by committing the empty repository, and then start all your projects from the same empty directory state. That way you are certain that the two lots of files are fairly independent. Also, give your branches a proper name and don't lazily just use "master". Your projects need to be separate so give them appropriate names.

Git commits (and hence tags and branches) basically store the state of a directory and its subdirectories and Git has no idea whether these are parts of the same or different projects so really there is no problem for git storing different projects in the same repository. The problem is then for you clearing up the untracked files from one project when using another, or separating the projects later.

Create an empty repository

cd some_empty_directory
git init
touch .gitignore
git add .gitignore
git commit -m empty
git tag EMPTY

Start your projects from empty.

Work on one project.

git branch software EMPTY
git checkout software
echo "array board[8,8] of piece" > chess.prog

git add chess.prog 
git commit -m "chess program"

Start another project

whenever you like.

git branch thesis EMPTY
git checkout thesis
echo "the meaning of meaning" > philosophy_doctorate.txt
git add philosophy_doctorate.txt 
git commit -m "Ph.D"

Switch back and forth

Go back and forwards between projects whenever you like. This example goes back to the chess software project.

git checkout software
echo "while not end_of_game do make_move()" >> chess.prog
git add chess.prog 
git commit -m "improved chess program"

Untracked files are annoying

You will however be annoyed by untracked files when swapping between projects/branches.

touch untracked_software_file.prog
git checkout thesis 
ls
    philosophy_doctorate.txt  untracked_software_file.prog

It's not an insurmountable problem

Sort of by definition, git doesn't really know what to do with untracked files and it's up to you to deal with them. You can stop untracked files from being carried around from one branch to another as follows.

git checkout EMPTY 
ls
    untracked_software_file.prog
rm -r *
    (directory is now really empty, apart from the repository stuff!)
git checkout thesis
ls
    philosophy_doctorate.txt

By ensuring that the directory was empty before checking out our new project we made sure there were no hanging untracked files from another project.

A refinement

$ GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01T01:01:01' git commit -m empty

If the same dates are specified whenever committing an empty repository, then independently created empty repository commits can have the same SHA1 code. This allows two repositories to be created independently and then merged together into a single tree with a common root in one repository later.

Example

# Create thesis repository. 
# Merge existing chess repository branch into it

mkdir single_repo_for_thesis_and_chess
cd single_repo_for_thesis_and_chess
git init
touch .gitignore
git add .gitignore
GIT_AUTHOR_DATE='2001-01-01:T01:01:01' GIT_COMMITTER_DATE='2001-01-01:T01:01:01' git commit -m empty
git tag EMPTY
echo "the meaning of meaning" > thesis.txt
git add thesis.txt
git commit -m "Wrote my PH.D"
git branch -m master thesis

# It's as simple as this ...
git remote add chess ../chessrepository/.git
git fetch chess chess:chess

Result

Diagram of merged repositories

Use subdirectories per project?

It may also help if you keep your projects in subdirectories where possible, e.g. instead of having files

chess.prog
philosophy_doctorate.txt 

have

chess/chess.prog
thesis/philosophy_doctorate.txt 

In this case your untracked software file will be chess/untracked_software_file.prog. When working in the thesis directory you should not be disturbed by untracked chess program files, and you may find occasions when you can work happily without deleting untracked files from other projects.

Also, if you want to remove untracked files from other projects, it will be quicker (and less prone to error) to dump an unwanted directory than to remove unwanted files by selecting each of them.

Branch names can include '/' characters

So you might want to name your branches something like

project1/master
project1/featureABC
project2/master
project2/featureXYZ

What is the maximum possible length of a .NET string?

Based on my highly scientific and accurate experiment, it tops out on my machine well before 1,000,000,000 characters. (I'm still running the code below to get a better pinpoint).

UPDATE: After a few hours, I've given up. Final results: Can go a lot bigger than 100,000,000 characters, instantly given System.OutOfMemoryException at 1,000,000,000 characters.

using System;
using System.Collections.Generic;

public class MyClass
{
    public static void Main()
    {
        int i = 100000000;
        try
        {
            for (i = i; i <= int.MaxValue; i += 5000)
            {
                string value = new string('x', i);
                //WL(i);
            }
        }
        catch (Exception exc)
        {
            WL(i);
            WL(exc);
        }
        WL(i);
        RL();
    }

    #region Helper methods

    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);   
    }

    private static void RL()
    {
        Console.ReadLine(); 
    }

    private static void Break() 
    {
        System.Diagnostics.Debugger.Break();
    }

    #endregion
}

How can I use JQuery to post JSON data?

The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.

_x000D_
_x000D_
var Data = {_x000D_
"name":"jonsa",_x000D_
"e-mail":"[email protected]",_x000D_
"phone":1223456789_x000D_
};_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
    type: 'POST',_x000D_
    url: '/form/',_x000D_
    data: Data,_x000D_
    success: function(data) { alert('data: ' + data); },_x000D_
    contentType: "application/json",_x000D_
    dataType: 'json'_x000D_
});
_x000D_
_x000D_
_x000D_

Do Java arrays have a maximum size?

This is (of course) totally VM-dependent.

Browsing through the source code of OpenJDK 7 and 8 java.util.ArrayList, .Hashtable, .AbstractCollection, .PriorityQueue, and .Vector, you can see this claim being repeated:

/**
 * Some VMs reserve some header words in an array.
 * Attempts to allocate larger arrays may result in
 * OutOfMemoryError: Requested array size exceeds VM limit
 */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

which is added by Martin Buchholz (Google) on 2010-05-09; reviewed by Chris Hegarty (Oracle).

So, probably we can say that the maximum "safe" number would be 2 147 483 639 (Integer.MAX_VALUE - 8) and "attempts to allocate larger arrays may result in OutOfMemoryError".

(Yes, Buchholz's standalone claim does not include backing evidence, so this is a calculated appeal to authority. Even within OpenJDK itself, we can see code like return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; which shows that MAX_ARRAY_SIZE does not yet have a real use.)

Where should I put the CSS and Javascript code in an HTML webpage?

Put Stylesheets at the Top Links to discussion

While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively.

Front-end engineers that care about performance want a page to load progressively; that is, we want the browser to display whatever content it has as soon as possible. This is especially important for pages with a lot of content and for users on slower Internet connections. The importance of giving users visual feedback, such as progress indicators, has been well researched and documented. In our case the HTML page is the progress indicator! When the browser loads the page progressively the header, the navigation bar, the logo at the top, etc. all serve as visual feedback for the user who is waiting for the page. This improves the overall user experience.

The problem with putting stylesheets near the bottom of the document is that it prohibits progressive rendering in many browsers, including Internet Explorer. These browsers block rendering to avoid having to redraw elements of the page if their styles change. The user is stuck viewing a blank white page.

The HTML specification clearly states that stylesheets are to be included in the HEAD of the page: "Unlike A, [LINK] may only appear in the HEAD section of a document, although it may appear any number of times." Neither of the alternatives, the blank white screen or flash of unstyled content, are worth the risk. The optimal solution is to follow the HTML specification and load your stylesheets in the document HEAD.

Put Scripts at the Bottom

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.

An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.

Read SQL Table into C# DataTable

Here, give this a shot (this is just a pseudocode)

using System;
using System.Data;
using System.Data.SqlClient;


public class PullDataTest
{
    // your data table
    private DataTable dataTable = new DataTable();

    public PullDataTest()
    {
    }

    // your method to pull data from database to datatable   
    public void PullData()
    {
        string connString = @"your connection string here";
        string query = "select * from table";

        SqlConnection conn = new SqlConnection(connString);        
        SqlCommand cmd = new SqlCommand(query, conn);
        conn.Open();

        // create data adapter
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        // this will query your database and return the result to your datatable
        da.Fill(dataTable);
        conn.Close();
        da.Dispose();
    }
}

Update R using RStudio

I found that for me the best permanent solution to stay up-to-date under Linux was to install the R-patched project. This will keep your R installation up-to-date, and you needn't even move your packages between installations (which is described in RyanStochastic's answer).

For openSUSE, see the instructions here.

How to create new folder?

Have you tried os.mkdir?

You might also try this little code snippet:

mypath = ...
if not os.path.isdir(mypath):
   os.makedirs(mypath)

makedirs creates multiple levels of directories, if needed.

Generate random numbers with a given (numerical) distribution

Another answer, probably faster :)

distribution = [(1, 0.2), (2, 0.3), (3, 0.5)]  
# init distribution  
dlist = []  
sumchance = 0  
for value, chance in distribution:  
    sumchance += chance  
    dlist.append((value, sumchance))  
assert sumchance == 1.0 # not good assert because of float equality  

# get random value  
r = random.random()  
# for small distributions use lineair search  
if len(distribution) < 64: # don't know exact speed limit  
    for value, sumchance in dlist:  
        if r < sumchance:  
            return value  
else:  
    # else (not implemented) binary search algorithm  

Debugging iframes with Chrome developer tools

When the iFrame points to your site like this:

<html>
  <head>
    <script type="text/javascript" src="/jquery.js"></script>
  </head>
  <body>
    <iframe id="my_frame" src="/wherev"></iframe>
  </body>
</html>

You can access iFrame DOM through this kind of thing.

var iframeBody = $(window.my_frame.document.getElementsByTagName("body")[0]);
iframeBody.append($("<h1/>").html("Hello world!"));

How to initialize a list with constructor?

You can initialize it just like any list:

public List<ContactNumber> ContactNumbers { get; set; }

public Human(int id)
{
    Id = id;
    ContactNumbers = new List<ContactNumber>();
}

public Human(int id, string address, string name) :this(id)
{
    Address = address;
    Name = name;
    // no need to initialize the list here since you're
    // already calling the single parameter constructor
}       

However, I would even go a step further and make the setter private since you often don't need to set the list, but just access/modify its contents:

public List<ContactNumber> ContactNumbers { get; private set; }

get and set in TypeScript

TypeScript uses getter/setter syntax that is like ActionScript3.

class foo {
    private _bar: boolean = false;
    get bar(): boolean {
        return this._bar;
    }
    set bar(value: boolean) {
        this._bar = value;
    }
}

That will produce this JavaScript, using the ECMAScript 5 Object.defineProperty() feature.

var foo = (function () {
    function foo() {
        this._bar = false;
    }
    Object.defineProperty(foo.prototype, "bar", {
        get: function () {
            return this._bar;
        },
        set: function (value) {
            this._bar = value;
        },
        enumerable: true,
        configurable: true
    });
    return foo;
})();

So to use it,

var myFoo = new foo();
if(myFoo.bar) {         // calls the getter
    myFoo.bar = false;  // calls the setter and passes false
}

However, in order to use it at all, you must make sure the TypeScript compiler targets ECMAScript5. If you are running the command line compiler, use --target flag like this;

tsc --target ES5

If you are using Visual Studio, you must edit your project file to add the flag to the configuration for the TypeScriptCompile build tool. You can see that here:

As @DanFromGermany suggests below, if your are simply reading and writing a local property like foo.bar = true, then having a setter and getter pair is overkill. You can always add them later if you need to do something, like logging, whenever the property is read or written.

Positioning <div> element at center of screen

Alternative solution that doesn't use position absolute:
I see a lot of position absolute answers. I couldn't use position absolute without breaking something else. So for those that couldn't as well, here is what I did:
https://stackoverflow.com/a/58622840/6546317 (posted in response to another question).

The solution only focuses on vertically centering because my children elements were already horizontally centered but same could be applied if you couldn't horizontally center them in another way.

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

What are the applications of binary trees?

To squabble about the performance of binary-trees is meaningless - they are not a data structure, but a family of data structures, all with different performance characteristics. While it is true that unbalanced binary trees perform much worse than self-balancing binary trees for searching, there are many binary trees (such as binary tries) for which "balancing" has no meaning.

Applications of binary trees

  • Binary Search Tree - Used in many search applications where data is constantly entering/leaving, such as the map and set objects in many languages' libraries.
  • Binary Space Partition - Used in almost every 3D video game to determine what objects need to be rendered.
  • Binary Tries - Used in almost every high-bandwidth router for storing router-tables.
  • Hash Trees - used in p2p programs and specialized image-signatures in which a hash needs to be verified, but the whole file is not available.
  • Heaps - Used in implementing efficient priority-queues, which in turn are used for scheduling processes in many operating systems, Quality-of-Service in routers, and A* (path-finding algorithm used in AI applications, including robotics and video games). Also used in heap-sort.
  • Huffman Coding Tree (Chip Uni) - used in compression algorithms, such as those used by the .jpeg and .mp3 file-formats.
  • GGM Trees - Used in cryptographic applications to generate a tree of pseudo-random numbers.
  • Syntax Tree - Constructed by compilers and (implicitly) calculators to parse expressions.
  • Treap - Randomized data structure used in wireless networking and memory allocation.
  • T-tree - Though most databases use some form of B-tree to store data on the drive, databases which keep all (most) their data in memory often use T-trees to do so.

The reason that binary trees are used more often than n-ary trees for searching is that n-ary trees are more complex, but usually provide no real speed advantage.

In a (balanced) binary tree with m nodes, moving from one level to the next requires one comparison, and there are log_2(m) levels, for a total of log_2(m) comparisons.

In contrast, an n-ary tree will require log_2(n) comparisons (using a binary search) to move to the next level. Since there are log_n(m) total levels, the search will require log_2(n)*log_n(m) = log_2(m) comparisons total. So, though n-ary trees are more complex, they provide no advantage in terms of total comparisons necessary.

(However, n-ary trees are still useful in niche-situations. The examples that come immediately to mind are quad-trees and other space-partitioning trees, where divisioning space using only two nodes per level would make the logic unnecessarily complex; and B-trees used in many databases, where the limiting factor is not how many comparisons are done at each level but how many nodes can be loaded from the hard-drive at once)

Regex allow digits and a single dot

\d*\.\d*

Explanation:

\d* - any number of digits

\. - a dot

\d* - more digits.

This will match 123.456, .123, 123., but not 123

If you want the dot to be optional, in most languages (don't know about jquery) you can use

\d*\.?\d*

Element-wise addition of 2 lists?

It's simpler to use numpy from my opinion:

import numpy as np
list1=[1,2,3]
list2=[4,5,6]
np.add(list1,list2)

Results:

Terminal execution

For detailed parameter information, check here: numpy.add

How to check if a file exists from a url

You have to use CURL

function does_url_exists($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($code == 200) {
        $status = true;
    } else {
        $status = false;
    }
    curl_close($ch);
    return $status;
}

CSS: how to add white space before element's content?

/* Most Accurate Setting if you only want
   to do this with CSS Pseudo Element */
p:before { 
   content: "\00a0";
   padding-right: 5px; /* If you need more space b/w contents */
}

Best way to remove items from a collection

@smaclell asked why reverse iteration was more efficient in in a comment to @sambo99.

Sometimes it's more efficient. Consider you have a list of people, and you want to remove or filter all customers with a credit rating < 1000;

We have the following data

"Bob" 999
"Mary" 999
"Ted" 1000

If we were to iterate forward, we'd soon get into trouble

for( int idx = 0; idx < list.Count ; idx++ )
{
    if( list[idx].Rating < 1000 )
    {
        list.RemoveAt(idx); // whoops!
    }
}

At idx = 0 we remove Bob, which then shifts all remaining elements left. The next time through the loop idx = 1, but list[1] is now Ted instead of Mary. We end up skipping Mary by mistake. We could use a while loop, and we could introduce more variables.

Or, we just reverse iterate:

for (int idx = list.Count-1; idx >= 0; idx--)
{
    if (list[idx].Rating < 1000)
    {
        list.RemoveAt(idx);
    }
}

All the indexes to the left of the removed item stay the same, so you don't skip any items.

The same principle applies if you're given a list of indexes to remove from an array. In order to keep things straight you need to sort the list and then remove the items from highest index to lowest.

Now you can just use Linq and declare what you're doing in a straightforward manner.

list.RemoveAll(o => o.Rating < 1000);

For this case of removing a single item, it's no more efficient iterating forwards or backwards. You could also use Linq for this.

int removeIndex = list.FindIndex(o => o.Name == "Ted");
if( removeIndex != -1 )
{
    list.RemoveAt(removeIndex);
}

Stored procedure return into DataSet in C# .Net

I should tell you the basic steps and rest depends upon your own effort. You need to perform following steps.

  • Create a connection string.
  • Create a SQL connection
  • Create SQL command
  • Create SQL data adapter
  • fill your dataset.

Do not forget to open and close connection. follow this link for more under standing.

What is tempuri.org?

Unfortunately the tempuri.org URL now just redirects to Bing.

You can see what it used to render via archive.org:

https://web.archive.org/web/20090304024056/http://tempuri.org/

To quote:

Each XML Web Service needs a unique namespace in order for client applications to distinguish it from other services on the Web. By default, ASP.Net Web Services use http://tempuri.org/ for this purpose. While this suitable for XML Web Services under development, published services should use a unique, permanent namespace.

Your XML Web Service should be identified by a namespace that you control. For example, you can use your company's Internet domain name as part of the namespace. Although many namespaces look like URLs, they need not point to actual resources on the Web.

For XML Web Services creating[sic] using ASP.NET, the default namespace can be changed using the WebService attribute's Namespace property. The WebService attribute is applied to the class that contains the XML Web Service methods. Below is a code example that sets the namespace to "http://microsoft.com/webservices/":

C#

[WebService(Namespace="http://microsoft.com/webservices/")]
public class MyWebService {
   // implementation
}

Visual Basic.NET

<WebService(Namespace:="http://microsoft.com/webservices/")> Public Class MyWebService
    ' implementation
End Class

Visual J#.NET

/**@attribute WebService(Namespace="http://microsoft.com/webservices/")*/
public class MyWebService {
    // implementation
}

It's also worth reading section 'A 1.3 Generating URIs' at:

http://www.w3.org/TR/wsdl#_Toc492291092

How to send and receive JSON data from a restful webservice using Jersey API

Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.

@Path("/hello")
public class Hello {

  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {

    String input = (String) inputJsonObj.get("input");
    String output = "The input you sent is :" + input;
    JSONObject outputJsonObj = new JSONObject();
    outputJsonObj.put("output", output);

    return outputJsonObj;
  }
}

And, your client code should look like this:

  ClientConfig config = new DefaultClientConfig();
  Client client = Client.create(config);
  client.addFilter(new LoggingFilter());
  WebResource service = client.resource(getBaseURI());
  JSONObject inputJsonObj = new JSONObject();
  inputJsonObj.put("input", "Value");
  System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));

Shuffling a list of objects

you can either use shuffle or sample . both of which come from random module.

import random
def shuffle(arr1):
    n=len(arr1)
    b=random.sample(arr1,n)
    return b

OR

import random
def shuffle(arr1):
    random.shuffle(arr1)
    return arr1

Fatal error: Call to undefined function sqlsrv_connect()

This helped me get to my answer. There are two php.ini files located, in my case, for wamp. One is under the php folder and the other one is in the C:\wamp\bin\apache\Apachex.x.x\bin folder. When connecting to SQL through sqlsrv_connect function, we are referring to the php.ini file in the apache folder. Add the following (as per your version) to this file:

extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

.Net framework of the referencing dll should be same as the .Net framework version of the Project in which dll is referred

Convert RGB to Black & White in OpenCV

A simple way of "binarize" an image is to compare to a threshold: For example you can compare all elements in a matrix against a value with opencv in c++

cv::Mat img = cv::imread("image.jpg", CV_LOAD_IMAGE_GRAYSCALE); 
cv::Mat bw = img > 128;

In this way, all pixels in the matrix greater than 128 now are white, and these less than 128 or equals will be black

Optionally, and for me gave good results is to apply blur

cv::blur( bw, bw, cv::Size(3,3) );

Later you can save it as said before with:

cv::imwrite("image_bw.jpg", bw);

How to convert a byte array to its numeric value (Java)?

public static long byteArrayToLong(byte[] bytes) {
    return ((long) (bytes[0]) << 56)
            + (((long) bytes[1] & 0xFF) << 48)
            + ((long) (bytes[2] & 0xFF) << 40)
            + ((long) (bytes[3] & 0xFF) << 32)
            + ((long) (bytes[4] & 0xFF) << 24)
            + ((bytes[5] & 0xFF) << 16)
            + ((bytes[6] & 0xFF) << 8)
            + (bytes[7] & 0xFF);
}

convert bytes array (long is 8 bytes) to long

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Any time you get the...

"Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given"

...it is likely because there is an issue with your query. The prepare() or query() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!

First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:

error_reporting(E_ALL);
ini_set('display_errors', 1);

If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.

Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:

$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();

The error is generic and not very helpful to you in solving what is going on.

With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.

$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
    $query->bind_param('s', $definition);
    $query->execute();
    // any additional code you need would go here.
} else {
    $error = $mysqli->errno . ' ' . $mysqli->error; // 1054 Unknown column 'foo' in 'field list'
    // handle error
}

If something is wrong you can spit out an error message which takes you directly to the issue. In this case, there is no foo column in the table, solving the problem is trivial.

If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.

Nested classes' scope?

Easiest solution:

class OuterClass:
    outer_var = 1
    class InnerClass:
        def __init__(self):
            self.inner_var = OuterClass.outer_var

It requires you to be explicit, but doesn't take much effort.

Split Strings into words with multiple word boundary delimiters

I like pprzemek's solution because it does not assume that the delimiters are single characters and it doesn't try to leverage a regex (which would not work well if the number of separators got to be crazy long).

Here's a more readable version of the above solution for clarity:

def split_string_on_multiple_separators(input_string, separators):
    buffer = [input_string]
    for sep in separators:
        strings = buffer
        buffer = []  # reset the buffer
        for s in strings:
            buffer = buffer + s.split(sep)

    return buffer

How to create a sub array from another array in Java?

I you are using java prior to version 1.6 use System.arraycopy() instead. Or upgrade your environment.

Unit testing click event in Angular

Events can be tested using the async/fakeAsync functions provided by '@angular/core/testing', since any event in the browser is asynchronous and pushed to the event loop/queue.

Below is a very basic example to test the click event using fakeAsync.

The fakeAsync function enables a linear coding style by running the test body in a special fakeAsync test zone.

Here I am testing a method that is invoked by the click event.

it('should', fakeAsync( () => {
    fixture.detectChanges();
    spyOn(componentInstance, 'method name'); //method attached to the click.
    let btn = fixture.debugElement.query(By.css('button'));
    btn.triggerEventHandler('click', null);
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(componentInstance.methodName).toHaveBeenCalled();
}));

Below is what Angular docs have to say:

The principle advantage of fakeAsync over async is that the test appears to be synchronous. There is no then(...) to disrupt the visible flow of control. The promise-returning fixture.whenStable is gone, replaced by tick()

There are limitations. For example, you cannot make an XHR call from within a fakeAsync

Filter by Dates in SQL

WHERE dates BETWEEN (convert(datetime, '2012-12-12',110) AND (convert(datetime, '2012-12-12',110))

Using group by on two fields and count in SQL

I think you're looking for: SELECT a, b, COUNT(a) FROM tbl GROUP BY a, b

Why does Java's hashCode() in String use 31 as a multiplier?

This is because 31 has a nice property – it's multiplication can be replaced by a bitwise shift which is faster than the standard multiplication:

31 * i == (i << 5) - i

Where can I view Tomcat log files in Eclipse?

Double click and open the server. Go to 'Arguments'. -Dcatalina.base= .. something. Go to that something. Your logs are there.

PostgreSQL IF statement

DO
$do$
BEGIN
   IF EXISTS (SELECT FROM orders) THEN
      DELETE FROM orders;
   ELSE
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

There are no procedural elements in standard SQL. The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command.

You need a semicolon (;) at the end of each statement in plpgsql (except for the final END).

You need END IF; at the end of the IF statement.

A sub-select must be surrounded by parentheses:

    IF (SELECT count(*) FROM orders) > 0 ...

Or:

    IF (SELECT count(*) > 0 FROM orders) ...

This is equivalent and much faster, though:

    IF EXISTS (SELECT FROM orders) ...

Alternative

The additional SELECT is not needed. This does the same, faster:

DO
$do$
BEGIN
   DELETE FROM orders;
   IF NOT FOUND THEN
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

Though unlikely, concurrent transactions writing to the same table may interfere. To be absolutely sure, write-lock the table in the same transaction before proceeding as demonstrated.

Laravel Check If Related Model Exists

I prefer to use exists method:

RepairItem::find($id)->option()->exists()

to check if related model exists or not. It's working fine on Laravel 5.2

Android: how to parse URL String with spaces to URI object?

To handle spaces, @, and other unsafe characters in arbitrary locations in the url path, Use Uri.Builder in combination with a local instance of URL as I have described here:

private Uri.Builder builder;
public Uri getUriFromUrl(String thisUrl) {
    URL url = new URL(thisUrl);
    builder =  new Uri.Builder()
                            .scheme(url.getProtocol())
                            .authority(url.getAuthority())
                            .appendPath(url.getPath());
    return builder.build();
}

Missing Microsoft RDLC Report Designer in Visual Studio

The setup feature does not work on Visual Studio 2017 and later versions.

The extension needs to be downloaded from VS Marketplace and then installed - Link

The same applies to other extensions such as Installer Projects (used for creating executable files) - Link

MySQL direct INSERT INTO with WHERE clause

you can use UPDATE command.

UPDATE table_name SET name=@name, email=@email, phone=@phone WHERE client_id=@client_id

data.frame rows to a list

Like this:

xy.list <- split(xy.df, seq(nrow(xy.df)))

And if you want the rownames of xy.df to be the names of the output list, you can do:

xy.list <- setNames(split(xy.df, seq(nrow(xy.df))), rownames(xy.df))

Best ways to teach a beginner to program?

Microsoft Small Basic is a free .NET based programming environment aimed to be a "fun" learning environment for beginners. The language is a subset of VB.NET and even contains a "Turtle" object familiar from the Logo language. The website contains a step-by-step tutorial.

How can I count occurrences with groupBy?

Here is example for list of Objects

Map<String, Long> requirementCountMap = requirements.stream().collect(Collectors.groupingBy(Requirement::getRequirementType, Collectors.counting()));

How to install psycopg2 with "pip" on Python?

In Arch base distributions:

sudo pacman -S python-psycopg2
pip2 install psycopg2  # Use pip or pip3 to python3

Using BigDecimal to work with currencies

Primitive numeric types are useful for storing single values in memory. But when dealing with calculation using double and float types, there is a problems with the rounding.It happens because memory representation doesn't map exactly to the value. For example, a double value is supposed to take 64 bits but Java doesn't use all 64 bits.It only stores what it thinks the important parts of the number. So you can arrive to the wrong values when you adding values together of the float or double type.

Please see a short clip https://youtu.be/EXxUSz9x7BM

How to cancel/abort jQuery AJAX request?

Why should you abort the request?

If each request takes more than five seconds, what will happen?

You shouldn't abort the request if the parameter passing with the request is not changing. eg:- the request is for retrieving the notification data. In such situations, The nice approach is that set a new request only after completing the previous Ajax request.

$(document).ready(

    var fn = function(){

        $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            },

            complete: function(){setTimeout(fn, 500);}
        });
    };

     var interval = setTimeout(fn, 500);

);

How to get a Docker container's IP address from the host

There are various ways to get the IP of the container from the host

_x000D_
_x000D_
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' containerID
_x000D_
_x000D_
_x000D_

If in case you can't remember the above command you can always do the following

docker inspect containerID

It will Return low-level information on Docker objects after the information is returned look for "Networks" and inside it you will find "IPAddress" of container

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Entity Framework Provider type could not be loaded?

I had same isssue i tried many times but it did not resolve but when i install the package EntityFramework.SqlServerCompact it solved install this package from Nuget package Manager.

Install-Package EntityFramework.SqlServerCompact

What are the differences between C, C# and C++ in terms of real-world applications?

My opinion is C# and ASP.NET would be the best of the three for development that is web biased.

I doubt anyone writes new web apps in C or C++ anymore. It was done 10 years ago, and there's likely a lot of legacy code still in use, but they're not particularly well suited, there doesn't appear to be as much (ongoing) tool support, and they probably have a small active community that does web development (except perhaps for web server development). I wrote many website C++ COM objects back in the day, but C# is far more productive that there's no compelling reason to code C or C++ (in this context) unless you need to.

I do still write C++ if necessary, but it's typically for a small problem domain. e.g. communicating from C# via P/Invoke to old C-style dll's - doing some things that are downright clumsy in C# were a breeze to create a C++ COM object as a bridge.

The nice thing with C# is that you can also easily transfer into writing Windows and Console apps and stay in C#. With Mono you're also not limited to Windows (although you may be limited to which libraries you use).

Anyways this is all from a web-biased perspective. If you asked about embedded devices I'd say C or C++. You could argue none of these are suited for web development, but C#/ASP.NET is pretty slick, it works well, there are heaps of online resources, a huge community, and free dev tools.

So from a real-world perspective, picking only one of C#, C++ and C as requested, as a general rule, you're better to stick with C#.

How can I set a UITableView to grouped style

If you have one TableView for more tables, and one of this tables is grouped and the another one plain, than you can simulate the plain style with the function from UITableViewDelegate:

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {   
    return CGFloat.min
}

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

Your problem is that you have 64-bit eclipse running but you have 32 bit JRE.So please download JRE for 64 bit windows and let it install on the default location. Finally add that path till bin in your PATH variable. Try it should work.

What is a stack trace, and how can I use it to debug my application errors?

Just to add to the other examples, there are inner(nested) classes that appear with the $ sign. For example:

public class Test {

    private static void privateMethod() {
        throw new RuntimeException();
    }

    public static void main(String[] args) throws Exception {
        Runnable runnable = new Runnable() {
            @Override public void run() {
                privateMethod();
            }
        };
        runnable.run();
    }
}

Will result in this stack trace:

Exception in thread "main" java.lang.RuntimeException
        at Test.privateMethod(Test.java:4)
        at Test.access$000(Test.java:1)
        at Test$1.run(Test.java:10)
        at Test.main(Test.java:13)

Requery a subform from another form?

Just a comment on the method of accomplishing this:

You're making your EntryForm permanently tied to the form you're calling it from. I think it's better to not have forms tied to context like that. I'd remove the requery from the Save/Close routine and instead open the EntryForm modally, using the acDialog switch:

  DoCmd.OpenForm "EntryForm", , ,"[ID]=" & Me!SubForm.Form!ID, , acDialog
  Me!SubForm.Form.Requery

That way, EntryForm is not tied down to use in one context. The alternative is to complicate EntryForm with something that is knowledgable of which form opened it and what needs to requeried. I think it's better to keep that kind of thing as close to the context in which it's used, and keep the called form's code as simple as possible.

Perhaps a principle here is that any time you are requerying a form using the Forms collection from another form, it's a good indication something's not right about your architecture -- that should happen seldom, in my opinion.

Can promises have multiple arguments to onFulfilled?

I'm following the spec here and I'm not sure whether it allows onFulfilled to be called with multiple arguments.

Nope, just the first parameter will be treated as resolution value in the promise constructor. You can resolve with a composite value like an object or array.

I don't care about how any specific promises implementation does it, I wish to follow the w3c spec for promises closely.

That's where I believe you're wrong. The specification is designed to be minimal and is built for interoperating between promise libraries. The idea is to have a subset which DOM futures for example can reliably use and libraries can consume. Promise implementations do what you ask with .spread for a while now. For example:

Promise.try(function(){
    return ["Hello","World","!"];
}).spread(function(a,b,c){
    console.log(a,b+c); // "Hello World!";
});

With Bluebird. One solution if you want this functionality is to polyfill it.

if (!Promise.prototype.spread) {
    Promise.prototype.spread = function (fn) {
        return this.then(function (args) {
            return Promise.all(args); // wait for all
        }).then(function(args){
         //this is always undefined in A+ complaint, but just in case
            return fn.apply(this, args); 
        });
    };
}

This lets you do:

Promise.resolve(null).then(function(){
    return ["Hello","World","!"]; 
}).spread(function(a,b,c){
    console.log(a,b+c);    
});

With native promises at ease fiddle. Or use spread which is now (2018) commonplace in browsers:

Promise.resolve(["Hello","World","!"]).then(([a,b,c]) => {
  console.log(a,b+c);    
});

Or with await:

let [a, b, c] = await Promise.resolve(['hello', 'world', '!']);

What does "Object reference not set to an instance of an object" mean?

It means you did something like this.

Class myObject = GetObjectFromFunction();

And without doing

if(myObject!=null), you go ahead do myObject.Method();

How can one pull the (private) data of one's own Android app?

After setting the right permissions by adding the following code:

File myFile = ...;
myFile.setReadable(true, false); // readable, not only for the owner

adb pull works as desired.

see File.setReadable()

addClass and removeClass in jQuery - not removing class

Whenever I see addClass and removeClass I think why not just use toggleClass. In this case we can remove the .clickable class to avoid event bubbling, and to avoid the event from being fired on everything we click inside of the .clickable div.

$(document).on("click", ".close_button", function () { 
    $(this).closest(".grown").toggleClass("spot grown clickable");
});  

$(document).on("click", ".clickable", function () {
    $(this).toggleClass("spot grown clickable");
}); 

I also recommend a parent wrapper for your .clickable divs instead of using the document. I am not sure how you are adding them dynamically so didn't want to assume your layout for you.

http://jsfiddle.net/bplumb/ECQg5/2/

Happy Coding :)

How to expand a list to function arguments in Python

That can be done with:

foo(*values)

Show message box in case of exception

        try
        {
           // your code
        }
        catch (Exception w)
        {
            MessageDialog msgDialog = new MessageDialog(w.ToString());
        }

References with text in LaTeX

I think you can do this with the hyperref package, although I've not tried it myself. From the relevant LaTeX Wikibook section:

The hyperref package introduces another useful command; \autoref{}. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command \autoref{sec:intro} would create a hyperlink to the \label{sec:intro} command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining \typeautorefname to the prefix you want, as in:

\def\subsectionautorefname{section}

How to write multiple conditions in Makefile.am with "else if"

I would accept ldav1s' answer if I were you, but I just want to point out that 'else if' can be written in terms of 'else's and 'if's in any language:

if HAVE_CLIENT
  libtest_LIBS = $(top_builddir)/libclient.la
else
  if HAVE_SERVER
    libtest_LIBS = $(top_builddir)/libserver.la
  else
    libtest_LIBS = 
  endif
endif

(The indentation is for clarity. Don't indent the lines, they won't work.)

Apply Calibri (Body) font to text

There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).

So use just font-family: Calibri or, better, font-family: Calibri, sans-serif. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)

POST request via RestTemplate in JSON

For me error occurred with this setup:

AndroidAnnotations Spring Android RestTemplate Module and ...

GsonHttpMessageConverter

Android annotations has some problems with this converted to generate POST request without parameter. Simply parameter new Object() solved it for me.

Variable might not have been initialized error

You haven't initialised a and b, only declared them. There is a subtle difference.

int a = 0;
int b = 0;

At least this is for C++, I presume Java is the same concept.

How to multi-line "Replace in files..." in Notepad++

Actually it's way easier to use ToolBucket plugin for Notepad++ to multiline replace.

To activate it just go to N++ menu:

Plugins > Plugin Manager > Show Plugin Manager > Check ToolBucket > Install.

Restart N++ and press ALT + SHIFT + F to multiline edit.

Char to int conversion in C

int i = c - '0';

You should be aware that this doesn't perform any validation against the character - for example, if the character was 'a' then you would get 91 - 48 = 49. Especially if you are dealing with user or network input, you should probably perform validation to avoid bad behavior in your program. Just check the range:

if ('0' <= c &&  c <= '9') {
    i = c - '0';
} else {
    /* handle error */
}

Note that if you want your conversion to handle hex digits you can check the range and perform the appropriate calculation.

if ('0' <= c && c <= '9') {
    i = c - '0';
} else if ('a' <= c && c <= 'f') {
    i = 10 + c - 'a';
} else if ('A' <= c && c <= 'F') {
    i = 10 + c - 'A';
} else {
    /* handle error */
}

That will convert a single hex character, upper or lowercase independent, into an integer.

Writing your own square root function

In general the square root of an integer (like 2, for example) can only be approximated (not because of problems with floating point arithmetic, but because they're irrational numbers which can't be calculated exactly).

Of course, some approximations are better than others. I mean, of course, that the value 1.732 is a better approximation to the square root of 3, than 1.7

The method used by the code at that link you gave works by taking a first approximation and using it to calculate a better approximation.

This is called Newton's Method, and you can repeat the calculation with each new approximation until it's accurate enough for you.

In fact there must be some way to decide when to stop the repetition or it will run forever.

Usually you would stop when the difference between approximations is less than a value you decide.

EDIT: I don't think there can be a simpler implementation than the two you already found.

Finding three elements in an array whose sum is closest to a given number

I did this in n^3, my pseudocode is below;

//Create a hashMap with key as Integer and value as ArrayList //iterate through list using a for loop, for each value in list iterate again starting from next value;

for (int i=0; i<=arr.length-1 ; i++){
    for (int j=i+1; j<=arr.length-1;j++){

//if the sum of arr[i] and arr[j] is less than desired sum then there is potential to find a third digit so do another for loop

      if (arr[i]+arr[j] < sum){
        for (int k= j+1; k<=arr.length-1;k++)

//in this case we are now looking for the third value; if the sum of arr[i] and arr[j] and arr[k] is the desired sum then add these to the HashMap by making the arr[i] the key and then adding arr[j] and arr[k] into the ArrayList in the value of that key

          if (arr[i]+arr[j]+arr[k] ==  sum){              
              map.put(arr[i],new ArrayList<Integer>());
              map.get(arr[i]).add(arr[j]);
              map.get(arr[i]).add(arr[k]);}

after this you now have a dictionary that has all the entries representing the three values adding to the desired sum. Extract all these entries using HashMap functions. This worked perfectly.

Passing arguments to require (when loading module)

Yes. In your login module, just export a single function that takes the db as its argument. For example:

module.exports = function(db) {
  ...
};

User Control - Custom Properties

Just add public properties to the user control.

You can add [Category("MyCategory")] and [Description("A property that controls the wossname")] attributes to make it nicer, but as long as it's a public property it should show up in the property panel.

String to HtmlDocument

I've adapted Nikhil's answer somewhat to simplify it. Admittedly, I have not run it through a .net compiler and there are likely very good reasons for the lines Nikhil put in which I have omitted. However, at least in my use case (a very simple page) they were unnecessary.

My use case was for a quick powershell script:

$htmlText = $(New-Object 
System.Net.WebClient).DownloadString("<URI HERE>") #Get the HTML document from a webserver
$browser = New-Object System.Windows.Forms.WebBrowser
$browser.DocumentText = $htmlText
$browser.Document.Write($htmlText)
$response = $browser.document

For my case, this returned an HTMLDocument object with HTMLElement objects in it, instead of __ComObject object types (which are a challenge to use in powershell class code) returned by a call to Invoke-WebRequest in PS 5.1.14393.1944

I believe the equivalent C# code is:

public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
{
    WebBrowser browser = new WebBrowser();
    browser.DocumentText = html;
    browser.Document.Write(html);
    return browser.Document;
}

Access multiple elements of list knowing their index

Static indexes and small list?

Don't forget that if the list is small and the indexes don't change, as in your example, sometimes the best thing is to use sequence unpacking:

_,a1,a2,_,_,a3,_ = a

The performance is much better and you can also save one line of code:

 %timeit _,a1,b1,_,_,c1,_ = a
10000000 loops, best of 3: 154 ns per loop 
%timeit itemgetter(*b)(a)
1000000 loops, best of 3: 753 ns per loop
 %timeit [ a[i] for i in b]
1000000 loops, best of 3: 777 ns per loop
 %timeit map(a.__getitem__, b)
1000000 loops, best of 3: 1.42 µs per loop

How do I use FileSystemObject in VBA?

After adding the reference, I had to use

Dim fso As New Scripting.FileSystemObject

JavaScript listener, "keypress" doesn't detect backspace?

KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc.

UPDATE:

The keypress event is fired when a key is pressed down and that key normally produces a character value

Reference.

Why does NULL = NULL evaluate to false in SQL server

The concept of NULL is questionable, to say the least. Codd introduced the relational model and the concept of NULL in context (and went on to propose more than one kind of NULL!) However, relational theory has evolved since Codd's original writings: some of his proposals have since been dropped (e.g. primary key) and others never caught on (e.g. theta operators). In modern relational theory (truly relational theory, I should stress) NULL simply does not exist. See The Third Manifesto. http://www.thethirdmanifesto.com/

The SQL language suffers the problem of backwards compatibility. NULL found its way into SQL and we are stuck with it. Arguably, the implementation of NULL in SQL is flawed (SQL Server's implementation makes things even more complicated due to its ANSI_NULLS option).

I recommend avoiding the use of NULLable columns in base tables.


Although perhaps I shouldn't be tempted, I just wanted to assert a corrections of my own about how NULL works in SQL:

NULL = NULL evaluates to UNKNOWN.

UNKNOWN is a logical value.

NULL is a data value.

This is easy to prove e.g.

SELECT NULL = NULL

correctly generates an error in SQL Server. If the result was a data value then we would expect to see NULL, as some answers here (wrongly) suggest we would.

The logical value UNKNOWN is treated differently in SQL DML and SQL DDL respectively.

In SQL DML, UNKNOWN causes rows to be removed from the resultset.

For example:

CREATE TABLE MyTable
(
 key_col INTEGER NOT NULL UNIQUE, 
 data_col INTEGER
 CHECK (data_col = 55)
);

INSERT INTO MyTable (key_col, data_col)
   VALUES (1, NULL);

The INSERT succeeds for this row, even though the CHECK condition resolves to NULL = NULL. This is due defined in the SQL-92 ("ANSI") Standard:

11.6 table constraint definition

3)

If the table constraint is a check constraint definition, then let SC be the search condition immediately contained in the check constraint definition and let T be the table name included in the corresponding table constraint descriptor; the table constraint is not satisfied if and only if

EXISTS ( SELECT * FROM T WHERE NOT ( SC ) )

is true.

Read that again carefully, following the logic.

In plain English, our new row above is given the 'benefit of the doubt' about being UNKNOWN and allowed to pass.

In SQL DML, the rule for the WHERE clause is much easier to follow:

The search condition is applied to each row of T. The result of the where clause is a table of those rows of T for which the result of the search condition is true.

In plain English, rows that evaluate to UNKNOWN are removed from the resultset.

how to remove css property using javascript?

You can use the styleSheets object:

document.styleSheets[0].cssRules[0].style.removeProperty("zoom");

Caveat #1: You have to know the index of your stylesheet and the index of your rule.

Caveat #2: This object is implemented inconsistently by the browsers; what works in one may not work in the others.

RestTemplate: How to send URL and query parameters together

An issue with the answer from Michal Foksa is that it adds the query parameters first, and then expands the path variables. If query parameter contains parenthesis, e.g. {foobar}, this will cause an exception.

The safe way is to expand the path variables first, and then add the query parameters:

String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
URI uri = UriComponentsBuilder.fromUriString(url)
        .buildAndExpand(params)
        .toUri();
uri = UriComponentsBuilder
        .fromUri(uri)
        .queryParam("name", "myName")
        .build()
        .toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);

Is it possible to use global variables in Rust?

It's possible but no heap allocation allowed directly. Heap allocation is performed at runtime. Here are a few examples:

static SOME_INT: i32 = 5;
static SOME_STR: &'static str = "A static string";
static SOME_STRUCT: MyStruct = MyStruct {
    number: 10,
    string: "Some string",
};
static mut db: Option<sqlite::Connection> = None;

fn main() {
    println!("{}", SOME_INT);
    println!("{}", SOME_STR);
    println!("{}", SOME_STRUCT.number);
    println!("{}", SOME_STRUCT.string);

    unsafe {
        db = Some(open_database());
    }
}

struct MyStruct {
    number: i32,
    string: &'static str,
}

mvn command is not recognized as an internal or external command

I have a stupid comment but someone else will have that issue. I was getting that same error when I was trying to put in ./mvnw clean package and I found out that I had to change it a bit to .\mvnw clean packageand I lived happily ever after.

How to break out of nested loops?

for(int i = 0; i < 1000; i++) {
   for(int j = 0; j < 1000; i++) {
       if(condition) {
            goto end;
   }
} 

end:

Java Date - Insert into database

you can use this code date and time time is 24 h

INSERT INTO TABLE_NAME(
  date_column
)values(
  TO_DATE('2016-10-05 10:53:56', 'SYYYY-MM-DD HH24:MI:SS')
)

How to get current timestamp in milliseconds since 1970 just the way Java gets

use <sys/time.h>

struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;

refer this.

javascript - Create Simple Dynamic Array

var arr = [];
for(var i=1; i<=mynumber; i++) {
   arr.push(i.toString());
}

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

console.log showing contents of array object

Seems like Firebug or whatever Debugger you are using, is not initialized properly. Are you sure Firebug is fully initialized when you try to access the console.log()-method? Check the Console-Tab (if it's set to activated).

Another possibility could be, that you overwrite the console-Object yourself anywhere in the code.

What is the right way to write my script 'src' url for a local development environment?

Write the src tag for calling the js file as

<script type='text/javascript' src='../Users/myUserName/Desktop/myPage.js'></script>

This should work.

How to implement an android:background that doesn't stretch?

I am using an ImageView in an RelativeLayout that overlays with my normal layout. No code required. It sizes the image to the full height of the screen (or any other layout you use) and then crops the picture left and right to fit the width. In my case, if the user turns the screen, the picture may be a tiny bit too small. Therefore I use match_parent, which will make the image stretch in width if too small.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/main_backgroundImage"
        android:layout_width="match_parent"
        //comment: Stretches picture in the width if too small. Use "wrap_content" does not stretch, but leaves space

        android:layout_height="match_parent"
        //in my case I always want the height filled

        android:layout_alignParentTop="true"
        android:scaleType="centerCrop"
        //will crop picture left and right, so it fits in height and keeps aspect ratio

        android:contentDescription="@string/image"
        android:src="@drawable/your_image" />

    <LinearLayout
        android:id="@+id/main_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

How to resolve ORA 00936 Missing Expression Error?

This happens every time you insert/ update and you don't use single quotes. When the variable is empty it will result in that error. Fix it by using ''

Assuming the first parameter is an empty variable here is a simple example:

Wrong

nvl( ,0)

Fix

nvl('' ,0)

Put your query into your database software and check it for that error. Generally this is an easy fix

How can I merge the columns from two tables into one output?

I guess that what you want to do is an UNION of both tables.

If both tables have the same columns then you can just do

SELECT category_id, col1, col2, col3
  FROM items_a
UNION 
SELECT category_id, col1, col2, col3 
  FROM items_b

Else, you might have to do something like

SELECT category_id, col1, col2, col3
  FROM items_a 
UNION 
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
  FROM items_b

How can I get date in application run by node.js?

GMT -03:00 Example

new Date(new Date()-3600*1000*3).toISOString();

What does "subject" mean in certificate?

The subject of the certificate is the entity its public key is associated with (i.e. the "owner" of the certificate).

As RFC 5280 says:

The subject field identifies the entity associated with the public key stored in the subject public key field. The subject name MAY be carried in the subject field and/or the subjectAltName extension.

X.509 certificates have a Subject (Distinguished Name) field and can also have multiple names in the Subject Alternative Name extension.

The Subject DN is made of multiple relative distinguished names (RDNs) (themselves made of attribute assertion values) such as "CN=yourname" or "O=yourorganization".

In the context of the article you're linking to, the subject would be the user/owner of the cert.

Check whether a table contains rows or not sql server 2005

Like Other said you can use something like that:

IF NOT EXISTS (SELECT 1 FROM Table)
  BEGIN 
    --Do Something
  END 
ELSE
  BEGIN
    --Do Another Thing
  END

How to implement OnFragmentInteractionListener

Just an addendum:

OnFragmentInteractionListener handle communication between Activity and Fragment using an interface (OnFragmentInteractionListener) and is created by default by Android Studio, but if you dont need to communicate with your activity, you can just get ride of it.

The goal is that you can attach your fragment to multiple activities and still reuse the same communication approach (Every activity could have its own OnFragmentInteractionListener for each fragment).

But and if im sure my fragment will be attached to only one type of activity and i want to communicate with that activity?

Then, if you dont want to use OnFragmentInteractionListener because of its verbosity, you can access your activity methods using:

((MyActivityClass) getActivity()).someMethod()

How to make layout with rounded corners..?

Use CardView to get rounded edges for any layouts. Use card_view:cardCornerRadius="5dp" for cardview to get rounded layout edges.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:card_view="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

      <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="5dp">
          <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="15dp"
                android:weightSum="1">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".3"
                    android:text="@string/quote_code"
                    android:textColor="@color/white"
                    android:textSize="@dimen/text_head_size" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".7"
                    android:text="@string/quote_details"
                    android:textColor="@color/white"
                    android:textSize="@dimen/text_head_size" />
            </LinearLayout>
       </android.support.v7.widget.CardView>
   </LinearLayout>

How can I iterate JSONObject to get individual items

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

How do I get list of all tables in a database using TSQL?

select * from sysobjects where xtype='U'

In Perl, how do I create a hash whose keys come from a given array?

#!/usr/bin/perl -w

use strict;
use Data::Dumper;

my @a = qw(5 8 2 5 4 8 9);
my @b = qw(7 6 5 4 3 2 1);
my $h = {};

@{$h}{@a} = @b;

print Dumper($h);

gives (note repeated keys get the value at the greatest position in the array - ie 8->2 and not 6)

$VAR1 = {
          '8' => '2',
          '4' => '3',
          '9' => '1',
          '2' => '5',
          '5' => '4'
        };

Firefox 'Cross-Origin Request Blocked' despite headers

In my case CORS error was happening only in POST requests with file attachments other than small files.

After many wasted hours we found out request was blocked for users who were using Kaspersky Total Control.

It's possible that other antivirus or firewall software may cause similar problems. Kaspersky run some security tests for requests, but omits them for websites with SSL EV certificate, so obtaining such certificate should resolve this issue properly.

Disabling protection for your domain is a bit tricky, so here are required steps (as for December 2020): Settings -> Network Settings -> Manage exclusions -> Add -> your domain -> Save

The good thing is you can detect such blocked request. The error is empty – it doesn't have status and response. This way you can assume it was blocked by third party software and show some info.

Redirecting to a new page after successful login

First of all, move all your PHP code to the top. Without it, my code below wont work.

To do the redirect, use:

header('Location: http://www.example.com/');

Also, please consider my advice. Since it's not the first question today and all your questions are related to basics, you should consider reading some good PHP book to understand how things work.

Here you can find useful links to free books: https://stackoverflow.com/tags/php/info

Material Design not styling alert dialogs

AppCompat doesn't do that for dialogs (not yet at least)

EDIT: it does now. make sure to use android.support.v7.app.AlertDialog

What is the easiest way to initialize a std::vector with hardcoded elements?

If you can, use the modern C++[11,14,17,...] way:

std::vector<int> vec = {10,20,30};

The old way of looping over a variable-length array or using sizeof() is truly terrible on the eyes and completely unnecessary in terms of mental overhead. Yuck.

How to determine if a string is a number with C++?

Yet another answer, that uses stold (though you could also use stof/stod if you don't require the precision).

bool isNumeric(const std::string& string)
{
    std::size_t pos;
    long double value = 0.0;

    try
    {
        value = std::stold(string, &pos);
    }
    catch(std::invalid_argument&)
    {
        return false;
    }
    catch(std::out_of_range&)
    {
        return false;
    }

    return pos == string.size() && !std::isnan(value);
}

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

You are getting AttributeError because you're calling groups on None, which hasn't any methods.

regex.search returning None means the regex couldn't find anything matching the pattern from supplied string.

when using regex, it is nice to check whether a match has been made:

Result = re.search(SearchStr, htmlString)

if Result:
    print Result.groups()

Make Axios send cookies in its requests automatically

Another solution is to use this library:

https://github.com/3846masa/axios-cookiejar-support

which integrates "Tough Cookie" support in to Axios. Note that this approach still requires the withCredentials flag.

Reading numbers from a text file into an array in C

change to

fscanf(myFile, "%1d", &numberArray[i]);

Creating a range of dates in Python

I thought I'd throw in my two cents with a simple (and not complete) implementation of a date range:

from datetime import date, timedelta, datetime

class DateRange:
    def __init__(self, start, end, step=timedelta(1)):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        start = self.start
        step = self.step
        end = self.end

        n = int((end - start) / step)
        d = start

        for _ in range(n):
            yield d
            d += step

    def __contains__(self, value):
        return (
            (self.start <= value < self.end) and 
            ((value - self.start) % self.step == timedelta(0))
        )

Can I set a TTL for @Cacheable

When using Redis, TTL can be set in properties file like this:

spring.cache.redis.time-to-live=1d # 1 day

spring.cache.redis.time-to-live=5m # 5 minutes

spring.cache.redis.time-to-live=10s # 10 seconds

How do I sort a vector of pairs based on the second element of the pair?

For something reusable:

template<template <typename> class P = std::less >
struct compare_pair_second {
    template<class T1, class T2> bool operator()(const std::pair<T1, T2>& left, const std::pair<T1, T2>& right) {
        return P<T2>()(left.second, right.second);
    }
};

You can use it as

std::sort(foo.begin(), foo.end(), compare_pair_second<>());

or

std::sort(foo.begin(), foo.end(), compare_pair_second<std::less>());

Passing html values into javascript functions

Here is the JSfiddle Demo

I changed your HTML and give your input textfield an id of value. I removed the passed param for your verifyorder function, and instead grab the content of your textfield by using document.getElementById(); then i convert the str into value with +order so you can check if it's greater than zero:

<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p> 

function verifyorder() {
        var order = document.getElementById('value').value;
        if (+order > 0) {
            alert(+order);
            return true;
        }
        else {
            alert("Sorry, you need to enter a positive integer value, try again");
            document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
        }
    }

How to install Laravel's Artisan?

Use the project's root folder

Artisan comes with Laravel by default, if your php command works fine, then the only thing you need to do is to navigate to the project's root folder. The root folder is the parent folder of the app folder. For example:

cd c:\Program Files\xampp\htdocs\your-project-name

Now the php artisan list command should work fine, because PHP runs the file called artisan in the project's folder.

Install the framework

Keep in mind that Artisan runs scripts stored in the vendor folder, so if you installed Laravel without Composer, like downloading and extracting the Laravel GitHub repo, then you don't have the framework itself and you may get the following error when you try to use Artisan:

Could not open input file: artisan

To solve this you have to install the framework itself by running composer install in your project's root folder.

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I got the following error:

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)

I fixed this by changing my hibernate properties file

hibernate.current_session_context_class=thread

My code and configuration file as follows

session =  getHibernateTemplate().getSessionFactory().getCurrentSession();

session.beginTransaction();

session.createQuery(Qry).executeUpdate();

session.getTransaction().commit();

on properties file

hibernate.dialect=org.hibernate.dialect.MySQLDialect

hibernate.show_sql=true

hibernate.query_factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory

hibernate.current_session_context_class=thread

on cofiguration file

<properties>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>         
<prop key="hibernate.query.factory_class">${hibernate.query_factory_class}</prop>       
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
</props>
</property>
</properties>

Thanks,
Ashok

Use a JSON array with objects with javascript

@Swapnil Godambe It works for me if JSON.stringfy is removed. That is:

$(jQuery.parseJSON(dataArray)).each(function() {  
    var ID = this.id;
    var TITLE = this.Title;
});

How do I disable orientation change on Android?

As said, set android:configChanges of your Activity (in manifest file) to keyboardHidden|orientation and then:

1) Override onConfigurationChanged()

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    //here you can handle orientation change
}

2) Add this line to your activity's onCreate()

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

It's better than add same line to onConfigurationChanged, because your app will turn to portrait mode and then back to landscape (it will happen only one time, but it's annoying).

Also you can set android:screenOrientation="nosensor" for your activity (in manifest). But using this way you're a not able to handle orientation changes at all.

How to find the Number of CPU Cores via .NET/C#?

There are many answers here already, but some have heavy upvotes and are incorrect.

The .NET Environment.ProcessorCount WILL return incorrect values and can fail critically if your system WMI is configured incorrectly.

If you want a RELIABLE way to count the cores, the only way is Win32 API.

Here is a C++ snippet:

#include <Windows.h>
#include <vector>

int num_physical_cores()
{
    static int num_cores = []
    {
        DWORD bytes = 0;
        GetLogicalProcessorInformation(nullptr, &bytes);
        std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> coreInfo(bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION));
        GetLogicalProcessorInformation(coreInfo.data(), &bytes);

        int cores = 0;
        for (auto& info : coreInfo)
        {
            if (info.Relationship == RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }();
    return num_cores;
}

And since this is a .NET C# Question, here's the ported version:

[StructLayout(LayoutKind.Sequential)]
struct CACHE_DESCRIPTOR
{
    public byte Level;
    public byte Associativity;
    public ushort LineSize;
    public uint Size;
    public uint Type;
}

[StructLayout(LayoutKind.Explicit)]
struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION
{
    [FieldOffset(0)] public byte ProcessorCore;
    [FieldOffset(0)] public uint NumaNode;
    [FieldOffset(0)] public CACHE_DESCRIPTOR Cache;
    [FieldOffset(0)] private UInt64 Reserved1;
    [FieldOffset(8)] private UInt64 Reserved2;
}

public enum LOGICAL_PROCESSOR_RELATIONSHIP
{
    RelationProcessorCore,
    RelationNumaNode,
    RelationCache,
    RelationProcessorPackage,
    RelationGroup,
    RelationAll = 0xffff
}

struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION
{
    public UIntPtr ProcessorMask;
    public LOGICAL_PROCESSOR_RELATIONSHIP Relationship;
    public SYSTEM_LOGICAL_PROCESSOR_INFORMATION_UNION ProcessorInformation;
}

[DllImport("kernel32.dll")]
static extern unsafe bool GetLogicalProcessorInformation(SYSTEM_LOGICAL_PROCESSOR_INFORMATION* buffer, out int bufferSize);

static unsafe int GetProcessorCoreCount()
{
    GetLogicalProcessorInformation(null, out int bufferSize);
    int numEntries = bufferSize / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
    var coreInfo = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[numEntries];

    fixed (SYSTEM_LOGICAL_PROCESSOR_INFORMATION* pCoreInfo = coreInfo)
    {
        GetLogicalProcessorInformation(pCoreInfo, out bufferSize);
        int cores = 0;
        for (int i = 0; i < numEntries; ++i)
        {
            ref SYSTEM_LOGICAL_PROCESSOR_INFORMATION info = ref pCoreInfo[i];
            if (info.Relationship == LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore)
                ++cores;
        }
        return cores > 0 ? cores : 1;
    }
}

public static readonly int NumPhysicalCores = GetProcessorCoreCount();

How to create an alert message in jsp page after submit process is complete

in your servlet

 request.setAttribute("submitDone","done");
 return mapping.findForward("success");

In your jsp

<c:if test="${not empty submitDone}">
  <script>alert("Form submitted");
</script></c:if>

Combining paste() and expression() functions in plot labels

Very nice example using paste and substitute to typeset both symbols (mathplot) and variables at http://vis.supstat.com/2013/04/mathematical-annotation-in-r/

Here is a ggplot adaptation

library(ggplot2)
x_mean <- 1.5
x_sd <- 1.2
N <- 500

n <- ggplot(data.frame(x <- rnorm(N, x_mean, x_sd)),aes(x=x)) +
    geom_bar() + stat_bin() +
    labs(title=substitute(paste(
             "Histogram of random data with ",
             mu,"=",m,", ",
             sigma^2,"=",s2,", ",
             "draws = ", numdraws,", ",
             bar(x),"=",xbar,", ",
             s^2,"=",sde),
             list(m=x_mean,xbar=mean(x),s2=x_sd^2,sde=var(x),numdraws=N)))

print(n)

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

Convenient C++ struct initialisation

You could use a lambda:

const FooBar fb = [&] {
    FooBar fb;
    fb.foo = 12;
    fb.bar = 3.4;
    return fb;
}();

More information on this idiom can be found on Herb Sutter's blog.

How to add number of days in postgresql datetime

For me I had to put the whole interval in single quotes not just the value of the interval.

select id,  
   title,
   created_at + interval '1 day' * claim_window as deadline from projects   

Instead of

select id,  
   title,
   created_at + interval '1' day * claim_window as deadline from projects   

Postgres Date/Time Functions

Driver executable must be set by the webdriver.ie.driver system property

You will need have to download InternetExplorer driver executable on your system, download it from the source (http://code.google.com/p/selenium/downloads/list) after download unzip it and put on the place of somewhere in your computer. In my example, I will place it to D:\iexploredriver.exe

Then you have write below code in your eclipse main class

   System.setProperty("webdriver.ie.driver", "D:/iexploredriver.exe");
   WebDriver driver = new InternetExplorerDriver();

Javascript : array.length returns undefined

Objects don't have a .length property.

A simple solution if you know you don't have to worry about hasOwnProperty checks, would be to do this:

Object.keys(data).length;

If you have to support IE 8 or lower, you'll have to use a loop, instead:

var length= 0;
for(var key in data) {
    if(data.hasOwnProperty(key)){
        length++;
    }
}

How to make rounded percentages add up to 100%

DO NOT sum the rounded numbers. You're going to have inaccurate results. The total could be off significantly depending on the number of terms and the distribution of fractional parts.

Display the rounded numbers but sum the actual values. Depending on how you're presenting the numbers, the actual way to do that would vary. That way you get

 14
 48
 10
 29
 __
100

Any way you go you're going to have discrepancy. There's no way in your example to show numbers that add up to 100 without "rounding" one value the wrong way (least error would be changing 9.596 to 9)

EDIT

You need to choose between one of the following:

  1. Accuracy of the items
  2. Accuracy of the sum (if you're summing rounded values)
  3. Consistency between the rounded items and the rounded sum)

Most of the time when dealing with percentages #3 is the best option because it's more obvious when the total equals 101% than when the individual items don't total to 100, and you keep the individual items accurate. "Rounding" 9.596 to 9 is inaccurate in my opinion.

To explain this I sometimes add a footnote that explains that the individual values are rounded and may not total 100% - anyone that understands rounding should be able to understand that explanation.

Error: Selection does not contain a main type

I had this happen repeatedly after adding images to a project in Eclipse and making them part of the build path. The solution was to right-click on the class containing the main method, and then choose Run As -> Java Application. It seems that when you add a file to the build path, Eclipse automatically assumes that file is where the main method is. By going through the Run As menu instead of just clicking the green Run As button, it allows you to specify the correct entry-point.

How to Scroll Down - JQuery

This can be used in to solve this problem

<div id='scrol'></div> 

in javascript use this

jQuery("div#scrol").scrollTop(jQuery("div#scrol")[0].scrollHeight);

Java: Clear the console

This will work if you are doing this in Bluej or any other similar software.

System.out.print('\u000C');

Get battery level and state in Android

try this function no need permisson or any reciver

void getBattery_percentage()
{
      IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
      Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter);
      int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
      int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
      float batteryPct = level / (float)scale;
      float p = batteryPct * 100;

      Log.d("Battery percentage",String.valueOf(Math.round(p)));
  }

How do I find out what keystore my JVM is using?

This works for me:

#! /bin/bash

CACERTS=$(readlink -e $(dirname $(readlink -e $(which keytool)))/../lib/security/cacerts)

if keytool -list -keystore $CACERTS -storepass changeit > /dev/null ; then
    echo $CACERTS
else
    echo 'Can not find cacerts file.' >&2
    exit 1
fi

Only for Linux. My Solaris has no readlink. In the end I used this Perl-Script:

#! /usr/bin/env perl
use strict;
use warnings;
use Cwd qw(realpath);
$_ = realpath((grep {-x && -f} map {"$_/keytool"} split(':', $ENV{PATH}))[0]);
die "Can not find keytool" unless defined $_;
my $keytool = $_;
print "Using '$keytool'.\n";
s/keytool$//;
$_ = realpath($_ . '../lib/security/cacerts');
die "Can not find cacerts" unless -f $_;
my $cacerts = $_;
print "Importing into '$cacerts'.\n";
`$keytool -list -keystore "$cacerts" -storepass changeit`;
die "Can not read key container" unless $? == 0;
exit if $ARGV[0] eq '-d';
foreach (@ARGV) {
    my $cert = $_;
    s/\.[^.]+$//;
    my $alias = $_;
    print "Importing '$cert' as '$alias'.\n";
    `keytool -importcert -file "$cert" -alias "$alias" -keystore "$cacerts" -storepass changeit`;
    warn "Can not import certificate: $?" unless $? == 0;
}

Why are unnamed namespaces used and what are their benefits?

Having something in an anonymous namespace means it's local to this translation unit (.cpp file and all its includes) this means that if another symbol with the same name is defined elsewhere there will not be a violation of the One Definition Rule (ODR).

This is the same as the C way of having a static global variable or static function but it can be used for class definitions as well (and should be used rather than static in C++).

All anonymous namespaces in the same file are treated as the same namespace and all anonymous namespaces in different files are distinct. An anonymous namespace is the equivalent of:

namespace __unique_compiler_generated_identifer0x42 {
    ...
}
using namespace __unique_compiler_generated_identifer0x42;

Signed to unsigned conversion in C - is it always safe?

Conversion from signed to unsigned does not necessarily just copy or reinterpret the representation of the signed value. Quoting the C standard (C99 6.3.1.3):

When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

For the two's complement representation that's nearly universal these days, the rules do correspond to reinterpreting the bits. But for other representations (sign-and-magnitude or ones' complement), the C implementation must still arrange for the same result, which means that the conversion can't just copy the bits. For example, (unsigned)-1 == UINT_MAX, regardless of the representation.

In general, conversions in C are defined to operate on values, not on representations.

To answer the original question:

unsigned int u = 1234;
int i = -5678;

unsigned int result = u + i;

The value of i is converted to unsigned int, yielding UINT_MAX + 1 - 5678. This value is then added to the unsigned value 1234, yielding UINT_MAX + 1 - 4444.

(Unlike unsigned overflow, signed overflow invokes undefined behavior. Wraparound is common, but is not guaranteed by the C standard -- and compiler optimizations can wreak havoc on code that makes unwarranted assumptions.)

How to get the top position of an element?

Try: $('#mytable').attr('offsetTop')

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

The selected answer is clever and tricky. Here's how I did it:

LoginActivity is the root activity of the task, set android:noHistory="true" to it in Manifest.xml; Say you want to logout from SettingsActivity, you can do it as below:

    Intent i = new Intent(SettingsActivity.this, LoginActivity.class);
    i.addFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
            | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);

Android layout replacing a view with another view on run time

private void replaceView(View oldV,View newV){
        ViewGroup par = (ViewGroup)oldV.getParent();
        if(par == null){return;}
        int i1 = par.indexOfChild(oldV);
        par.removeViewAt(i1);
        par.addView(newV,i1);
    }

How do you strip a character out of a column in SQL Server?

This is done using the REPLACE function

To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:

SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn]  FROM [SomeTable]

To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"

UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')

How to split() a delimited string to a List<String>

string.Split() returns an array - you can convert it to a list using ToList():

listStrLineElements = line.Split(',').ToList();

Note that you need to import System.Linq to access the .ToList() function.

Java: Casting Object to Array type

Your values object is obviously an Object[] containing a String[] containing the values.

String[] stringValues = (String[])values[0];

Getting multiple keys of specified value of a generic Dictionary?

revised: okay to have some kind of find you would need something other than dictionary, since if you think about it dictionary are one way keys. that is, the values might not be unique

that said it looks like you're using c#3.0 so you might not have to resort to looping and could use something like:

var key = (from k in yourDictionary where string.Compare(k.Value, "yourValue", true)  == 0 select k.Key).FirstOrDefault();

Is it possible to decrypt SHA1

SHA1 is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.

However, breaking a SHA1 hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.

So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.

As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod eliminate information from your input. Suppose you calculate mod 5 and you get 0. What was the input? Was it 0, 5 or 500? You see, you can't really 'go back' in this case.

LINQ query on a DataTable

Using LINQ to manipulate data in DataSet/DataTable

var results = from myRow in tblCurrentStock.AsEnumerable()
              where myRow.Field<string>("item_name").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())
              select myRow;
DataView view = results.AsDataView();

getting the X/Y coordinates of a mouse click on an image with jQuery

The below code works always even if any image makes the window scroll.

$(function() {
    $("#demo-box").click(function(e) {

      var offset = $(this).offset();
      var relativeX = (e.pageX - offset.left);
      var relativeY = (e.pageY - offset.top);

      alert("X: " + relativeX + "  Y: " + relativeY);

    });
});

Ref: http://css-tricks.com/snippets/jquery/get-x-y-mouse-coordinates/

How to center a Window in Java?

Example: Inside myWindow() on line 3 is the code you need to set the window in the center of the screen.

JFrame window;

public myWindow() {

    window = new JFrame();
    window.setSize(1200,800);
    window.setLocationRelativeTo(null); // this line set the window in the center of thr screen
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setBackground(Color.BLACK);
    window.setLayout(null); // disable the default layout to use custom one.
    window.setVisible(true); // to show the window on the screen.
}

React: "this" is undefined inside a component function

I ran into a similar bind in a render function and ended up passing the context of this in the following way:

{someList.map(function(listItem) {
  // your code
}, this)}

I've also used:

{someList.map((listItem, index) =>
    <div onClick={this.someFunction.bind(this, listItem)} />
)}

HTML - how can I show tooltip ONLY when ellipsis is activated

This was my solution, works as a charm!

    $(document).on('mouseover', 'input, span', function() {
      var needEllipsis = $(this).css('text-overflow') && (this.offsetWidth < this.scrollWidth);
      var hasNotTitleAttr = typeof $(this).attr('title') === 'undefined';
      if (needEllipsis === true) {
          if(hasNotTitleAttr === true){
            $(this).attr('title', $(this).val());
          }
      }
      if(needEllipsis === false && hasNotTitleAttr == false){
        $(this).removeAttr('title');
      }
  });

Why is my element value not getting changed? Am I using the wrong function?

Sounds like we need to assume that your textbox name and ID are both set to "Tue." If that's the case, try using a lower-case V on .value.

jquery (or pure js) simulate enter key pressed for testing

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

File uploading with Express 4.0: req.files undefined

The body-parser module only handles JSON and urlencoded form submissions, not multipart (which would be the case if you're uploading files).

For multipart, you'd need to use something like connect-busboy or multer or connect-multiparty (multiparty/formidable is what was originally used in the express bodyParser middleware). Also FWIW, I'm working on an even higher level layer on top of busboy called reformed. It comes with an Express middleware and can also be used separately.

Using colors with printf

You're mixing the parts together instead of separating them cleanly.

printf '\e[1;34m%-6s\e[m' "This is text"

Basically, put the fixed stuff in the format and the variable stuff in the parameters.

How do I retrieve the number of columns in a Pandas data frame?

df.info() function will give you result something like as below. If you are using read_csv method of Pandas without sep parameter or sep with ",".

raw_data = pd.read_csv("a1:\aa2/aaa3/data.csv")
raw_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5144 entries, 0 to 5143
Columns: 145 entries, R_fighter to R_age

My Routes are Returning a 404, How can I Fix Them?

Have you tried to check if

http://localhost/mysite/public/index.php/user 

was working? If so then make sure all your path's folders don't have any uppercase letters. I had the same situation and converting letters to lower case helped.

How to remove error about glyphicons-halflings-regular.woff2 not found

This problem happens because IIS does not find the actual location of woff2 file mime types. Set URL of font-face properly, also keep font-family as glyphicons-halflings-regular in your CSS file as shown below.

@font-face {
font-family: 'glyphicons-halflings-regular'; 
src: url('../../../fonts/glyphicons-halflings-regular.woff2') format('woff2');}

SQL Server: Invalid Column Name

Following procedure helped me solve this issue but i don't know why.

  1. Cut the code in question given by the lines in the message
  2. Save the query (e.g. to file)
  3. Paste the code to where it was before
  4. Again save the query

Even if it seems to be the same query executing it did not throw this error

Difference between Big-O and Little-O Notation

The big-O notation has a companion called small-o notation. The big-O notation says the one function is asymptotical no more than another. To say that one function is asymptotically less than another, we use small-o notation. The difference between the big-O and small-o notations is analogous to the difference between <= (less than equal) and < (less than).

How to remove the underline for anchors(links)?

When you want to use an anchor tag simply as a link without the added styling (such as the underline on hover or blue color) add class="no-style" to the anchor tag. Then in your global stylesheet create the class "no-style".

.no-style {
    text-decoration: none !important;
}

This has two advantages.

  1. It will not affect all anchor tags, just the ones with the "no-style" class added to them.
  2. It will override any other styling that may otherwise prevent setting text-decoration to none.

Installing SciPy and NumPy using pip

Since the previous instructions for installing with yum are broken here are the updated instructions for installing on something like fedora. I've tested this on "Amazon Linux AMI 2016.03"

sudo yum install atlas-devel lapack-devel blas-devel libgfortran
pip install scipy

json_encode(): Invalid UTF-8 sequence in argument

The symbol you posted is the placeholder symbol for a broken byte sequence. Basically, it's not a real symbol but an error in your string.

What is the exact byte value of the symbol? Blindly applying utf8_encode is not a good idea, it's better to find out first where the byte(s) came from and what they mean.

Ajax Upload image

You can use jquery.form.js plugin to upload image via ajax to the server.

http://malsup.com/jquery/form/

Here is the sample jQuery ajax image upload script

(function() {
$('form').ajaxForm({
    beforeSubmit: function() {  
        //do validation here


    },

    beforeSend:function(){
       $('#loader').show();
       $('#image_upload').hide();
    },
    success: function(msg) {

        ///on success do some here
    }
}); })();  

If you have any doubt, please refer following ajax image upload tutorial here

http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/

Importing packages in Java

Here is the right way to do imports in Java.

import Dan.Vik;
class Kab
{
public static void main(String args[])
{
    Vik Sam = new Vik();
    Sam.disp();
}
}

You don't import methods in java. There is an advanced usage of static imports but basically you just import packages and classes. If the function you are importing is a static function you can do a static import, but I don't think you are looking for static imports here.

What's the syntax for mod in java

if (a % 2 == 0) {
} else {
}

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Select      Eventname, 
            count(Eventname) as 'Counts'
INTO        #TEMPTABLE                                                                                
FROM        tblevent
where       Eventname like 'A%'
Group by    Eventname
order by    count(Eventname)

Here by using the into clause the table is directly created

Using sendmail from bash script for multiple recipients

to use sendmail from the shell script

subject="mail subject"
body="Hello World"
from="[email protected]"
to="[email protected],[email protected]"
echo -e "Subject:${subject}\n${body}" | sendmail -f "${from}" -t "${to}"

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

Using reshape2 and dplyr. Your data:

df <- read.table(text=
"tea                coke            beer             water           gender
14.55              26.50793651     22.53968254      40              1
24.92997199        24.50980392     26.05042017      24.50980393     2
23.03732304        30.63063063     25.41827542      20.91377091     1   
225.51781276       24.6064623      24.85501243      50.80645161     1
24.53662842        26.03706973     25.24271845      24.18358341     2", header=TRUE)

Getting data into correct form:

library(reshape2)
library(dplyr)
df.melt <- melt(df, id="gender")
bar <- group_by(df.melt, variable, gender)%.%summarise(mean=mean(value))

Plotting:

library(ggplot2)
ggplot(bar, aes(x=variable, y=mean, fill=factor(gender)))+
  geom_bar(position="dodge", stat="identity")

enter image description here

How to loop through an array of objects in swift

You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:

class ModelAttachment {
    var id: String?
    var url: String?
    var thumb: String?
}

var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"

var imgs: Array<ModelAttachment> = [modelAttachementObj]

for img in imgs  {
    let url = img.url
    NSLog(url!)
}

See docs here

Laravel 5 How to switch from Production mode

Do not forget to run the command php artisan config:clear after you have made the changes to the .env file. Done this again php artisan env, which will return the correct version.

How to get a random number between a float range?

Most commonly, you'd use:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

Python provides other distributions if you need.

If you have numpy imported already, you can used its equivalent:

import numpy as np
np.random.uniform(a, b) # range [a, b)

Again, if you need another distribution, numpy provides the same distributions as python, as well as many additional ones.

Convert a list to a dictionary in Python

Simple answer

Another option (courtesy of Alex Martelli - source):

dict(x[i:i+2] for i in range(0, len(x), 2))

Related note

If you have this:

a = ['bi','double','duo','two']

and you want this (each element of the list keying a given value (2 in this case)):

{'bi':2,'double':2,'duo':2,'two':2}

you can use:

>>> dict((k,2) for k in a)
{'double': 2, 'bi': 2, 'two': 2, 'duo': 2}

Create a new database with MySQL Workbench

In MySQL Work bench 6.0 CE.

  1. You launch MySQL Workbench.
  2. From Menu Bar click on Database and then select "Connect to Database"
  3. It by default showing you default settings other wise you choose you host name, user name and password. and click to ok.
  4. As in above define that you should click write on existing database but if you don't have existing new database then you may choose the option from the icon menu that is provided on below the menu bar. Now keep the name as you want and enjoy ....

How do you manually execute SQL commands in Ruby On Rails using NuoDB

The working command I'm using to execute custom SQL statements is:

results = ActiveRecord::Base.connection.execute("foo")

with "foo" being the sql statement( i.e. "SELECT * FROM table").

This command will return a set of values as a hash and put them into the results variable.

So on my rails application_controller.rb I added this:

def execute_statement(sql)
  results = ActiveRecord::Base.connection.execute(sql)

  if results.present?
    return results
  else
    return nil
  end
end

Using execute_statement will return the records found and if there is none, it will return nil.

This way I can just call it anywhere on the rails application like for example:

records = execute_statement("select * from table")

"execute_statement" can also call NuoDB procedures, functions, and also Database Views.

Read entire file in Scala?

(EDIT: This does not work in scala 2.9 and maybe not 2.8 either)

Use trunk:

scala> io.File("/etc/passwd").slurp
res0: String = 
##
# User Database
# 
... etc

What to gitignore from the .idea folder?

While maintaining the proper .gitignore file is helpful, I found this alternate approach is way cleaner and easier to use.

  • Create dummy folder my_project and inside that git clone my_real_project the actual project repo.
  • Now while opening the project in IDE (Intellij/Pycharm) open the folder my_project and mark my_project/my_real_project as the VCS root.
  • You can see my_project/.idea wouldn't pollute your git repo because it happily lives outside the git repo which is what you want. This way your .gitignore files stays clean as well.

This approach works better due to the below reasons.

1 - .gitignore file stays clean and we don't have to insert lines related to JetBrains products, that file is better used for binaries and libraries and autogen contents.

2 - Intellij keeps updating their projects and the files inside .idea keep changing every significant release from JB. What this means is we have to keep updating our .gitignore accordingly which is not an ideal use of time.

3 - Intellij has the flawed pattern here, most editors Atom, VS Code, Eclipse... nobody stores their IDE contents right inside project root. JB shouldn't be an exception either. It's the onus of Jetbrains to keep those files tracked outside project root. They have to refrain from polluting VCS root. This approach does just that. The .idea folder is kept outside the PROJECT_ROOT

Hope this helps.

What is the difference between connection and read timeout for sockets?

These are timeout values enforced by JVM for TCP connection establishment and waiting on reading data from socket.

If the value is set to infinity, you will not wait forever. It simply means JVM doesn't have timeout and OS will be responsible for all the timeouts. However, the timeouts on OS may be really long. On some slow network, I've seen timeouts as long as 6 minutes.

Even if you set the timeout value for socket, it may not work if the timeout happens in the native code. We can reproduce the problem on Linux by connecting to a host blocked by firewall or unplugging the cable on switch.

The only safe approach to handle TCP timeout is to run the connection code in a different thread and interrupt the thread when it takes too long.

Run Command Prompt Commands

if you want to keep the cmd window open or want to use it in winform/wpf then use it like this

    string strCmdText;
//For Testing
    strCmdText= "/K ipconfig";

 System.Diagnostics.Process.Start("CMD.exe",strCmdText);

/K

Will keep the cmd window open

How do I declare a two dimensional array?

Just declare? You don't have to. Just make sure variable exists:

$d = array();

Arrays are resized dynamically, and attempt to write anything to non-exsistant element creates it (and creates entire array if needed)

$d[1][2] = 3;

This is valid for any number of dimensions without prior declarations.

How to get JavaScript variable value in PHP

You need to add this value to the form data that is submitted to the server. You can use

<input type="hidden" value="1" name="profile_viewer_uid" id="profile_viewer_uid">

inside your form tag.

Creating columns in listView and add items

You need to set property for the control:

listView1.View = View.Details;

How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script>

'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
        resolve("result");
    }, 1000);
});

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);
});

</script>

How to check not in array element

Try with array_intersect method

$id = $access_data['Privilege']['id']; 

if(count(array_intersect($id,$user_access_arr)) == 0){

$this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));
}

Looping through a DataTable

     foreach (DataRow row in dt.Rows) 
     {
        foreach (DataColumn col in dt.Columns)
           Console.WriteLine(row[col]);
     }

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

This is due to a PHP 5.3.0 bug on Windows where MYSQL_ATTR_INIT_COMMAND is not available. The PHP bug report is:

http://bugs.php.net/bug.php?id=47224

If you are experiencing this, please update your WAMP product to a version that uses PHP 5.3.1 or later version.

Search for value in DataGridView in a column

//     This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
    string searchValue=textBoxSearch.Text;
    int rowIndex = 1;  //this one is depending on the position of cell or column
    //string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;

    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        bool valueResulet = true;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;
                dataGridView1.Rows[rowIndex].Selected = true;
                rowIndex++;
                valueResulet = false;
            }
        }
        if (valueResulet != false)
        {
            MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
            return;
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

POST data with request module on Node.JS

  1. Install request module, using npm install request

  2. In code:

    var request = require('request');
    var data = '{ "request" : "msg", "data:" {"key1":' + Var1 + ', "key2":' + Var2 + '}}';
    var json_obj = JSON.parse(data);
    request.post({
        headers: {'content-type': 'application/json'},
        url: 'http://localhost/PhpPage.php',
        form: json_obj
    }, function(error, response, body){
      console.log(body)
    });
    

How do I test if a recordSet is empty? isNull?

A simple way is to write it:

Dim rs As Object
Set rs = Me.Recordset.Clone
If Me.Recordset.RecordCount = 0 then 'checks for number of records
   msgbox "There is no records" 
End if

Select rows having 2 columns equal value

Question 1 query:

SELECT ta.C1
      ,ta.C2
      ,ta.C3
      ,ta.C4
FROM [TableA] ta
WHERE (SELECT COUNT(*)
       FROM [TableA] ta2
       WHERE ta.C2=ta2.C2
       AND ta.C3=ta2.C3
       AND ta.C4=ta2.C4)>1

[Ljava.lang.Object; cannot be cast to

In case entire entity is being return, better solution in spring JPA is use @Query(value = "from entity where Id in :ids")

This return entity type rather than object type

How to change a particular element of a C++ STL vector

I prefer

l.at(4)= -1;

while [4] is your index

Android - How to decode and decompile any APK file?

You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

WordPress overrides PHP's memory limit to 256M, with the assumption that whatever it was set to before is going to be too low to render the dashboard. You can override this by defining WP_MAX_MEMORY_LIMIT in wp-config.php:

define( 'WP_MAX_MEMORY_LIMIT' , '512M' );

I agree with DanFromGermany, 256M is really a lot of memory for rendering a dashboard page. Changing the memory limit is really putting a bandage on the problem.

Get values from an object in JavaScript

If you $ is defined then You can iterate

var data={"id" : 1, "second" : "abcd"};
$.each(data, function() {
  var key = Object.keys(this)[0];
  var value = this[key];
  //do something with value;
}); 

You can access it by following way If you know the values of keys

data.id

or

data["id"]

How to build PDF file from binary string returned from a web-service using javascript

Detect the browser and use Data-URI for Chrome and use PDF.js as below for other browsers.

PDFJS.getDocument(url_of_pdf)
.then(function(pdf) {
    return pdf.getPage(1);
})
.then(function(page) {
    // get a viewport
    var scale = 1.5;
    var viewport = page.getViewport(scale);
    // get or create a canvas
    var canvas = ...;
    canvas.width = viewport.width;
    canvas.height = viewport.height;

    // render a page
    page.render({
        canvasContext: canvas.getContext('2d'),
        viewport: viewport
    });
})
.catch(function(err) {
    // deal with errors here!
});

regex for zip-code

^\d{5}(?:[-\s]\d{4})?$
  • ^ = Start of the string.
  • \d{5} = Match 5 digits (for condition 1, 2, 3)
  • (?:…) = Grouping
  • [-\s] = Match a space (for condition 3) or a hyphen (for condition 2)
  • \d{4} = Match 4 digits (for condition 2, 3)
  • …? = The pattern before it is optional (for condition 1)
  • $ = End of the string.

How do I horizontally center an absolute positioned element inside a 100% width div?

Was missing the use of calc in the answers, which is a cleaner solution.

#logo {
  position: absolute;
  left: calc(50% - 25px);
  height: 50px;
  width: 50px;
  background: red;
}

jsFiddle

Works in most modern browsers: http://caniuse.com/calc

Maybe it's too soon to use it without a fallback, but I thought maybe for future visitors it would be helpful.

Show empty string when date field is 1/1/1900

If you CAST your data as a VARCHAR() instead of explicitly CONVERTing your data you can simply

SELECT REPLACE(CAST(CreatedDate AS VARCHAR(20)),'Jan  1 1900 12:00AM','')

The CAST will automatically return your Date then as Jun 18 2020 12:46PM fix length strings formats which you can additionally SUBSTRING()

SELECT SUBSTRING(REPLACE(CAST(CreatedDate  AS VARCHAR(20)),'Jan  1 1900 12:00AM',''),1,11)

Output

Jun 18 2020

For a boolean field, what is the naming convention for its getter/setter?

http://geosoft.no/development/javastyle.html#Specific

  1. is prefix should be used for boolean variables and methods.

    isSet, isVisible, isFinished, isFound, isOpen

This is the naming convention for boolean methods and variables used by Sun for the Java core packages. Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.

Setter methods for boolean variables must have set prefix as in:

void setFound(boolean isFound);

There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:

boolean hasLicense(); 
boolean canEvaluate(); 
boolean shouldAbort = false;

Center text in div?

div {
    height: 256px;
    width: 256px;
    display: table-cell;
    text-align: center;
    line-height: 256px;
}

The trick is to set the line-height equal to the height of the div.

Oracle Sql get only month and year in date datatype

SELECT to_char(to_date(month,'yyyy-mm'),'Mon yyyy'), nos
FROM (SELECT to_char(credit_date,'yyyy-mm') MONTH,count(*) nos
      FROM HCN
      WHERE   TRUNC(CREDIT_dATE) BEtween '01-jul-2014' AND '30-JUN-2015'
      AND CATEGORYCODECFR=22
      --AND CREDIT_NOTE_NO IS NOT  NULL
      AND CANCELDATE IS NULL
GROUP BY to_char(credit_date,'yyyy-mm')
ORDER BY to_char(credit_date,'yyyy-mm') ) mm

Output:

Jul 2014        49
Aug 2014        35
Sep 2014        57
Oct 2014        50
Nov 2014        45
Dec 2014        88
Jan 2015       131
Feb 2015       112
Mar 2015        76
Apr 2015        45
May 2015        49
Jun 2015        40