Programs & Examples On #Conflict

DO NOT USE THIS TAG. Instead try to use something more specific like name-collision, failed-installation, merge-conflict-resolution, conflicting-libraries etc (see also the meta discussion: http://meta.stackoverflow.com/questions/284369/end-the-conflict)

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

Just an addition to the answer of @phantomlimb,

while View.generateViewId() require API Level >= 17,
this tool is compatibe with all API.

according to current API Level,
it decide weather using system API or not.

so you can use ViewIdGenerator.generateViewId() and View.generateViewId() in the same time and don't worry about getting same id

import java.util.concurrent.atomic.AtomicInteger;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;

/**
 * {@link View#generateViewId()}??API Level >= 17,??????????API Level
 * <p>
 * ??????API Level,?????{@link View#generateViewId()},???????{@link View#generateViewId()}
 * ??,???????Id??
 * <p>
 * =============
 * <p>
 * while {@link View#generateViewId()} require API Level >= 17, this tool is compatibe with all API.
 * <p>
 * according to current API Level, it decide weather using system API or not.<br>
 * so you can use {@link ViewIdGenerator#generateViewId()} and {@link View#generateViewId()} in the
 * same time and don't worry about getting same id
 * 
 * @author [email protected]
 */
public class ViewIdGenerator {
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    @SuppressLint("NewApi")
    public static int generateViewId() {

        if (Build.VERSION.SDK_INT < 17) {
            for (;;) {
                final int result = sNextGeneratedId.get();
                // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
                int newValue = result + 1;
                if (newValue > 0x00FFFFFF)
                    newValue = 1; // Roll over to 1, not 0.
                if (sNextGeneratedId.compareAndSet(result, newValue)) {
                    return result;
                }
            }
        } else {
            return View.generateViewId();
        }

    }
}

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

Situation:

  • You have local uncommitted changes
  • You pull from the master repo
  • You get the error "Checkout conflict with files: xy"

Solution:

  • Stage and commit (at least) the files xy
  • Pull again
  • If automerge is possible, everything is ok.
  • If not, the pull merges the files and inserts the merge-conflict markers (<<<<<<, >>>>)
    • Manually edit the conflicting files
  • Commit and push

How can I discard remote changes and mark a file as "resolved"?

Make sure of the conflict origin: if it is the result of a git merge, see Brian Campbell's answer.

But if is the result of a git rebase, in order to discard remote (their) changes and use local changes, you would have to do a:

git checkout --theirs -- .

See "Why is the meaning of “ours” and “theirs” reversed"" to see how ours and theirs are swapped during a rebase (because the upstream branch is checked out).

Git resolve conflict using --ours/--theirs for all files

In case anyone else is looking to simply overwrite everything from one branch (say master) with the contents of another, there's an easier way:

git merge origin/master --strategy=ours

Thanks to https://stackoverflow.com/a/1295232/560114

Or for the other way around, see Is there a "theirs" version of "git merge -s ours"?

How do I implement JQuery.noConflict() ?

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

How do I manage conflicts with git submodules?

I had this problem with git rebase -i origin/master to a branch. I wanted to take master's version of the submodule ref, so I simply did:

git reset master path/to/submodule

and then

git rebase --continue

That solved the problem for me.

Alter column, add default constraint

I confirm like the comment from JohnH, never use column types in the your object names! It's confusing. And use brackets if possible.

Try this:

ALTER TABLE [TableName]
ADD  DEFAULT (getutcdate()) FOR [Date]; 

What is the equivalent of the C++ Pair<L,R> in Java?

If anyone wants a dead-simple and easy to use version I made my available at https://github.com/lfac-pt/Java-Pair. Also, improvements are very much welcome!

how to call an ASP.NET c# method using javascript

There are several options. You can use the WebMethod attribute, for your purpose.

no operator "<<" matches these operands

You're not including the standard <string> header.

You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<< was not.

What is the difference between 'git pull' and 'git fetch'?

Trying to be clear and simple.

The git pull command is actually a shortcut for git fetch followed by the git merge or the git rebase command depending on your configuration. You can configure your Git repository so that git pull is a fetch followed by a rebase.

Is it possible to install both 32bit and 64bit Java on Windows 7?

You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.

For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".

The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button

There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.

If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.

Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.

How to get the version of ionic framework?

In the terminal following command returns the version:

'ionic version' or 'ionic -v'

returned

'3.2.0'

The above is the CLI version. Go to the project folder and use the code below like scw's answer.

$ cd ionic-project
$ ionic info
? Gathering environment info - done!

Ionic:

   ionic (Ionic CLI)  : 4.2.1 (/usr/local/lib/node_modules/ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.2.0

Cordova:

   cordova (Cordova CLI) : 8.1.2 ([email protected])
   Cordova Platforms     : android 7.1.4
   Cordova Plugins       : cordova-plugin-ionic 5.2.7, cordova-plugin-ionic-webview 2.2.5, (and 15 other plugins)

System:

   NodeJS : v8.12.0 (/usr/local/bin/node)
   npm    : 6.4.1
   OS     : OS X Yosemite

Xcode - Warning: Implicit declaration of function is invalid in C99

The compiler wants to know the function before it can use it

just declare the function before you call it

#include <stdio.h>

int Fibonacci(int number); //now the compiler knows, what the signature looks like. this is all it needs for now

int main(int argc, const char * argv[])
{
    int input;
    printf("Please give me a number : ");
    scanf("%d", &input);
    getchar();
    printf("The fibonacci number of %d is : %d", input, Fibonacci(input)); //!!!

}/* main */

int Fibonacci(int number)
{
//…

How to specify the private SSH-key to use when executing shell command on Git?

If SSH port number is not 22(default), add Port xx in ~/.ssh/config

In my case (synology),

Host my_synology
    Hostname xxxx.synology.me
    IdentityFile ~/.ssh/id_rsa_xxxx
    User myname
    Port xx

Then clone using Host title in config. ("my_synology". to avoid @chopstik 's "*")

git clone my_synology:path/to/repo.git

How to get the text of the selected value of a dropdown list?

$("#select_id").find("option:selected").text();

It is helpful if your control is on Server side. In .NET it looks like:

$('#<%= dropdownID.ClientID %>').find("option:selected").text();

how to align text vertically center in android

Try to put android:gravity="center_vertical|right" inside parent LinearLayout else as you are inside RelativeLayout you can put android:layout_centerInParent="true" inside your scrollView.

How can I access Oracle from Python?

Here's what worked for me. My Python and Oracle versions are slightly different from yours, but the same approach should apply. Just make sure the cx_Oracle binary installer version matches your Oracle client and Python versions.

My versions:

  • Python 2.7
  • Oracle Instant Client 11G R2
  • cx_Oracle 5.0.4 (Unicode, Python 2.7, Oracle 11G)
  • Windows XP SP3

Steps:

  1. Download the Oracle Instant Client package. I used instantclient-basic-win32-11.2.0.1.0.zip. Unzip it to C:\your\path\to\instantclient_11_2
  2. Download and run the cx_Oracle binary installer. I used cx_Oracle-5.0.4-11g-unicode.win32-py2.7.msi. I installed it for all users and pointed it to the Python 2.7 location it found in the registry.
  3. Set the ORACLE_HOME and PATH environment variables via a batch script or whatever mechanism makes sense in your app context, so that they point to the Oracle Instant Client directory. See oracle_python.bat source below. I'm sure there must be a more elegant solution for this, but I wanted to limit my system-wide changes as much as possible. Make sure you put the targeted Oracle Instant Client directory at the beginning of the PATH (or at least ahead of any other Oracle client directories). Right now, I'm only doing command-line stuff so I just run oracle_python.bat in the shell before running any programs that require cx_Oracle.
  4. Run regedit and check to see if there's an NLS_LANG key set at \HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE. If so, rename the key (I changed it to NLS_LANG_OLD) or unset it. This key should only be used as the default NLS_LANG value for Oracle 7 client, so it's safe to remove it unless you happen to be using Oracle 7 client somewhere else. As always, be sure to backup your registry before making changes.
  5. Now, you should be able to import cx_Oracle in your Python program. See the oracle_test.py source below. Note that I had to set the connection and SQL strings to Unicode for my version of cx_Oracle.

Source: oracle_python.bat

@echo off
set ORACLE_HOME=C:\your\path\to\instantclient_11_2
set PATH=%ORACLE_HOME%;%PATH%

Source: oracle_test.py

import cx_Oracle

conn_str = u'user/password@host:port/service'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute(u'select your_col_1, your_col_2 from your_table')
for row in c:
    print row[0], "-", row[1]
conn.close()

Possible Issues:

  • "ORA-12705: Cannot access NLS data files or invalid environment specified" - I ran into this before I made the NLS_LANG registry change.
  • "TypeError: argument 1 must be unicode, not str" - if you need to set the connection string to Unicode.
  • "TypeError: expecting None or a string" - if you need to set the SQL string to Unicode.
  • "ImportError: DLL load failed: The specified procedure could not be found." - may indicate that cx_Oracle can't find the appropriate Oracle client DLL.

PowerShell The term is not recognized as cmdlet function script file or operable program

You first have to 'dot' source the script, so for you :

. .\Get-NetworkStatistics.ps1

The first 'dot' asks PowerShell to load the script file into your PowerShell environment, not to start it. You should also use set-ExecutionPolicy Unrestricted or set-ExecutionPolicy AllSigned see(the Execution Policy instructions).

Purge Kafka Topic

Temporarily update the retention time on the topic to one second:

kafka-topics.sh --zookeeper <zkhost>:2181 --alter --topic <topic name> --config retention.ms=1000

And in newer Kafka releases, you can also do it with kafka-configs --entity-type topics

kafka-configs.sh --zookeeper <zkhost>:2181 --entity-type topics --alter --entity-name <topic name> --add-config retention.ms=1000

then wait for the purge to take effect (about one minute). Once purged, restore the previous retention.ms value.

How to center the content inside a linear layout?

If you are looking for an answer in java code,

LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setGravity(Gravity.CENTER);
// add children

Why not inherit from List<T>?

Problems with serializing

One aspect is missing. Classes that inherit from List can't be serialized correctly using XmlSerializer. In that case DataContractSerializer must be used instead, or an own serializing implementation is needed.
public class DemoList : List<Demo>
{
    // using XmlSerializer this properties won't be seralized
    // There is no error, the data is simply not there.
    string AnyPropertyInDerivedFromList { get; set; }     
}

public class Demo
{
    // this properties will be seralized
    string AnyPropetyInDemo { get; set; }  
}

Further reading: When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes

Flask Value error view function did not return a response

The following does not return a response:

You must return anything like return afunction() or return 'a string'.

This can solve the issue

Restore the mysql database from .frm files

I just copy pasted the database folders to data folder in MySQL, i.e. If you have a database called alto then find the folder alto in your MySQL -> Data folder in your backup and copy the entire alto folder and past it to newly installed MySQL -> data folder, restart the MySQL and this works perfect.

Difference between clustered and nonclustered index

faster to read than non cluster as data is physically storted in index order we can create only one per table.(cluster index)

quicker for insert and update operation than a cluster index. we can create n number of non cluster index.

HTTPS setup in Amazon EC2

First, you need to open HTTPS port (443). To do that, you go to https://console.aws.amazon.com/ec2/ and click on the Security Groups link on the left, then create a new security group with also HTTPS available. Then, just update the security group of a running instance or create a new instance using that group.

After these steps, your EC2 work is finished, and it's all an application problem.

Comparing arrays in JUnit assertions, concise built-in way?

Use org.junit.Assert's method assertArrayEquals:

import org.junit.Assert;
...

Assert.assertArrayEquals( expectedResult, result );

If this method is not available, you may have accidentally imported the Assert class from junit.framework.

Python read-only property

Notice that instance methods are also attributes (of the class) and that you could set them at the class or instance level if you really wanted to be a badass. Or that you may set a class variable (which is also an attribute of the class), where handy readonly properties won't work neatly out of the box. What I'm trying to say is that the "readonly attribute" problem is in fact more general than it's usually perceived to be. Fortunately there are conventional expectations at work that are so strong as to blind us wrt these other cases (after all, almost everything is an attribute of some sort in python).

Building upon these expectations I think the most general and lightweight approach is to adopt the convention that "public" (no leading underscore) attributes are readonly except when explicitly documented as writeable. This subsumes the usual expectation that methods won't be patched and class variables indicating instance defaults are better let alone. If you feel really paranoid about some special attribute, use a readonly descriptor as a last resource measure.

Session unset, or session_destroy?

Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.

It really depends on your application as to which one you should use. Just keep the above in mind.

unset($_SESSION['name']); // will delete just the name data

session_destroy(); // will delete ALL data associated with that user.

How to add a jar in External Libraries in android studio

This is how you can add .jar file in Android Studio 2.1.3.

  1. Copy the .jar file jar file copy screenshot

  2. paste the file in Libs folder and then right click on .jar file and press Add as library enter image description here

  3. open build.gradle enter image description here

  4. add lines under dependencies as shown in screenshot enter image description hereenter image description here

  5. Now press play button and you are done adding .jar file enter image description here

Android layout replacing a view with another view on run time

You could replace any view at any time.

int optionId = someExpression ? R.layout.option1 : R.layout.option2;

View C = findViewById(R.id.C);
ViewGroup parent = (ViewGroup) C.getParent();
int index = parent.indexOfChild(C);
parent.removeView(C);
C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

If you don't want to replace already existing View, but choose between option1/option2 at initialization time, then you could do this easier: set android:id for parent layout and then:

ViewGroup parent = (ViewGroup) findViewById(R.id.parent);
View C = getLayoutInflater().inflate(optionId, parent, false);
parent.addView(C, index);

You will have to set "index" to proper value depending on views structure. You could also use a ViewStub: add your C view as ViewStub and then:

ViewStub C = (ViewStub) findViewById(R.id.C);
C.setLayoutResource(optionId);
C.inflate();

That way you won't have to worry about above "index" value if you will want to restructure your XML layout.

Spring MVC Missing URI template variable

I got this error for a stupid mistake, the variable name in the @PathVariable wasn't matching the one in the @RequestMapping

For example

@RequestMapping(value = "/whatever/{**contentId**}", method = RequestMethod.POST)
public … method(@PathVariable Integer **contentID**){
}

It may help others

How to return multiple objects from a Java method?

Can do some thing like a tuple in dynamic language (Python)

public class Tuple {
private Object[] multiReturns;

private Tuple(Object... multiReturns) {
    this.multiReturns = multiReturns;
}

public static Tuple _t(Object... multiReturns){
    return new Tuple(multiReturns);
}

public <T> T at(int index, Class<T> someClass) {
    return someClass.cast(multiReturns[index]);
}
}

and use like this

public Tuple returnMultiValues(){
   return Tuple._t(new ArrayList(),new HashMap())
}


Tuple t = returnMultiValues();
ArrayList list = t.at(0,ArrayList.class);

Read values into a shell variable from a pipe

The following code:

echo "hello world" | ( test=($(< /dev/stdin)); echo test=$test )

will work too, but it will open another new sub-shell after the pipe, where

echo "hello world" | { test=($(< /dev/stdin)); echo test=$test; }

won't.


I had to disable job control to make use of chepnars' method (I was running this command from terminal):

set +m;shopt -s lastpipe
echo "hello world" | read test; echo test=$test
echo "hello world" | test="$(</dev/stdin)"; echo test=$test

Bash Manual says:

lastpipe

If set, and job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment.

Note: job control is turned off by default in a non-interactive shell and thus you don't need the set +m inside a script.

INNER JOIN ON vs WHERE clause

They have a different human-readable meaning.

However, depending on the query optimizer, they may have the same meaning to the machine.

You should always code to be readable.

That is to say, if this is a built-in relationship, use the explicit join. if you are matching on weakly related data, use the where clause.

Can pandas automatically recognize dates?

When merging two columns into a single datetime column, the accepted answer generates an error (pandas version 0.20.3), since the columns are sent to the date_parser function separately.

The following works:

def dateparse(d,t):
    dt = d + " " + t
    return pd.datetime.strptime(dt, '%d/%m/%Y %H:%M:%S')

df = pd.read_csv(infile, parse_dates={'datetime': ['date', 'time']}, date_parser=dateparse)

How do I update pip itself from inside my virtual environment?

Single Line Python Program
The best way I have found is to write a single line program that downloads and runs the official get-pip script. See below for the code.

The official docs recommend using curl to download the get-pip script, but since I work on windows and don't have curl installed I prefer using python itself to download and run the script.

Here is the single line program that can be run via the command line using Python 3:

python -c "import urllib.request; exec(urllib.request.urlopen('https://bootstrap.pypa.io/get-pip.py').read())"

This line gets the official "get-pip.py" script as per the installation notes and executes the script with the "exec" command.

For Python2 you would replace "urllib.request" with "urllib2":

python -c "import urllib2; exec(urllib2.urlopen('https://bootstrap.pypa.io/get-pip.py').read())"

Precautions
It's worth noting that running any python script blindly is inherently dangerous. For this reason, the official instructions recommend downloading the script and inspecting it before running.

That said, many people don't actually inspect the code and just run it. This one-line program makes that easier.

Set value to currency in <input type="number" />

It seems that you'll need two fields, a choice list for the currency and a number field for the value.

A common technique in such case is to use a div or span for the display (form fields offscreen), and on click switch to the form elements for editing.

jQuery window scroll event does not fire up

To whom its just not working to (like me) no matter what you tried: <element onscroll="myFunction()"></element> works like a charm

exactly as they explain in W3 schools https://www.w3schools.com/tags/ev_onscroll.asp

'list' object has no attribute 'shape'

if the type is list, use len(list) and len(list[0]) to get the row and column.

l = [[1,2,3,4], [0,1,3,4]]

len(l) will be 2 len(l[0]) will be 4

How to get position of a certain element in strings vector, to use it as an index in ints vector?

To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

Now you need to check pos against Names.size() to see if it is out of bounds or not:

if(pos >= Names.size()) {
    //old_name_ not found
}

vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

Its fairly simple

Lets suppose you do something like

document.ontouchmove = function(e){ e.preventDefault(); }

now to revert it to the original situation, do the below...

document.ontouchmove = function(e){ return true; }

From this website.

Path to Powershell.exe (v 2.0)

Here is one way...

(Get-Process powershell | select -First 1).Path

Here is possibly a better way, as it returns the first hit on the path, just like if you had ran Powershell from a command prompt...

(Get-Command powershell.exe).Definition

Converting Go struct to JSON

You need to export the User.name field so that the json package can see it. Rename the name field to Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Output:

{"Name":"Frank"}

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

Run exe file with parameters in a batch file

This should work:

start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2

The start command interprets the first argument as a window title if it contains spaces. In this case, that means start considers your whole argument a title and sees no command. Passing "" (an empty title) as the first argument to start fixes the problem.

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
    server 127.0.0.1:9000;
}

...

fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/my.site.sock

So I need just socket, no any 127.0.0.1:9000, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
}

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/my.site.sock;

IIS - can't access page by ip address instead of localhost

Follow the below steps -

  1. In IIS Right click the "Default Web Site"
  2. Click Edit Buildings in the context menu
  3. Select and edit
  4. Give your machine IP instead of "*" in IP Address

Get loop count inside a Python FOR loop

I know rather old question but....came across looking other thing so I give my shot:

[each*2 for each in [1,2,3,4,5] if each % 10 == 0])

How can I make my custom objects Parcelable?

Create Parcelable class without plugin in Android Studio

implements Parcelable in your class and then put cursor on "implements Parcelable" and hit Alt+Enter and select Add Parcelable implementation (see image). that's it.

enter image description here

How to get previous page url using jquery

Use can use one of below this

history.back();     // equivalent to clicking back button
history.go(-1);     // equivalent to history.back();

I am using as below for back button

<a class="btn btn-info float-right" onclick="history.back();" >Back</a>

How to create major and minor gridlines with different linestyles in Python

Actually, it is as simple as setting major and minor separately:

In [9]: plot([23, 456, 676, 89, 906, 34, 2345])
Out[9]: [<matplotlib.lines.Line2D at 0x6112f90>]

In [10]: yscale('log')

In [11]: grid(b=True, which='major', color='b', linestyle='-')

In [12]: grid(b=True, which='minor', color='r', linestyle='--')

The gotcha with minor grids is that you have to have minor tick marks turned on too. In the above code this is done by yscale('log'), but it can also be done with plt.minorticks_on().

enter image description here

How should I have explained the difference between an Interface and an Abstract class?

Almost everything seems to be covered here already.. Adding just one more point on practical implementation of abstract class:

abstract keyword is also used just prevent a class from being instantiated. If you have a concrete class which you do not want to be instantiated - Make it abstract.

Are the days of passing const std::string & as a parameter over?

Herb Sutter is still on record, along with Bjarne Stroustroup, in recommending const std::string& as a parameter type; see https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-in .

There is a pitfall not mentioned in any of the other answers here: if you pass a string literal to a const std::string& parameter, it will pass a reference to a temporary string, created on-the-fly to hold the characters of the literal. If you then save that reference, it will be invalid once the temporary string is deallocated. To be safe, you must save a copy, not the reference. The problem stems from the fact that string literals are const char[N] types, requiring promotion to std::string.

The code below illustrates the pitfall and the workaround, along with a minor efficiency option -- overloading with a const char* method, as described at Is there a way to pass a string literal as reference in C++.

(Note: Sutter & Stroustroup advise that if you keep a copy of the string, also provide an overloaded function with a && parameter and std::move() it.)

#include <string>
#include <iostream>
class WidgetBadRef {
public:
    WidgetBadRef(const std::string& s) : myStrRef(s)  // copy the reference...
    {}

    const std::string& myStrRef;    // might be a reference to a temporary (oops!)
};

class WidgetSafeCopy {
public:
    WidgetSafeCopy(const std::string& s) : myStrCopy(s)
            // constructor for string references; copy the string
    {std::cout << "const std::string& constructor\n";}

    WidgetSafeCopy(const char* cs) : myStrCopy(cs)
            // constructor for string literals (and char arrays);
            // for minor efficiency only;
            // create the std::string directly from the chars
    {std::cout << "const char * constructor\n";}

    const std::string myStrCopy;    // save a copy, not a reference!
};

int main() {
    WidgetBadRef w1("First string");
    WidgetSafeCopy w2("Second string"); // uses the const char* constructor, no temp string
    WidgetSafeCopy w3(w2.myStrCopy);    // uses the String reference constructor
    std::cout << w1.myStrRef << "\n";   // garbage out
    std::cout << w2.myStrCopy << "\n";  // OK
    std::cout << w3.myStrCopy << "\n";  // OK
}

OUTPUT:

const char * constructor
const std::string& constructor

Second string
Second string

Setting background colour of Android layout element

You can use simple color resources, specified usually inside res/values/colors.xml.

<color name="red">#ffff0000</color>

and use this via android:background="@color/red". This color can be used anywhere else too, e.g. as a text color. Reference it in XML the same way, or get it in code via getResources().getColor(R.color.red).

You can also use any drawable resource as a background, use android:background="@drawable/mydrawable" for this (that means 9patch drawables, normal bitmaps, shape drawables, ..).

HTML / CSS table with GRIDLINES

For internal gridlines, use the tag: td For external gridlines, use the tag: table

ASP.NET MVC: Custom Validation by DataAnnotation

To improve Darin's answer, it can be bit shorter:

public class UniqueFileName : ValidationAttribute
{
    private readonly NewsService _newsService = new NewsService();

    public override bool IsValid(object value)
    {
        if (value == null) { return false; }

        var file = (HttpPostedFile) value;

        return _newsService.IsFileNameUnique(file.FileName);
    }
}

Model:

[UniqueFileName(ErrorMessage = "This file name is not unique.")]

Do note that an error message is required, otherwise the error will be empty.

What's the difference between JPA and Hibernate?

JPA is just a specification while Hibernate is one of the JPA provider i.e hibernate is implementing various things mentioned in JPA contract.

How to normalize a NumPy array to within a certain range?

You can also rescale using sklearn. The advantages are that you can adjust normalize the standard deviation, in addition to mean-centering the data, and that you can do this on either axis, by features, or by records.

from sklearn.preprocessing import scale
X = scale( X, axis=0, with_mean=True, with_std=True, copy=True )

The keyword arguments axis, with_mean, with_std are self explanatory, and are shown in their default state. The argument copy performs the operation in-place if it is set to False. Documentation here.

Run reg command in cmd (bat file)?

You could also just create a Group Policy Preference and have it create the reg key for you. (no scripting involved)

The static keyword and its various uses in C++

Variables:

static variables exist for the "lifetime" of the translation unit that it's defined in, and:

  • If it's in a namespace scope (i.e. outside of functions and classes), then it can't be accessed from any other translation unit. This is known as "internal linkage" or "static storage duration". (Don't do this in headers except for constexpr. Anything else, and you end up with a separate variable in each translation unit, which is crazy confusing)
  • If it's a variable in a function, it can't be accessed from outside of the function, just like any other local variable. (this is the local they mentioned)
  • class members have no restricted scope due to static, but can be addressed from the class as well as an instance (like std::string::npos). [Note: you can declare static members in a class, but they should usually still be defined in a translation unit (cpp file), and as such, there's only one per class]

locations as code:

static std::string namespaceScope = "Hello";
void foo() {
    static std::string functionScope= "World";
}
struct A {
   static std::string classScope = "!";
};

Before any function in a translation unit is executed (possibly after main began execution), the variables with static storage duration (namespace scope) in that translation unit will be "constant initialized" (to constexpr where possible, or zero otherwise), and then non-locals are "dynamically initialized" properly in the order they are defined in the translation unit (for things like std::string="HI"; that aren't constexpr). Finally, function-local statics will be initialized the first time execution "reaches" the line where they are declared. All static variables all destroyed in the reverse order of initialization.

The easiest way to get all this right is to make all static variables that are not constexpr initialized into function static locals, which makes sure all of your statics/globals are initialized properly when you try to use them no matter what, thus preventing the static initialization order fiasco.

T& get_global() {
    static T global = initial_value();
    return global;
}

Be careful, because when the spec says namespace-scope variables have "static storage duration" by default, they mean the "lifetime of the translation unit" bit, but that does not mean it can't be accessed outside of the file.

Functions

Significantly more straightforward, static is often used as a class member function, and only very rarely used for a free-standing function.

A static member function differs from a regular member function in that it can be called without an instance of a class, and since it has no instance, it cannot access non-static members of the class. Static variables are useful when you want to have a function for a class that definitely absolutely does not refer to any instance members, or for managing static member variables.

struct A {
    A() {++A_count;}
    A(const A&) {++A_count;}
    A(A&&) {++A_count;}
    ~A() {--A_count;}

    static int get_count() {return A_count;}
private:
    static int A_count;
}

int main() {
    A var;

    int c0 = var.get_count(); //some compilers give a warning, but it's ok.
    int c1 = A::get_count(); //normal way
}

A static free-function means that the function will not be referred to by any other translation unit, and thus the linker can ignore it entirely. This has a small number of purposes:

  • Can be used in a cpp file to guarantee that the function is never used from any other file.
  • Can be put in a header and every file will have it's own copy of the function. Not useful, since inline does pretty much the same thing.
  • Speeds up link time by reducing work
  • Can put a function with the same name in each translation unit, and they can all do different things. For instance, you could put a static void log(const char*) {} in each cpp file, and they could each all log in a different way.

How to sort an array of ints using a custom comparator?

You don't need external library:

Integer[] input = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(input, (a, b) -> b - a); // reverse order
return Arrays.stream(input).mapToInt(Integer::intValue).toArray();

How to change TextBox's Background color?

webforms;

TextBox.Background = System.Drawing.Color.Red;

MySQL - ERROR 1045 - Access denied

use this command to check the possible output

mysql> select user,host,password from mysql.user;

output

mysql> select user,host,password from mysql.user;
+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     |                                           |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)
  1. In this user admin will not be allowed to login from another host though you have granted permission. the reason is that user admin is not identified by any password.
  2. Grant the user admin with password using GRANT command once again

    mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED by 'password'
    

then check the GRANT LIST the out put will be like his

mysql> select user,host,password from mysql.user;

+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)

if the desired user for example user 'admin' is need to be allowed login then use once GRANT command and execute the command.

Now the user should be allowed to login.

How to clear a chart from a canvas so that hover events cannot be triggered?

First put chart in some variable then history it next time before init

#Check if myChart object exist then distort it

    if($scope.myChart) {
      $scope.myChart.destroy();
    }

    $scope.myChart  = new Chart(targetCanvas

Jquery : Refresh/Reload the page on clicking a button

Use this line simply inside your head with

       window.location.reload(true);

It will load your current page or view.

Class 'DOMDocument' not found

For Centos 7 and php 7.1:
yum install php71w-xml
apachectl restart

Using Jquery Datatable with AngularJs

Take a look at this: AngularJS+JQuery(datatable)

FULL code: http://jsfiddle.net/zdam/7kLFU/

JQuery Datatables's Documentation: http://www.datatables.net/

var dialogApp = angular.module('tableExample', []);

    dialogApp.directive('myTable', function() {
        return function(scope, element, attrs) {

            // apply DataTable options, use defaults if none specified by user
            var options = {};
            if (attrs.myTable.length > 0) {
                options = scope.$eval(attrs.myTable);
            } else {
                options = {
                    "bStateSave": true,
                    "iCookieDuration": 2419200, /* 1 month */
                    "bJQueryUI": true,
                    "bPaginate": false,
                    "bLengthChange": false,
                    "bFilter": false,
                    "bInfo": false,
                    "bDestroy": true
                };
            }

            // Tell the dataTables plugin what columns to use
            // We can either derive them from the dom, or use setup from the controller           
            var explicitColumns = [];
            element.find('th').each(function(index, elem) {
                explicitColumns.push($(elem).text());
            });
            if (explicitColumns.length > 0) {
                options["aoColumns"] = explicitColumns;
            } else if (attrs.aoColumns) {
                options["aoColumns"] = scope.$eval(attrs.aoColumns);
            }

            // aoColumnDefs is dataTables way of providing fine control over column config
            if (attrs.aoColumnDefs) {
                options["aoColumnDefs"] = scope.$eval(attrs.aoColumnDefs);
            }

            if (attrs.fnRowCallback) {
                options["fnRowCallback"] = scope.$eval(attrs.fnRowCallback);
            }

            // apply the plugin
            var dataTable = element.dataTable(options);



            // watch for any changes to our data, rebuild the DataTable
            scope.$watch(attrs.aaData, function(value) {
                var val = value || null;
                if (val) {
                    dataTable.fnClearTable();
                    dataTable.fnAddData(scope.$eval(attrs.aaData));
                }
            });
        };
    });

function Ctrl($scope) {

    $scope.message = '';            

        $scope.myCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {            
            $('td:eq(2)', nRow).bind('click', function() {
                $scope.$apply(function() {
                    $scope.someClickHandler(aData);
                });
            });
            return nRow;
        };

        $scope.someClickHandler = function(info) {
            $scope.message = 'clicked: '+ info.price;
        };

        $scope.columnDefs = [ 
            { "mDataProp": "category", "aTargets":[0]},
            { "mDataProp": "name", "aTargets":[1] },
            { "mDataProp": "price", "aTargets":[2] }
        ]; 

        $scope.overrideOptions = {
            "bStateSave": true,
            "iCookieDuration": 2419200, /* 1 month */
            "bJQueryUI": true,
            "bPaginate": true,
            "bLengthChange": false,
            "bFilter": true,
            "bInfo": true,
            "bDestroy": true
        };


        $scope.sampleProductCategories = [

              {
                "name": "1948 Porsche 356-A Roadster",
                "price": 53.9,
                  "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1948 Porsche Type 356 Roadster",
                "price": 62.16,
            "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1949 Jaguar XK 120",
                "price": 47.25,
            "category": "Classic Cars",
                  "action":"x"
              }
              ,
              {
                "name": "1936 Harley Davidson El Knucklehead",
                "price": 24.23,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1957 Vespa GS150",
                "price": 32.95,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1960 BSA Gold Star DBD34",
                "price": 37.32,
            "category": "Motorcycles",
                  "action":"x"
              }
           ,
              {
                "name": "1900s Vintage Bi-Plane",
                "price": 34.25,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1900s Vintage Tri-Plane",
                "price": 36.23,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1928 British Royal Navy Airplane",
                "price": 66.74,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1980s Black Hawk Helicopter",
                "price": 77.27,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "ATA: B757-300",
                "price": 59.33,
            "category": "Planes",
                  "action":"x"
              }

        ];            

}

Validation of file extension before uploading file

I think better to try with mimetype than checking extension. Because, sometimes files can be exist without it and those are working very well in linux and unix systems.

So, you can try something like this:

["image/jpeg", "image/png", "image/gif"].indexOf(file.type) > -1

What's the simplest way to print a Java array?

Prior to Java 8

We could have used Arrays.toString(array) to print one dimensional array and Arrays.deepToString(array) for multi-dimensional arrays.

Java 8

Now we have got the option of Stream and lambda to print the array.

Printing One dimensional Array:

public static void main(String[] args) {
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    String[] strArray = new String[] {"John", "Mary", "Bob"};

    //Prior to Java 8
    System.out.println(Arrays.toString(intArray));
    System.out.println(Arrays.toString(strArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(intArray).forEach(System.out::println);
    Arrays.stream(strArray).forEach(System.out::println);
}

The output is:

[1, 2, 3, 4, 5]
[John, Mary, Bob]
1
2
3
4
5
John
Mary
Bob

Printing Multi-dimensional Array Just in case we want to print multi-dimensional array we can use Arrays.deepToString(array) as:

public static void main(String[] args) {
    int[][] int2DArray = new int[][] { {11, 12}, { 21, 22}, {31, 32, 33} };
    String[][] str2DArray = new String[][]{ {"John", "Bravo"} , {"Mary", "Lee"}, {"Bob", "Johnson"} };

    //Prior to Java 8
    System.out.println(Arrays.deepToString(int2DArray));
    System.out.println(Arrays.deepToString(str2DArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(int2DArray).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);
    Arrays.stream(str2DArray).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
} 

Now the point to observe is that the method Arrays.stream(T[]), which in case of int[] returns us Stream<int[]> and then method flatMapToInt() maps each element of stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

The output is:

[[11, 12], [21, 22], [31, 32, 33]]
[[John, Bravo], [Mary, Lee], [Bob, Johnson]]
11
12
21
22
31
32
33
John
Bravo
Mary
Lee
Bob
Johnson

How to convert a string to ASCII

You can do it by using LINQ-expression.

  public static List<int> StringToAscii(string value)
  {
        if (string.IsNullOrEmpty(value))
            throw new ArgumentException("Value cannot be null or empty.", nameof(value));

        return value.Select(System.Convert.ToInt32).ToList();
  } 

Sorting dropdown alphabetically in AngularJS

var module = angular.module("example", []);

module.controller("orderByController", function ($scope) {
    $scope.orderByValue = function (value) {
        return value;
    };

    $scope.items = ["c", "b", "a"];
    $scope.objList = [
        {
            "name": "c"
        }, {
            "name": "b"
        }, {
            "name": "a"
        }];
        $scope.item = "b";
    });

http://jsfiddle.net/Nfv42/65/

How do I use FileSystemObject in VBA?

These guys have excellent examples of how to use the filesystem object http://www.w3schools.com/asp/asp_ref_filesystem.asp

<%
dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\test.txt",true)
fname.WriteLine("Hello World!")
fname.Close
set fname=nothing
set fs=nothing
%> 

UTF-8 all the way through

I'd like to add one thing to chazomaticus' excellent answer:

Don't forget the META tag either (like this, or the HTML4 or XHTML version of it):

<meta charset="utf-8">

That seems trivial, but IE7 has given me problems with that before.

I was doing everything right; the database, database connection and Content-Type HTTP header were all set to UTF-8, and it worked fine in all other browsers, but Internet Explorer still insisted on using the "Western European" encoding.

It turned out the page was missing the META tag. Adding that solved the problem.

Edit:

The W3C actually has a rather large section dedicated to I18N. They have a number of articles related to this issue – describing the HTTP, (X)HTML and CSS side of things:

They recommend using both the HTTP header and HTML meta tag (or XML declaration in case of XHTML served as XML).

Recommended website resolution (width and height)?

Try to target 1024 as the minimum width. Try how it looks at 800, but don't bother too much making that work. At 800x600 almost none of the major websites are going to work, so people working at that resolution are going to have problems all the time anyway.

If you're going to go for a liquid layout, make sure that text doesn't get too wide, because when lines are too long, they become hard to read. That's the main reason why most websites have a fixed width.

How do I write a "tab" in Python?

It's usually \t in command-line interfaces, which will convert the char \t into the whitespace tab character.

For example, hello\talex -> hello--->alex.

How can I pretty-print JSON in a shell script?

You can use this simple command to achieve the result:

echo "{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }"|python -m json.tool

How do I disable "missing docstring" warnings at a file-level in Pylint?

Go to file "settings.json" and disable the Python pydocstyle:

"python.linting.pydocstyleEnabled": false

Changing Placeholder Text Color with Swift

In Swift 3.0, Use

let color = UIColor.lightText
textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder, attributes: [NSForegroundColorAttributeName : color])

In Siwft 5.0 + Use

let color = UIColor.lightText
let placeholder = textField.placeholder ?? "" //There should be a placeholder set in storyboard or elsewhere string or pass empty
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor : color])

How to get all elements which name starts with some string?

HTML DOM querySelectorAll() method seems apt here.

W3School Link given here

Syntax (As given in W3School)

document.querySelectorAll(CSS selectors)

So the answer.

document.querySelectorAll("[name^=q1_]")

Fiddle

Edit:

Considering FLX's suggestion adding link to MDN here

How can I use the python HTMLParser library to extract data from a specific div tag?

Have You tried BeautifulSoup ?

from bs4 import BeautifulSoup
soup = BeautifulSoup('<div id="remository">20</div>')
tag=soup.div
print(tag.string)

This gives You 20 on output.

Attaching click event to a JQuery object not yet added to the DOM

Use this. You can replace body with any parent element that exists on dom ready

$('body').on('click', '#my-button', function () {
     console.log("yeahhhh!!! but this doesn't work for me :(");
});

Look here http://api.jquery.com/on/ for more info on how to use on() as it replaces live() as of 1.7+.

Below lists which version you should be using

$(selector).live(events, data, handler); // jQuery 1.3+

$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+

$(document).on(events, selector, data, handler); // jQuery 1.7+

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use a ComboBox with its ComboBoxStyle (appears as DropDownStyle in later versions) set to DropDownList. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx

Replacement for "rename" in dplyr

The next version of dplyr will support an improved version of select that also incorporates renaming:

> mtcars2 <- select( mtcars, disp2 = disp )
> head( mtcars2 )
                  disp2
Mazda RX4         160
Mazda RX4 Wag     160
Datsun 710        108
Hornet 4 Drive    258
Hornet Sportabout 360
Valiant           225
> changes( mtcars, mtcars2 )
Changed variables:
      old         new
disp  0x105500400
disp2             0x105500400

Changed attributes:
      old         new
names 0x106d2cf50 0x106d28a98

How to make html table vertically scrollable

Just add the display:block to the thead > tr and tbody. check the below example

http://www.imaputz.com/cssStuff/bigFourVersion.html

Remove Top Line of Text File with PowerShell

Inspired by AASoft's answer, I went out to improve it a bit more:

  1. Avoid the loop variable $i and the comparison with 0 in every loop
  2. Wrap the execution into a try..finally block to always close the files in use
  3. Make the solution work for an arbitrary number of lines to remove from the beginning of the file
  4. Use a variable $p to reference the current directory

These changes lead to the following code:

$p = (Get-Location).Path

(Measure-Command {
    # Number of lines to skip
    $skip = 1
    $ins = New-Object System.IO.StreamReader ($p + "\test.log")
    $outs = New-Object System.IO.StreamWriter ($p + "\test-1.log")
    try {
        # Skip the first N lines, but allow for fewer than N, as well
        for( $s = 1; $s -le $skip -and !$ins.EndOfStream; $s++ ) {
            $ins.ReadLine()
        }
        while( !$ins.EndOfStream ) {
            $outs.WriteLine( $ins.ReadLine() )
        }
    }
    finally {
        $outs.Close()
        $ins.Close()
    }
}).TotalSeconds

The first change brought the processing time for my 60 MB file down from 5.3s to 4s. The rest of the changes is more cosmetic.

Increase number of axis ticks

The upcoming version v3.3.0 of ggplot2 will have an option n.breaks to automatically generate breaks for scale_x_continuous and scale_y_continuous

    devtools::install_github("tidyverse/ggplot2")

    library(ggplot2)

    plt <- ggplot(mtcars, aes(x = mpg, y = disp)) +
      geom_point()

    plt + 
      scale_x_continuous(n.breaks = 5)

enter image description here

    plt + 
      scale_x_continuous(n.breaks = 10) +
      scale_y_continuous(n.breaks = 10)

enter image description here

How to supply value to an annotation from a Constant java

I am thinking this may not be possible in Java because annotation and its parameters are resolved at compile time.

With Seam 2 http://seamframework.org/ you were able to resolve annotation parameters at runtime, with expression language inside double quotes.

In Seam 3 http://seamframework.org/Seam3/Solder, this feature is the module Seam Solder

Chain-calling parent initialisers in python

The way you are doing it is indeed the recommended one (for Python 2.x).

The issue of whether the class is passed explicitly to super is a matter of style rather than functionality. Passing the class to super fits in with Python's philosophy of "explicit is better than implicit".

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

Sometimes in order to write less code it is used to have SQL server set fields like date, time and ID on insert by setting the default value for fields to GETDATE() or NEWID().

In such cases Auto Generated Value property of those fields in entity classes should be set to true.

This way you do not need to set values in code (preventing energy consumption!!!) and never see that exception.

How do I find the MySQL my.cnf location

On Ubuntu (direct edit) :

$ sudo nano /etc/mysql.conf.d/mysqld.cnf

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

The Taylor series is one way to approximate pi. As noted it converges slowly.

The partial sums of the Taylor series can be shown to be within some multiplier of the next term away from the true value of pi.

Other means of approximating pi have similar ways to calculate the max error.

We know this because we can prove it mathematically.

Where is Python language used?

Python is also great for scientific programs such as statistical models or physics sims. I've done monte-carlo programs and, using the VISUAL module, a 3D simulation of the Apollo mission.

How to read a .properties file which contains keys that have a period character using Shell script

I found using while IFS='=' read -r to be a bit slow (I don't know why, maybe someone could briefly explain in a comment or point to a SO answer?). I also found @Nicolai answer very neat as a one-liner, but very inefficient as it will scan the entire properties file over and over again for every single call of prop.

I found a solution that answers the question, performs well and it is a one-liner (bit verbose line though).

The solution does sourcing but massages the contents before sourcing:

#!/usr/bin/env bash

source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')

echo $db_uat_user

Explanation:

grep -v '^ *#': discard comment lines grep '[^ ] *=': discards lines without = split($0,a,"="): splits line at = and stores into array a, i.e. a[1] is the key, a[2] is the value gensub(/\./, "_", "g", a[1]): replaces . with _ print gensub... "=" a[2]} concatenates the result of gensub above with = and value.

Edit: As others pointed out, there are some incompatibilities issues (awk) and also it does not validate the contents to see if every line of the property file is actually a kv pair. But the goal here is to show the general idea for a solution that is both fast and clean. Sourcing seems to be the way to go as it loads the properties once that can be used multiple times.

For loop example in MySQL

You can exchange this local variable for a global, it would be easier.

DROP PROCEDURE IF EXISTS ABC;
DELIMITER $$  
CREATE PROCEDURE ABC()

   BEGIN
      SET @a = 0;
      simple_loop: LOOP
         SET @a=@a+1;
         select @a;
         IF @a=5 THEN
            LEAVE simple_loop;
         END IF;
   END LOOP simple_loop;
END $$

Shell script "for" loop syntax

Try the arithmetic-expression version of for:

max=10
for (( i=2; i <= $max; ++i ))
do
    echo "$i"
done

This is available in most versions of bash, and should be Bourne shell (sh) compatible also.

How do I get current URL in Selenium Webdriver 2 Python?

Use current_url element for Python 2:

print browser.current_url

For Python 3 and later versions of selenium:

print(driver.current_url)

EXTRACT() Hour in 24 Hour format

The problem is not with extract, which can certainly handle 'military time'. It looks like you have a default timestamp format which has HH instead of HH24; or at least that's the only way I can see to recreate this:

SQL> select value from nls_session_parameters
  2  where parameter = 'NLS_TIMESTAMP_FORMAT';

VALUE
--------------------------------------------------------------------------------
DD-MON-RR HH24.MI.SSXFF

SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
  2  as timestamp)) from dual;

EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
                                                                        15

alter session set nls_timestamp_format = 'DD-MON-YYYY HH:MI:SS';

Session altered.

SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
  2  as timestamp)) from dual;

select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS') as timestamp)) from dual
                              *
ERROR at line 1:
ORA-01849: hour must be between 1 and 12

So the simple 'fix' is to set the format to something that does recognise 24-hours:

SQL> alter session set nls_timestamp_format = 'DD-MON-YYYY HH24:MI:SS';

Session altered.

SQL> select extract(hour from cast(to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS')
  2  as timestamp)) from dual;

EXTRACT(HOURFROMCAST(TO_CHAR(SYSDATE,'DD-MON-YYYYHH24:MI:SS')ASTIMESTAMP))
--------------------------------------------------------------------------
                                                                        15

Although you don't need the to_char at all:

SQL> select extract(hour from cast(sysdate as timestamp)) from dual;

EXTRACT(HOURFROMCAST(SYSDATEASTIMESTAMP))
-----------------------------------------
                                       15

WPF checkbox binding

You need a dependency property for this:

public BindingList<User> Users
{
    get { return (BindingList<User>)GetValue(UsersProperty); }
    set { SetValue(UsersProperty, value); }
}

public static readonly DependencyProperty UsersProperty =
    DependencyProperty.Register("Users", typeof(BindingList<User>), 
      typeof(OptionsDialog));

Once that is done, you bind the checkbox to the dependency property:

<CheckBox x:Name="myCheckBox"
          IsChecked="{Binding ElementName=window1, Path=CheckBoxIsChecked}" />

For that to work you have to name your Window or UserControl in its openning tag, and use that name in the ElementName parameter.

With this code, whenever you change the property on the code side, you will change the textbox. Also, whenever you check/uncheck the textbox, the Dependency Property will change too.

EDIT:

An easy way to create a dependency property is typing the snippet propdp, which will give you the general code for Dependency Properties.

All the code:

XAML:

<Window x:Class="StackOverflowTests.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" x:Name="window1" Height="300" Width="300">
    <Grid>
        <StackPanel Orientation="Vertical">
            <CheckBox Margin="10"
                      x:Name="myCheckBox"
                      IsChecked="{Binding ElementName=window1, Path=IsCheckBoxChecked}">
                Bound CheckBox
            </CheckBox>
            <Label Content="{Binding ElementName=window1, Path=IsCheckBoxChecked}"
                   ContentStringFormat="Is checkbox checked? {0}" />
        </StackPanel>
    </Grid>
</Window>

C#:

using System.Windows;

namespace StackOverflowTests
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public bool IsCheckBoxChecked
        {
           get { return (bool)GetValue(IsCheckBoxCheckedProperty); }
           set { SetValue(IsCheckBoxCheckedProperty, value); }
        }

        // Using a DependencyProperty as the backing store for 
         //IsCheckBoxChecked.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsCheckBoxCheckedProperty =
            DependencyProperty.Register("IsCheckBoxChecked", typeof(bool), 
            typeof(Window1), new UIPropertyMetadata(false));

        public Window1()
        {             
            InitializeComponent();
        }
    }
}

Notice how the only code behind is the Dependency Property. Both the label and the checkbox are bound to it. If the checkbox changes, the label changes too.

What is the purpose of backbone.js?

Backbone was created by Jeremy Ashkenas who also wrote CoffeeScript. As a JavaScript-heavy application, what we now know as Backbone was responsible for structuring the application into a coherent code base. Underscore.js, backbone's only dependency, was also part of the DocumentCloud application.

Backbone helps developers manage a data model in their client-side web app with as much discipline and structure as you would get in traditional server-side application logic.

Additional benefits of using Backbone.js

  1. See Backbone as a library, not as a framework
  2. Javascript is now getting organized in a structured way, the (MVVM) Model
  3. Large user community

Can I use tcpdump to get HTTP requests, response header and response body?

There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):

  • Run man tcpdump | less -Ip examples to see some examples

  • Here’s a tcpdump filter for HTTP GET (GET = 0x47, 0x45, 0x54, 0x20):

    sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
    
  • Here’s a tcpdump filter for HTTP POST (POST = 0x50, 0x4f, 0x53, 0x54):

    sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
    
  • Monitor HTTP traffic including request and response headers and message body (source):

    tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    

For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).

How can I push a specific commit to a remote, and not previous commits?

I did want to obmit a old big history and start from a fresh commit i choosed to:

rsync -a --exclude '.git' old-repo/ new-repo/
cd new-repo 
git push 

when now old-repo changes i can apply the patches to the new-repo to rebase them on the new-repo.

Linq code to select one item

Depends how much you like the linq query syntax, you can use the extension methods directly like:

var item = Items.First(i => i.Id == 123);

And if you don't want to throw an error if the list is empty, use FirstOrDefault which returns the default value for the element type (null for reference types):

var item = Items.FirstOrDefault(i => i.Id == 123);

if (item != null)
{
    // found it
}

Single() and SingleOrDefault() can also be used, but if you are reading from a database or something that already guarantees uniqueness I wouldn't bother as it has to scan the list to see if there's any duplicates and throws. First() and FirstOrDefault() stop on the first match, so they are more efficient.

Of the First() and Single() family, here's where they throw:

  • First() - throws if empty/not found, does not throw if duplicate
  • FirstOrDefault() - returns default if empty/not found, does not throw if duplicate
  • Single() - throws if empty/not found, throws if duplicate exists
  • SingleOrDefault() - returns default if empty/not found, throws if duplicate exists

How to send and retrieve parameters using $state.go toParams and $stateParams?

In my case I tried with all the options given here, but no one was working properly (angular 1.3.13, ionic 1.0.0, angular-ui-router 0.2.13). The solution was:

.state('tab.friends', {
      url: '/friends/:param1/:param2',
      views: {
        'tab-friends': {
          templateUrl: 'templates/tab-friends.html',
          controller: 'FriendsCtrl'
        }
      }
    })

and in the state.go:

$state.go('tab.friends', {param1 : val1, param2 : val2});

Cheers

ASP.NET jQuery Ajax Calling Code-Behind Method

Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });

Using CSS to affect div style inside iframe

Just add this and all works well:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">

How to get current class name including package name in Java?

The fully-qualified name is opbtained as follows:

String fqn = YourClass.class.getName();

But you need to read a classpath resource. So use

InputStream in = YourClass.getResourceAsStream("resource.txt");

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

my problem was with @WebServelet annotation and it was because of the name was repeated, I had two of @WebServlet("/route")in my code by mistake(I copy and pasted and forgot to change the route name)

Convert datetime to Unix timestamp and convert it back in python

If your datetime object represents UTC time, don't use time.mktime, as it assumes the tuple is in your local timezone. Instead, use calendar.timegm:

>>> import datetime, calendar
>>> d = datetime.datetime(1970, 1, 1, 0, 1, 0)
>>> calendar.timegm(d.timetuple())
60

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

Counting number of words in a file

You can use a Scanner with a FileInputStream instead of BufferedReader with a FileReader. For example:-

File file = new File("sample.txt");
try(Scanner sc = new Scanner(new FileInputStream(file))){
    int count=0;
    while(sc.hasNext()){
        sc.next();
        count++;
    }
System.out.println("Number of words: " + count);
}

Woocommerce get products

<?php
$args     = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args ); 
?>

This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products

Code for best fit straight line of a scatter plot in python

Have implemented @Micah 's solution to generate a trendline with a few changes and thought I'd share:

  • Coded as a function
  • Option for a polynomial trendline (input order=2)
  • Function can also just return the coefficient of determination (R^2, input Rval=True)
  • More Numpy array optimisations

Code:

def trendline(xd, yd, order=1, c='r', alpha=1, Rval=False):
    """Make a line of best fit"""

    #Calculate trendline
    coeffs = np.polyfit(xd, yd, order)

    intercept = coeffs[-1]
    slope = coeffs[-2]
    power = coeffs[0] if order == 2 else 0

    minxd = np.min(xd)
    maxxd = np.max(xd)

    xl = np.array([minxd, maxxd])
    yl = power * xl ** 2 + slope * xl + intercept

    #Plot trendline
    plt.plot(xl, yl, c, alpha=alpha)

    #Calculate R Squared
    p = np.poly1d(coeffs)

    ybar = np.sum(yd) / len(yd)
    ssreg = np.sum((p(xd) - ybar) ** 2)
    sstot = np.sum((yd - ybar) ** 2)
    Rsqr = ssreg / sstot

    if not Rval:
        #Plot R^2 value
        plt.text(0.8 * maxxd + 0.2 * minxd, 0.8 * np.max(yd) + 0.2 * np.min(yd),
                 '$R^2 = %0.2f$' % Rsqr)
    else:
        #Return the R^2 value:
        return Rsqr

How can I match a string with a regex in Bash?

shopt -s nocasematch

if [[ sed-4.2.2.$LINE =~ (yes|y)$ ]]
 then exit 0 
fi

Navigation drawer: How do I set the selected item at startup?

You have to call 2 functions for this:

First: for excuting the commands you have implemented in onNavigationItemSelected listener:

onNavigationItemSelected(navigationView.getMenu().getItem(R.id.nav_camera));

Second: for changing the state of the navigation drawer menu item to selected (or checked):

navigationView.setCheckedItem(R.id.nav_camera);

I called both functions and it worked for me.

Creating an instance using the class name and calling constructor

Very Simple way to create an object in Java using Class<?> with constructor argument(s) passing:

Case 1:- Here, is a small code in this Main class:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {

    public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        // Get class name as string.
        String myClassName = Base.class.getName();
        // Create class of type Base.
        Class<?> myClass = Class.forName(myClassName);
        // Create constructor call with argument types.
        Constructor<?> ctr = myClass.getConstructor(String.class);
        // Finally create object of type Base and pass data to constructor.
        String arg1 = "My User Data";
        Object object = ctr.newInstance(new Object[] { arg1 });
        // Type-cast and access the data from class Base.
        Base base = (Base)object;
        System.out.println(base.data);
    }

}

And, here is the Base class structure:

public class Base {

    public String data = null;

    public Base() 
    {
        data = "default";
        System.out.println("Base()");
    }

    public Base(String arg1) {
        data = arg1;
        System.out.println("Base("+arg1+")");
    }

}

Case 2:- You, can code similarly for constructor with multiple argument and copy constructor. For example, passing 3 arguments as parameter to the Base constructor will need the constructor to be created in class and a code change in above as:

Constructor<?> ctr = myClass.getConstructor(String.class, String.class, String.class);
Object object = ctr.newInstance(new Object[] { "Arg1", "Arg2", "Arg3" }); 

And here the Base class should somehow look like:

public class Base {

    public Base(String a, String b, String c){
        // This constructor need to be created in this case.
    }   
}

Note:- Don't forget to handle the various exceptions which need to be handled in the code.

x86 Assembly on a Mac

Also, on the Intel Macs, can I use generic x86 asm? or is there a modified instruction set? Any information about post Intel Mac assembly helps.

It's the same instruction set; it's the same chips.

Create a CSS rule / class with jQuery at runtime

if you don' t want to assign a display:none to a css class, the right approach in to append to style, jQuery.Rule do the job.

I some cases you want to apply stiles before the append event of ajax content and fade content after append and this is it!

How to get a JavaScript object's class?

There's no exact counterpart to Java's getClass() in JavaScript. Mostly that's due to JavaScript being a prototype-based language, as opposed to Java being a class-based one.

Depending on what you need getClass() for, there are several options in JavaScript:

A few examples:

function Foo() {}
var foo = new Foo();

typeof Foo;             // == "function"
typeof foo;             // == "object"

foo instanceof Foo;     // == true
foo.constructor.name;   // == "Foo"
Foo.name                // == "Foo"    

Foo.prototype.isPrototypeOf(foo);   // == true

Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21);            // == 42

Note: if you are compiling your code with Uglify it will change non-global class names. To prevent this, Uglify has a --mangle param that you can set to false is using gulp or grunt.

Spring data JPA query with parameter properties

if we are using JpaRepository then it will internally created the queries.

Sample

findByLastnameAndFirstname(String lastname,String firstname)

findByLastnameOrFirstname(String lastname,String firstname)

findByStartDateBetween(Date date1,Date2)

findById(int id)

Note

if suppose we need complex queries then we need to write manual queries like

@Query("SELECT salesOrder FROM SalesOrder salesOrder WHERE salesOrder.clientId=:clientId AND salesOrder.driver_username=:driver_username AND salesOrder.date>=:fdate AND salesOrder.date<=:tdate ")
 @Transactional(readOnly=true)
 List<SalesOrder> findAllSalesByDriver(@Param("clientId")Integer clientId, @Param("driver_username")String driver_username, @Param("fdate") Date fDate, @Param("tdate") Date tdate);

Print directly from browser without print popup window

IE9 no longer supports triggering the Print() VBScript by calling window.print() like IE7 and IE8 do, and thus window.print() will now always trigger the print dialog in IE9.

The fix is pretty simple. You just need to call Print() itself, instead of window.print() in the onclick event.

I've described the fix in more detail in an answer to another question, with a working code example sporting slightly updated HTML syntax (as much as possible while still tested as working code).

You can find that sample code here:

Bypass Printdialog in IE9

Custom li list-style with font-awesome icon

I wanted to add to JOPLOmacedo's answer. His solution is my favourite, but I always had problem with indentation when the li had more than one line. It was fiddly to find the correct indentation with margins etc. But this might concern only me.

For me absolute positioning of the :before pseudo-element works best. I set padding-left on ul, negative position left on the :before element, same as ul's padding-left. To get the distance of the content from the :before element right I just set the padding-left on the li. Of course the li has to have position relative. For example

ul {
  margin: 0 0 1em 0;
  padding: 0 0 0 1em;
  /* make space for li's :before */
  list-style: none;
}

li {
  position: relative;
  padding-left: 0.4em;
  /* text distance to icon */
}

li:before {
  font-family: 'my-icon-font';
  content: 'character-code-here';
  position: absolute;
  left: -1em;
  /* same as ul padding-left */
  top: 0.65em;
  /* depends on character, maybe use padding-top instead */
  /*  .... more styling, maybe set width etc ... */
}

Hopefully this is clear and has some value for someone else than me.

Creating a UIImage from a UIColor to use as a background image for UIButton

Are you using ARC? The problem here is that you don't have a reference to the UIColor object that you're trying to apply; the CGColor is backed by that UIColor, but ARC will deallocate the UIColor before you have a chance to use the CGColor.

The clearest solution is to have a local variable pointing to your UIColor with the objc_precise_lifetime attribute.

You can read more about this exact case on this article about UIColor and short ARC lifetimes or get more details about the objc_precise_lifetime attribute.

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

how to display excel sheet in html page

You can upload it into Google Docs, and embed the Google Spreadsheet as detailed here: http://support.google.com/docs/bin/answer.py?hl=en&answer=55244

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

Display the binary representation of a number in C?

There is no direct format specifier for this in the C language. Although I wrote this quick python snippet to help you understand the process step by step to roll your own.

#!/usr/bin/python

dec = input("Enter a decimal number to convert: ")
base = 2
solution = ""

while dec >= base:
    solution = str(dec%base) + solution
    dec = dec/base
if dec > 0:
    solution = str(dec) + solution

print solution

Explained:

dec = input("Enter a decimal number to convert: ") - prompt the user for numerical input (there are multiple ways to do this in C via scanf for example)

base = 2 - specify our base is 2 (binary)

solution = "" - create an empty string in which we will concatenate our solution

while dec >= base: - while our number is bigger than the base entered

solution = str(dec%base) + solution - get the modulus of the number to the base, and add it to the beginning of our string (we must add numbers right to left using division and remainder method). the str() function converts the result of the operation to a string. You cannot concatenate integers with strings in python without a type conversion.

dec = dec/base - divide the decimal number by the base in preperation to take the next modulo

if dec > 0: solution = str(dec) + solution - if anything is left over, add it to the beginning (this will be 1, if anything)

print solution - print the final number

Using partial views in ASP.net MVC 4

You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

LaTeX source code listing like in professional books

It seems to me that what you really want, is to customize the look of the captions. This is most easily done using the caption package. For instructions how to use this package, see the manual (PDF). You would probably need to create your own custom caption format, as described in chapter 4 in the manual.

Edit: Tested with MikTex:

\documentclass{report}

\usepackage{color}
\usepackage{xcolor}
\usepackage{listings}

\usepackage{caption}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}

% This concludes the preamble

\begin{document}

\begin{lstlisting}[label=some-code,caption=Some Code]
public void here() {
    goes().the().code()
}
\end{lstlisting}

\end{document}

Result:

Preview

PHP write file from input to txt

The problems you have are because of the extra <form> you have, that your data goes in GET method, and you are accessing the data in PHP using POST.

<body>
<!--<form>-->
    <form action="myprocessingscript.php" method="POST">

Angular2 router (@angular/router), how to set default route?

With the current version of angular 2 you can't use '/' on a path or give a name to your route. What you can do is create a route file like "app.routes.ts" and import your components, make sure of the path when importing.

import { Component } from '@angular/core';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ConfigManagerComponent } from './configManager/configManager.component';
import { ApplicationMgmtComponent } from './applicationMgmt/applicationMgmt.component';
import { MergeComponent } from './merge/merge.component';`

Add:

import {RouterConfig, provideRouter } from '@angular/router';

Then your routes:

const routes:RouterConfig = [      
    { path: 'Dashboard', component: DashboardComponent },
    { path: 'ConfigManager', component: ConfigManagerComponent },
    { path: 'Merge', component: MergeComponent },
    { path: 'ApplicationManagement', component: ApplicationMgmtComponent }
 ];

Then export:

export  const APP_ROUTER_PROVIDERS = [
    provideRouter(routes)]

In your main.ts import APP_ROUTER_PROVIDERS and add bootstrap the router providers to the main.ts like this:

bootstrap(AppComponent,[APP_ROUTER_PROVIDERS]);

Finally, your link will look like this:

li class="nav hidden-xs"><a [routerLink]="['./Dashboard']" routerLinkActive="active">Dashboard</a>/li>

Python Pandas replicate rows in dataframe

df = df_try
for i in range(4):
   df = df.append(df_try)

# Here, we have df_try times 5

df = df.append(df)

# Here, we have df_try times 10

Remove non-ascii character in string

It can also be done with a positive assertion of removal, like this:

textContent = textContent.replace(/[\u{0080}-\u{FFFF}]/gu,"");

This uses unicode. In Javascript, when expressing unicode for a regular expression, the characters are specified with the escape sequence \u{xxxx} but also the flag 'u' must present; note the regex has flags 'gu'.

I called this a "positive assertion of removal" in the sense that a "positive" assertion expresses which characters to remove, while a "negative" assertion expresses which letters to not remove. In many contexts, the negative assertion, as stated in the prior answers, might be more suggestive to the reader. The circumflex "^" says "not" and the range \x00-\x7F says "ascii," so the two together say "not ascii."

textContent = textContent.replace(/[^\x00-\x7F]/g,"");

That's a great solution for English language speakers who only care about the English language, and its also a fine answer for the original question. But in a more general context, one cannot always accept the cultural bias of assuming "all non-ascii is bad." For contexts where non-ascii is used, but occasionally needs to be stripped out, the positive assertion of Unicode is a better fit.

A good indication that zero-width, non printing characters are embedded in a string is when the string's "length" property is positive (nonzero), but looks like (i.e. prints as) an empty string. For example, I had this showing up in the Chrome debugger, for a variable named "textContent":

> textContent
""
> textContent.length
7

This prompted me to want to see what was in that string.

> encodeURI(textContent)
"%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B%E2%80%8B"

This sequence of bytes seems to be in the family of some Unicode characters that get inserted by word processors into documents, and then find their way into data fields. Most commonly, these symbols occur at the end of a document. The zero-width-space "%E2%80%8B" might be inserted by CK-Editor (CKEditor).

encodeURI()  UTF-8     Unicode  html     Meaning
-----------  --------  -------  -------  -------------------
"%E2%80%8B"  EC 80 8B  U 200B   &#8203;  zero-width-space
"%E2%80%8E"  EC 80 8E  U 200E   &#8206;  left-to-right-mark
"%E2%80%8F"  EC 80 8F  U 200F   &#8207;  right-to-left-mark

Some references on those:

http://www.fileformat.info/info/unicode/char/200B/index.htm

https://en.wikipedia.org/wiki/Left-to-right_mark

Note that although the encoding of the embedded character is UTF-8, the encoding in the regular expression is not. Although the character is embedded in the string as three bytes (in my case) of UTF-8, the instructions in the regular expression must use the two-byte Unicode. In fact, UTF-8 can be up to four bytes long; it is less compact than Unicode because it uses the high bit (or bits) to escape the standard ascii encoding. That's explained here:

https://en.wikipedia.org/wiki/UTF-8

creating json object with variables

var formValues = {
    firstName: $('#firstName').val(),
    lastName: $('#lastName').val(),
    phone: $('#phoneNumber').val(),
    address: $('#address').val()
};

Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.

Store multiple values in single key in json

{
    "success": true,
    "data": {
        "BLR": {
            "origin": "JAI",
            "destination": "BLR",
            "price": 127,
            "transfers": 0,
            "airline": "LB",
            "flight_number": 655,
            "departure_at": "2017-06-03T18:20:00Z",
            "return_at": "2017-06-07T08:30:00Z",
            "expires_at": "2017-03-05T08:40:31Z"
        }
    }
};

How to copy std::string into std::vector<char>?

std::vector has a constructor that takes two iterators. You can use that:

std::string str = "hello";
std::vector<char> data(str.begin(), str.end());

If you already have a vector and want to add the characters at the end, you need a back inserter:

std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));

what is Promotional and Feature graphic in Android Market/Play Store?

I found this nice write-up that clears it up pretty nicely:

The different graphic assets we request are used to highlight and promote your application in Android Market, and possibly other Google-owned properties. If you’d like to restrict the marketing of your app to just Android Market, you have the option of opting-out of marketing by selecting the "Marketing Opt-Out" in the Developer Console.

Screenshots (Required):
We require 2 screenshots.
Use: Displayed on the details page for your application in Android Market.
You may upload up to 8 screenshots.
Specs: 320w x 480h, 480w x 800h, or 480w x 854h; 24 bit PNG or JPEG (no alpha) Full bleed, no border in art.
Tips:
Landscape thumbnails are cropped, but we preserve the image’s full size and aspect ratio if the user opens it up on market client.
High Resolution Application Icon (Required):
Use: In various locations in Android Market.
Does not replace your launcher icon.
Specs: 512x512, 32-bit PNG with alpha; Max size of 1024KB.
Tips:
This does not replace your launcher icon, but should be a higher-fidelity, higher-resolution version of your application icon.
Same safe-frame as current launcher guidelines, just scaled up:
Full Asset: 512 x 512 px.
Circle or non-square icons: 426 x 426 px, centered within the PNG.
Square Icons: 398 x 398 px.
Drop shadow: black, 75% opaque, 90 degrees down, distance of 14px, size of 36px.
Tweak as necessary to fit icon style (e.g., Google Maps icon has a drop shadow of varying height).
Promotional Graphic (Optional):
Use: In various locations in Android Market.
Specs: 180w x 120h, 24 bit PNG or JPEG (no alpha), Full bleed, no border in art.
Feature Graphic (Optional):
Use: The featured section in Android Market. Will be downsized to mini or micro.
Specs: 1024w x 500h, 24 bit PNG or JPEG (no alpha) with no transparency
Tips:
Use a safe frame of 924x400 (50 pixel of safe padding on each side). All the important content of the graphic should be within this safe frame. Pixels outside of this safe frame may be cropped for stylistic purposes.
If incorporating text, use large font sizes, and keep the graphic simple, as this graphic may be scaled down from its original size.
This graphic may be displayed alone without the app icon.
Video Link (Optional):
Specs: Enter the URL to a YouTube video showcasing your app.
Tip:
Short videos (30 seconds - 2 minutes) highlighting the top features of your app work best.

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Since it's not possible to post code blocks into comments here's the POM template I am using in projects requiring JUnit 5. This allows to build and "Run as JUnit Test" in Eclipse and building the project with plain Maven.

<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>group</groupId>
    <artifactId>project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>project name</name>

    <dependencyManagement>
      <dependencies>
        <dependency>
        <groupId>org.junit</groupId>
        <artifactId>junit-bom</artifactId>
        <version>5.3.1</version>
        <type>pom</type>
        <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>

    <dependencies>
      <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <scope>test</scope>
      </dependency>

      <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-launcher</artifactId>
        <scope>test</scope>
      </dependency>

      <dependency>
        <!-- only required when using parameterized tests -->
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-params</artifactId>
        <scope>test</scope>
      </dependency>
    </dependencies>
</project>

You can see that now you only have to update the version in one place if you want to update JUnit. Also the platform version number does not need to appear (in a compatible version) anywhere in your POM, it's automatically managed via the junit-bom import.

How to change resolution (DPI) of an image?

This article talks about modifying the EXIF data without the re-saving/re-compressing (and thus loss of information -- it actually uses a "trick"; there may be more direct libraries) required by the SetResolution approach. This was found on a quick google search, but I wanted to point out that all you need to do is modify the stored EXIF data.

Also: .NET lib for EXIF modification and another SO question. Google owns when you know good search terms.

AVD Manager - Cannot Create Android Virtual Device

I had trouble creating an AVD.

Either:

  • re-start eclipse after installing SDK versions from the SDK manager, or
  • you should run the "AVD Manager.exe" outside of Eclipse

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

You have enabled CORS and enabled Access-Control-Allow-Origin : * in the server.If still you get GET method working and POST method is not working then it might be because of the problem of Content-Type and data problem.

First AngularJS transmits data using Content-Type: application/json which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded

Example :-

        $scope.formLoginPost = function () {
            $http({
                url: url,
                method: "POST",
                data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(function (response) {
                // success
                console.log('success');
                console.log("then : " + JSON.stringify(response));
            }, function (response) { // optional
                // failed
                console.log('failed');
                console.log(JSON.stringify(response));
            });
        };

Note : I am using $.params to serialize the data to use Content-Type: x-www-form-urlencoded. Alternatively you can use the following javascript function

function params(obj){
    var str = "";
    for (var key in obj) {
        if (str != "") {
            str += "&";
        }
        str += key + "=" + encodeURIComponent(obj[key]);
    }
    return str;
}

and use params({ 'username': $scope.username, 'Password': $scope.Password }) to serialize it as the Content-Type: x-www-form-urlencoded requests only gets the POST data in username=john&Password=12345 form.

Adding headers when using httpClient.GetAsync

Following the greenhoorn's answer, you can use "Extensions" like this:

  public static class HttpClientExtensions
    {
        public static HttpClient AddTokenToHeader(this HttpClient cl, string token)
        {
            //int timeoutSec = 90;
            //cl.Timeout = new TimeSpan(0, 0, timeoutSec);
            string contentType = "application/json";
            cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
            cl.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token));
            var userAgent = "d-fens HttpClient";
            cl.DefaultRequestHeaders.Add("User-Agent", userAgent);
            return cl;
        }
    }

And use:

string _tokenUpdated = "TOKEN";
HttpClient _client;
_client.AddTokenToHeader(_tokenUpdated).GetAsync("/api/values")

Convert xlsx to csv in Linux with command line

If .xlsx file has many sheets, -s flag can be used to get the sheet you want. For example:

xlsx2csv "my_file.xlsx" -s 2 second_sheet.csv

second_sheet.csv would contain data of 2nd sheet in my_file.xlsx.

Twitter bootstrap collapse: change display of toggle button

I guess you could look inside your downloaded code where exactly there is a + sign (but this might not be very easy).

What I'd do? I'd find the class/id of the DOM elements that contain the + sign (suppose it's ".collapsible", and with Javascript (actually jQuery):

<script>
     $(document).ready(function() {
         var content=$(".collapsible").html().replace("+", "-");
         $(".collapsible").html(content));
     });
</script>

edit Alright... Sorry I haven't looked at the bootstrap code... but I guess it works with something like slideToggle, or slideDown and slideUp... Imagine it's a slideToggle for the elements of class .collapsible, which reveal contents of some .info elements. Then:

         $(".collapsible").click(function() { 
             var content=$(".collapsible").html();
             if $(this).next().css("display") === "none") { 
                 $(".collapsible").html(content.replace("+", "-"));
             }
             else $(".collapsible").html(content.replace("-", "+"));
         });

This seems like the opposite thing to do, but since the actual animation runs in parallel, you will check css before animation, and that's why you need to check if it's visible (which will mean it will be hidden once the animation is complete) and then set the corresponding + or -.

How can I select all elements without a given class in jQuery?

You could use this to pick all li elements without class:

$('ul#list li:not([class])')

Keras, how do I predict after I trained a model?

model.predict() expects the first parameter to be a numpy array. You supply a list, which does not have the shape attribute a numpy array has.

Otherwise your code looks fine, except that you are doing nothing with the prediction. Make sure you store it in a variable, for example like this:

prediction = model.predict(np.array(tk.texts_to_sequences(text)))
print(prediction)

How to install grunt and how to build script with it

To setup GruntJS build here is the steps:

  1. Make sure you have setup your package.json or setup new one:

    npm init
    
  2. Install Grunt CLI as global:

    npm install -g grunt-cli
    
  3. Install Grunt in your local project:

    npm install grunt --save-dev
    
  4. Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:

    npm install grunt-contrib-concat --save-dev
    
  5. Now you need to setup your Gruntfile.js which will describe your build process. For this sample I just combine two JS files file1.js and file2.js in the js folder and generate app.js:

    module.exports = function(grunt) {
    
        // Project configuration.
        grunt.initConfig({
            concat: {
                "options": { "separator": ";" },
                "build": {
                    "src": ["js/file1.js", "js/file2.js"],
                    "dest": "js/app.js"
                }
            }
        });
    
        // Load required modules
        grunt.loadNpmTasks('grunt-contrib-concat');
    
        // Task definitions
        grunt.registerTask('default', ['concat']);
    };
    
  6. Now you'll be ready to run your build process by following command:

    grunt
    

I hope this give you an idea how to work with GruntJS build.

NOTE:

You can use grunt-init for creating Gruntfile.js if you want wizard-based creation instead of raw coding for step 5.

To do so, please follow these steps:

npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile

For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile to %USERPROFILE%\.grunt-init\. PowerShell will recognize the ~ correctly.

What does the clearfix class do in css?

When an element, such as a div is floated, its parent container no longer considers its height, i.e.

<div id="main">
  <div id="child" style="float:left;height:40px;"> Hi</div>
</div>

The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.

So the clearfix class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.

Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.

Can read more here

http://www.webtoolkit.info/css-clearfix.html

Can I apply multiple background colors with CSS3?

You can use as many colors and images as you desire.

Please note that the priority with which the background images are rendered is FILO, the first specified image is on the top layer, the last specified image is on the bottom layer (see the snippet).

_x000D_
_x000D_
#composition {_x000D_
    width: 400px;_x000D_
    height: 200px;_x000D_
    background-image:_x000D_
        linear-gradient(to right, #FF0000, #FF0000), /* gradient 1 as solid color */_x000D_
        linear-gradient(to right, #00FF00, #00FF00), /* gradient 2 as solid color */_x000D_
        linear-gradient(to right, #0000FF, #0000FF), /* gradient 3 as solid color */_x000D_
        url('http://lorempixel.com/400/200/'); /* image */_x000D_
    background-repeat: no-repeat; /* same as no-repeat, no-repeat, no-repeat */_x000D_
    background-position:_x000D_
        0 0, /* gradient 1 */_x000D_
        20px 0, /* gradient 2 */_x000D_
        40px 0, /* gradient 3 */_x000D_
        0 0; /* image position */_x000D_
    background-size:_x000D_
        30px 30px,_x000D_
        30px 30px,_x000D_
        30px 30px,_x000D_
        100% 100%;_x000D_
}
_x000D_
<div id="composition">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

How do you print in a Go test using the "testing" package?

For example,

package verbose

import (
    "fmt"
    "testing"
)

func TestPrintSomething(t *testing.T) {
    fmt.Println("Say hi")
    t.Log("Say bye")
}

go test -v
=== RUN TestPrintSomething
Say hi
--- PASS: TestPrintSomething (0.00 seconds)
    v_test.go:10: Say bye
PASS
ok      so/v    0.002s

Command go

Description of testing flags

-v
Verbose output: log all tests as they are run. Also print all
text from Log and Logf calls even if the test succeeds.

Package testing

func (*T) Log

func (c *T) Log(args ...interface{})

Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.

How to return an array from a function?

how can i return a array in a c++ method and how must i declare it? int[] test(void); ??

This sounds like a simple question, but in C++ you have quite a few options. Firstly, you should prefer...

  • std::vector<>, which grows dynamically to however many elements you encounter at runtime, or

  • std::array<> (introduced with C++11), which always stores a number of elements specified at compile time,

...as they manage memory for you, ensuring correct behaviour and simplifying things considerably:

std::vector<int> fn()
{
    std::vector<int> x;
    x.push_back(10);
    return x;
}

std::array<int, 2> fn2()  // C++11
{
    return {3, 4};
}

void caller()
{
    std::vector<int> a = fn();
    const std::vector<int>& b = fn(); // extend lifetime but read-only
                                      // b valid until scope exit/return

    std::array<int, 2> c = fn2();
    const std::array<int, 2>& d = fn2();
}

The practice of creating a const reference to the returned data can sometimes avoid a copy, but normally you can just rely on Return Value Optimisation, or - for vector but not array - move semantics (introduced with C++11).

If you really want to use an inbuilt array (as distinct from the Standard library class called array mentioned above), one way is for the caller to reserve space and tell the function to use it:

void fn(int x[], int n)
{
    for (int i = 0; i < n; ++i)
        x[i] = n;
}

void caller()
{
    // local space on the stack - destroyed when caller() returns
    int x[10];
    fn(x, sizeof x / sizeof x[0]);

    // or, use the heap, lives until delete[](p) called...
    int* p = new int[10];
    fn(p, 10);
}

Another option is to wrap the array in a structure, which - unlike raw arrays - are legal to return by value from a function:

struct X
{
    int x[10];
};

X fn()
{
    X x;
    x.x[0] = 10;
    // ...
    return x;
}

void caller()
{
    X x = fn();
}

Starting with the above, if you're stuck using C++03 you might want to generalise it into something closer to the C++11 std::array:

template <typename T, size_t N>
struct array
{
    T& operator[](size_t n) { return x[n]; }
    const T& operator[](size_t n) const { return x[n]; }
    size_t size() const { return N; }
    // iterators, constructors etc....
  private:
    T x[N];
};

Another option is to have the called function allocate memory on the heap:

int* fn()
{
    int* p = new int[2];
    p[0] = 0;
    p[1] = 1;
    return p;
}

void caller()
{
    int* p = fn();
    // use p...
    delete[] p;
}

To help simplify the management of heap objects, many C++ programmers use "smart pointers" that ensure deletion when the pointer(s) to the object leave their scopes. With C++11:

std::shared_ptr<int> p(new int[2], [](int* p) { delete[] p; } );
std::unique_ptr<int[]> p(new int[3]);

If you're stuck on C++03, the best option is to see if the boost library is available on your machine: it provides boost::shared_array.

Yet another option is to have some static memory reserved by fn(), though this is NOT THREAD SAFE, and means each call to fn() overwrites the data seen by anyone keeping pointers from previous calls. That said, it can be convenient (and fast) for simple single-threaded code.

int* fn(int n)
{
    static int x[2];  // clobbered by each call to fn()
    x[0] = n;
    x[1] = n + 1;
    return x;  // every call to fn() returns a pointer to the same static x memory
}

void caller()
{
    int* p = fn(3);
    // use p, hoping no other thread calls fn() meanwhile and clobbers the values...
    // no clean up necessary...
}

Can I automatically increment the file build version when using Visual Studio?

open up the AssemblyInfo.cs file and change

// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

to

[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]

you can do this in IDE by going to project -> properties -> assembly information

This however will only allow you to auto increment the Assembly version and will give you the

Assembly File Version: A wildcard ("*") is not allowed in this field

message box if you try place a * in the file version field.

So just open up the assemblyinfo.cs and do it manually.

How can I format the output of a bash command in neat columns

Try

xargs -n2  printf "%-20s%s\n"

or even

xargs printf "%-20s%s\n"

if input is not very large.

Angular 2: How to call a function after get a response from subscribe http.post

Update your get_categories() method to return the total (wrapped in an observable):

// Note that .subscribe() is gone and I've added a return.
get_categories(number) {
  return this.http.post( url, body, {headers: headers, withCredentials:true})
    .map(response => response.json());
}

In search_categories(), you can subscribe the observable returned by get_categories() (or you could keep transforming it by chaining more RxJS operators):

// send_categories() is now called after get_categories().
search_categories() {
  this.get_categories(1)
    // The .subscribe() method accepts 3 callbacks
    .subscribe(
      // The 1st callback handles the data emitted by the observable.
      // In your case, it's the JSON data extracted from the response.
      // That's where you'll find your total property.
      (jsonData) => {
        this.send_categories(jsonData.total);
      },
      // The 2nd callback handles errors.
      (err) => console.error(err),
      // The 3rd callback handles the "complete" event.
      () => console.log("observable complete")
    );
}

Note that you only subscribe ONCE, at the end.

Like I said in the comments, the .subscribe() method of any observable accepts 3 callbacks like this:

obs.subscribe(
  nextCallback,
  errorCallback,
  completeCallback
);

They must be passed in this order. You don't have to pass all three. Many times only the nextCallback is implemented:

obs.subscribe(nextCallback);

equivalent of rm and mv in windows .cmd

If you want to see a more detailed discussion of differences for the commands, see the Details about Differences section, below.

From the LeMoDa.net website1 (archived), specifically the Windows and Unix command line equivalents page (archived), I found the following2. There's a better/more complete table in the next edit.

Windows command     Unix command
rmdir               rmdir
rmdir /s            rm -r
move                mv

I'm interested to hear from @Dave and @javadba to hear how equivalent the commands are - how the "behavior and capabilities" compare, whether quite similar or "woefully NOT equivalent".

All I found out was that when I used it to try and recursively remove a directory and its constituent files and subdirectories, e.g.

(Windows cmd)>rmdir /s C:\my\dirwithsubdirs\

gave me a standard Windows-knows-better-than-you-do-are-you-sure message and prompt

dirwithsubdirs, Are you sure (Y/N)?

and that when I typed Y, the result was that my top directory and its constituent files and subdirectories went away.


Edit

I'm looking back at this after finding this answer. I retried each of the commands, and I'd change the table a little bit.

Windows command     Unix command
rmdir               rmdir
rmdir /s /q         rm -r
rmdir /s /q         rm -rf
rmdir /s            rm -ri
move                mv
del <file>          rm <file>

If you want the equivalent for

rm -rf

you can use

rmdir /s /q

or, as the author of the answer I sourced described,

But there is another "old school" way to do it that was used back in the day when commands did not have options to suppress confirmation messages. Simply ECHO the needed response and pipe the value into the command.

echo y | rmdir /s


Details about Differences

I tested each of the commands using Windows CMD and Cygwin (with its bash).

Before each test, I made the following setup.

Windows CMD

>mkdir this_directory
>echo some text stuff > this_directory/some.txt
>mkdir this_empty_directory

Cygwin bash

$ mkdir this_directory
$ echo "some text stuff" > this_directory/some.txt
$ mkdir this_empty_directory

That resulted in the following file structure for both.

base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

Here are the results. Note that I'll not mark each as CMD or bash; the CMD will have a > in front, and the bash will have a $ in front.

RMDIR

>rmdir this_directory
The directory is not empty.

>tree /a /f .
Folder PATH listing for volume Windows
Volume serial number is ¦¦¦¦¦¦¦¦ ¦¦¦¦:¦¦¦¦
base
+---this_directory
|       some.txt
|
\---this_empty_directory

> rmdir this_empty_directory

>tree /a /f .
base
\---this_directory
        some.txt
$ rmdir this_directory
rmdir: failed to remove 'this_directory': Directory not empty

$ tree --charset=ascii
base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

2 directories, 1 file

$ rmdir this_empty_directory

$ tree --charset=ascii
base
`-- this_directory
    `-- some.txt

RMDIR /S /Q and RM -R ; RM -RF

>rmdir /s /q this_directory

>tree /a /f
base
\---this_empty_directory

>rmdir /s /q this_empty_directory

>tree /a /f
base
No subfolders exist
$ rm -r this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -r this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files
$ rm -rf this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -rf this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files

RMDIR /S AND RM -RI Here, we have a bit of a difference, but they're pretty close.

>rmdir /s this_directory
this_directory, Are you sure (Y/N)? y

>tree /a /f
base
\---this_empty_directory

>rmdir /s this_empty_directory
this_empty_directory, Are you sure (Y/N)? y

>tree /a /f
base
No subfolders exist
$ rm -ri this_directory
rm: descend into directory 'this_directory'? y
rm: remove regular file 'this_directory/some.txt'? y
rm: remove directory 'this_directory'? y

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -ri this_empty_directory
rm: remove directory 'this_empty_directory'? y

$ tree --charset=ascii
base
0 directories, 0 files

I'M HOPING TO GET A MORE THOROUGH MOVE AND MV TEST


Notes

  1. I know almost nothing about the LeMoDa website, other than the fact that the info is

Copyright © Ben Bullock 2009-2018. All rights reserved.

(archived copyright notice)

and that there seem to be a bunch of useful programming tips along with some humour (yes, the British spelling) and information on how to fix Japanese toilets. I also found some stuff talking about the "Ibaraki Report", but I don't know if that is the website.

I think I shall go there more often; it's quite useful. Props to Ben Bullock, whose email is on his page. If he wants me to remove this info, I will.

I will include the disclaimer (archived) from the site:

Disclaimer Please read the following disclaimer before using any of the computer program code on this site.

There Is No Warranty For The Program, To The Extent Permitted By Applicable Law. Except When Otherwise Stated In Writing The Copyright Holders And/Or Other Parties Provide The Program “As Is” Without Warranty Of Any Kind, Either Expressed Or Implied, Including, But Not Limited To, The Implied Warranties Of Merchantability And Fitness For A Particular Purpose. The Entire Risk As To The Quality And Performance Of The Program Is With You. Should The Program Prove Defective, You Assume The Cost Of All Necessary Servicing, Repair Or Correction.

In No Event Unless Required By Applicable Law Or Agreed To In Writing Will Any Copyright Holder, Or Any Other Party Who Modifies And/Or Conveys The Program As Permitted Above, Be Liable To You For Damages, Including Any General, Special, Incidental Or Consequential Damages Arising Out Of The Use Or Inability To Use The Program (Including But Not Limited To Loss Of Data Or Data Being Rendered Inaccurate Or Losses Sustained By You Or Third Parties Or A Failure Of The Program To Operate With Any Other Programs), Even If Such Holder Or Other Party Has Been Advised Of The Possibility Of Such Damages.


  1. Actually, I found the information with a Google search for "cmd equivalent of rm"

https://www.google.com/search?q=cmd+equivalent+of+rm

The information I'm sharing came up first.

EC2 Instance Cloning

There is no explicit Clone button. Basically what you do is create an image, or snapshot of an existing EC2 instance, and then spin up a new instance using that snapshot.

First create an image from an existing EC2 instance.

enter image description here


Check your snapshots list to see if the process is completed. This usually takes around 20 minutes depending on how large your instance drive is.

enter image description here


Then, you need to create a new instance and use that image as the AMI.

enter image description here

enter image description here

How to adjust the size of y axis labels only in R?

ucfagls is right, providing you use the plot() command. If not, please give us more detail.

In any case, you can control every axis seperately by using the axis() command and the xaxt/yaxt options in plot(). Using the data of ucfagls, this becomes :

plot(Y ~ X, data=foo,yaxt="n")
axis(2,cex.axis=2)

the option yaxt="n" is necessary to avoid that the plot command plots the y-axis without changing. For the x-axis, this works exactly the same :

plot(Y ~ X, data=foo,xaxt="n")
axis(1,cex.axis=2)

See also the help files ?par and ?axis


Edit : as it is for a barplot, look at the options cex.axis and cex.names :

tN <- table(sample(letters[1:5],100,replace=T,p=c(0.2,0.1,0.3,0.2,0.2)))

op <- par(mfrow=c(1,2))
barplot(tN, col=rainbow(5),cex.axis=0.5) # for the Y-axis
barplot(tN, col=rainbow(5),cex.names=0.5) # for the X-axis
par(op)

alt text

How to dynamically add a class to manual class names?

A simple possible syntax will be:

<div className={`wrapper searchDiv ${this.state.something}`}>

Refresh or force redraw the fragment

This worked for me from within Fragment:

Fragment frg = null;
Class fragmentClass;
fragmentClass = MainFragment.class;

try {
    frg = (android.support.v4.app.Fragment)     
    fragmentClass.newInstance();
} catch(Exception ex) {
    ex.printStackTrace();
}

getFragmentManager()
    .beginTransaction()
    .replace(R.id.flContent, frg)
    .commit();

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

Update statement with inner join on Oracle

UPDATE IP_ADMISSION_REQUEST ip1
SET IP1.WRIST_BAND_PRINT_STATUS=0
WHERE IP1.IP_ADM_REQ_ID        =
  (SELECT IP.IP_ADM_REQ_ID
  FROM IP_ADMISSION_REQUEST ip
  INNER JOIN VISIT v
  ON ip.ip_visit_id=v.visit_id
  AND v.pat_id     =3702
  ); `enter code here`

Exception: There is already an open DataReader associated with this Connection which must be closed first

You are trying to to an Insert (with ExecuteNonQuery()) on a SQL connection that is used by this reader already:

while (myReader.Read())

Either read all the values in a list first, close the reader and then do the insert, or use a new SQL connection.

Generic deep diff between two objects

const diff = require("deep-object-diff").diff;
let differences = diff(obj2, obj1);

There is an npm module with over 500k weekly downloads: https://www.npmjs.com/package/deep-object-diff

I like the object like representation of the differences - especially it is easy to see the structure, when it is formated.

const diff = require("deep-object-diff").diff;

const lhs = {
  foo: {
    bar: {
      a: ['a', 'b'],
      b: 2,
      c: ['x', 'y'],
      e: 100 // deleted
    }
  },
  buzz: 'world'
};

const rhs = {
  foo: {
    bar: {
      a: ['a'], // index 1 ('b')  deleted
      b: 2, // unchanged
      c: ['x', 'y', 'z'], // 'z' added
      d: 'Hello, world!' // added
    }
  },
  buzz: 'fizz' // updated
};

console.log(diff(lhs, rhs)); // =>
/*
{
  foo: {
    bar: {
      a: {
        '1': undefined
      },
      c: {
        '2': 'z'
      },
      d: 'Hello, world!',
      e: undefined
    }
  },
  buzz: 'fizz'
}
*/

What is a "thread" (really)?

A thread is nothing more than a memory context (or how Tanenbaum better puts it, resource grouping) with execution rules. It's a software construct. The CPU has no idea what a thread is (some exceptions here, some processors have hardware threads), it just executes instructions.

The kernel introduces the thread and process concept to manage the memory and instructions order in a meaningful way.

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

Concept behind putting wait(),notify() methods in Object class

wait and notify operations work on implicit lock, and implicit lock is something that make inter thread communication possible. And all objects have got their own copy of implicit object. so keeping wait and notify where implicit lock lives is a good decision.

Alternatively wait and notify could have lived in Thread class as well. than instead of wait() we may have to call Thread.getCurrentThread().wait(), same with notify. For wait and notify operations there are two required parameters, one is thread who will be waiting or notifying other is implicit lock of the object . both are these could be available in Object as well as thread class as well. wait() method in Thread class would have done the same as it is doing in Object class, transition current thread to waiting state wait on the lock it had last acquired.

So yes i think wait and notify could have been there in Thread class as well but its more like a design decision to keep it in object class.

What is the best way to seed a database in Rails?

Updating since these answers are slightly outdated (although some still apply).

Simple feature added in rails 2.3.4, db/seeds.rb

Provides a new rake task

rake db:seed

Good for populating common static records like states, countries, etc...

http://railscasts.com/episodes/179-seed-data

*Note that you can use fixtures if you had already created them to also populate with the db:seed task by putting the following in your seeds.rb file (from the railscast episode):

require 'active_record/fixtures'
Fixtures.create_fixtures("#{Rails.root}/test/fixtures", "operating_systems")

For Rails 3.x use 'ActiveRecord::Fixtures' instead of 'Fixtures' constant

require 'active_record/fixtures'
ActiveRecord::Fixtures.create_fixtures("#{Rails.root}/test/fixtures", "fixtures_file_name")

How do I detect if software keyboard is visible on Android Device or not?

I did this as follows, but its relevet only if your goal is to close / open the keyboad.

close example: (checking if keyboard already closed, if not - closing)

imm.showSoftInput(etSearch, InputMethodManager.HIDE_IMPLICIT_ONLY, new ResultReceiver(null) {
                    @Override
                    protected void onReceiveResult(int resultCode, Bundle resultData) {
                        super.onReceiveResult(resultCode, resultData);
                        if (resultCode != InputMethodManager.RESULT_UNCHANGED_HIDDEN)
                            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                    }
                });

Looping through array and removing items, without breaking for loop

There are lot of wonderful answers on this thread already. However I wanted to share my experience when I tried to solve "remove nth element from array" in ES5 context.

JavaScript arrays have different methods to add/remove elements from start or end. These are:

arr.push(ele) - To add element(s) at the end of the array 
arr.unshift(ele) - To add element(s) at the beginning of the array
arr.pop() - To remove last element from the array 
arr.shift() - To remove first element from the array 

Essentially none of the above methods can be used directly to remove nth element from the array.

A fact worth noting is that this is in contrast with java iterator's using which it is possible to remove nth element for a collection while iterating.

This basically leaves us with only one array method Array.splice to perform removal of nth element (there are other things you could do with these methods as well, but in the context of this question I am focusing on removal of elements):

Array.splice(index,1) - removes the element at the index 

Here is the code copied from original answer (with comments):

_x000D_
_x000D_
var arr = ["one", "two", "three", "four"];_x000D_
var i = arr.length; //initialize counter to array length _x000D_
_x000D_
while (i--) //decrement counter else it would run into IndexOutBounds exception_x000D_
{_x000D_
  if (arr[i] === "four" || arr[i] === "two") {_x000D_
    //splice modifies the original array_x000D_
    arr.splice(i, 1); //never runs into IndexOutBounds exception _x000D_
    console.log("Element removed. arr: ");_x000D_
_x000D_
  } else {_x000D_
    console.log("Element not removed. arr: ");_x000D_
  }_x000D_
  console.log(arr);_x000D_
}
_x000D_
_x000D_
_x000D_

Another noteworthy method is Array.slice. However the return type of this method is the removed elements. Also this doesn't modify original array. Modified code snippet as follows:

_x000D_
_x000D_
var arr = ["one", "two", "three", "four"];_x000D_
var i = arr.length; //initialize counter to array length _x000D_
_x000D_
while (i--) //decrement counter _x000D_
{_x000D_
  if (arr[i] === "four" || arr[i] === "two") {_x000D_
    console.log("Element removed. arr: ");_x000D_
    console.log(arr.slice(i, i + 1));_x000D_
    console.log("Original array: ");_x000D_
    console.log(arr);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Having said that, we can still use Array.slice to remove nth element as shown below. However it is lot more code (hence inefficient)

_x000D_
_x000D_
var arr = ["one", "two", "three", "four"];_x000D_
var i = arr.length; //initialize counter to array length _x000D_
_x000D_
while (i--) //decrement counter _x000D_
{_x000D_
  if (arr[i] === "four" || arr[i] === "two") {_x000D_
    console.log("Array after removal of ith element: ");_x000D_
    arr = arr.slice(0, i).concat(arr.slice(i + 1));_x000D_
    console.log(arr);_x000D_
  }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

The Array.slice method is extremely important to achieve immutability in functional programming à la redux

Meaning of *& and **& in C++

This *& in theory as well as in practical its possible and called as reference to pointer variable. and it's act like same. This *& combination is used in as function parameter for 'pass by' type defining. unlike ** can also be used for declaring a double pointer variable.
The passing of parameter is divided into pass by value, pass by reference, pass by pointer. there are various answer about "pass by" types available. however the basic we require to understand for this topic is.

pass by reference --> generally operates on already created variable refereed while passing to function e.g fun(int &a);

pass by pointer --> Operates on already initialized 'pointer variable/variable address' passing to function e.g fun(int* a);

auto addControl = [](SomeLabel** label, SomeControl** control) {
    *label = new SomeLabel;
    *control = new SomeControl;
    // few more operation further.
};

addControl(&m_label1,&m_control1);
addControl(&m_label2,&m_control2);
addControl(&m_label3,&m_control3);

in the above example(this is the real life problem i came across) i am trying to init few pointer variable from the lambda function and for that we need to pass it by double pointer, so that comes with d-referencing of pointer for its all usage inside of that lambda + while passing pointer in function which takes double pointer, you need to pass reference to the pointer variable.

so with this same thing reference to the pointer variable, *& this combination helps. in below given way for the same example i have mentioned above.

auto addControl = [](SomeLabel*& label, SomeControl*& control) {
        label = new SomeLabel;
        control = new SomeControl;
        // few more operation further.
    };

addControl(m_label1,m_control1);
addControl(m_label2,m_control2);
addControl(m_label3,m_control3);

so here you can see that you neither require d-referencing nor we require to pass reference to pointer variable while passing in function, as current pass by type is already reference to pointer.

Hope this helps :-)

How to write a file with C in Linux?

You need to write() the read() data into the new file:

ssize_t nrd;
int fd;
int fd1;

fd = open(aa[1], O_RDONLY);
fd1 = open(aa[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,50)) {
    write(fd1,buffer,nrd);
}

close(fd);
close(fd1);

Update: added the proper opens...

Btw, the O_CREAT can be OR'd (O_CREAT | O_WRONLY). You are actually opening too many file handles. Just do the open once.

Check if current directory is a Git repository

Not sure if there is a publicly accessible/documented way to do this (there are some internal git functions which you can use/abuse in the git source itself)

You could do something like;

if ! git ls-files >& /dev/null; then
  echo "not in git"
fi

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

The offending lines are the following:

MaxConnections=90
InitialConnections=80

You can increase the values to allow more connections.

When would you use the different git merge strategies?

As the answers above are not showing all strategy details. For example, some answer is missing the details about the import resolve option and the recursive which has many sub options as ours, theirs, patience, renormalize, etc.

Therefore, I would recommend to visit the official git documentation which explains all the possible features features:

https://git-scm.com/docs/merge-strategies

Can an int be null in Java?

As @Glen mentioned in a comment, you basically have two ways around this:

  • use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
  • Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.

How to read all of Inputstream in Server Socket JAVA

The problem you have is related to TCP streaming nature.

The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.

You need to implement a loop in which you read until the whole message was received. Let me provide an example with DataInputStream instead of BufferedinputStream. Something very simple to give you just an example.

Let's suppose you know beforehand the server is to send 100 Bytes of data.

In client you need to write:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());

    while(!end)
    {
        int bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == 100)
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.

The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:

  • 1 Byte indicating type (For example, it could also be 2 or whatever).
  • 1 Byte (or whatever) for length of message
  • N Bytes for the value (N is indicated in length).

So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.

This is just a suggestion of a possible protocol. You could also get rid of "Type".

So it would be something like:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());
    int bytesRead = 0;

    messageByte[0] = in.readByte();
    messageByte[1] = in.readByte();

    int bytesToRead = messageByte[1];

    while(!end)
    {
        bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == bytesToRead )
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.

import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

class Test
{
    public static void main(String[] args)
    {
        byte[] messageByte = new byte[1000];
        boolean end = false;
        String dataString = "";

        try 
        {
            Socket clientSocket;
            ServerSocket server;

            server = new ServerSocket(30501, 100);
            clientSocket = server.accept();

            DataInputStream in = new DataInputStream(clientSocket.getInputStream());
            int bytesRead = 0;

            messageByte[0] = in.readByte();
            messageByte[1] = in.readByte();
            ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);

            int bytesToRead = byteBuffer.getShort();
            System.out.println("About to read " + bytesToRead + " octets");

            //The following code shows in detail how to read from a TCP socket

            while(!end)
            {
                bytesRead = in.read(messageByte);
                dataString += new String(messageByte, 0, bytesRead);
                if (dataString.length() == bytesToRead )
                {
                    end = true;
                }
            }

            //All the code in the loop can be replaced by these two lines
            //in.readFully(messageByte, 0, bytesToRead);
            //dataString = new String(messageByte, 0, bytesToRead);

            System.out.println("MESSAGE: " + dataString);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

SHA1 vs md5 vs SHA256: which to use for a PHP login?

As Johannes Gorset pointed out, the post by Thomas Ptacek from Matasano Security explains why simple, general-purpose hashing functions such as MD5, SHA1, SHA256 and SHA512 are poor password hashing choices.

Why? They are too fast--you can calculate at least 1,000,000 MD5 hashes a second per core with a modern computer, so brute force is feasible against most passwords people use. And that's much less than a GPU-based cracking server cluster!

Salting without key stretching only means that you cannot precompute the rainbow table, you need to build it ad hoc for that specific salt. But it won't really make things that much harder.

User @Will says:

Everyone is talking about this like they can be hacked over the internet. As already stated, limiting attempts makes it impossible to crack a password over the Internet and has nothing to do with the hash.

They don't need to. Apparently, in the case of LinkedIn they used the common SQL injection vulnerability to get the login DB table and cracked millions of passwords offline.

Then he goes back to the offline attack scenario:

The security really comes into play when the entire database is compromised and a hacker can then perform 100 million password attempts per second against the md5 hash. SHA512 is about 10,000 times slower.

No, SHA512 is not 10000 times slower than MD5--it only takes about twice as much. Crypt/SHA512, on the other hand, is a very different beast that, like its BCrypt counterpart, performs key stretching, producing a very different hash with a random salt built-in and will take anything between 500 and 999999 times as much to compute (stretching is tunable).

SHA512 => aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
Crypt/SHA512 => $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21

So the choice for PHP is either Crypt/Blowfish (BCrypt), Crypt/SHA256 or Crypt/SHA512. Or at least Crypt/MD5 (PHK). See www.php.net/manual/en/function.crypt.php

How to reset AUTO_INCREMENT in MySQL?

Best way is remove the field with AI and add it again with AI, works for all tables

What is the garbage collector in Java?

Automatic garbage collection is a process where the JVM gets rid of or keeps certain data points in memory to ultimately free up space for the running program. Memory is first sent to heap memory, that is where the garbage collector (GC) does its work, then is decided to be terminated or kept. Java assumes that the programmer cannot always be trusted, so it terminates items it thinks it doesn't need.

Formatting a float to 2 decimal places

This is for cases that you want to use interpolated strings. I'm actually posting this because I'm tired of trial and error and eventually scrolling through tons of docs every time I need to format some scalar.

$"{1234.5678:0.00}"        "1234.57"        2 decimal places, notice that value is rounded
$"{1234.5678,10:0.00}"     "   1234.57"     right-aligned
$"{1234.5678,-10:0.00}"    "1234.57   "     left-aligned
$"{1234.5678:0.#####}"     "1234.5678"      5 optional digits after the decimal point
$"{1234.5678:0.00000}"     "1234.56780"     5 forced digits AFTER the decimal point, notice the trailing zero
$"{1234.5678:00000.00}"    "01234.57"       5 forced digits BEFORE the decimal point, notice the leading zero
$"{1234.5612:0}"           "1235"           as integer, notice that value is rounded
$"{1234.5678:F2}"          "1234.57"        standard fixed-point
$"{1234.5678:F5}"          "1234.56780"     5 digits after the decimal point, notice the trailing zero
$"{1234.5678:g2}"          "1.2e+03"        standard general with 2 meaningful digits, notice "e"
$"{1234.5678:G2}"          "1.2E+03"        standard general with 2 meaningful digits, notice "E"
$"{1234.5678:G3}"          "1.23E+03"       standard general with 3 meaningful digits
$"{1234.5678:G5}"          "1234.6"         standard general with 5 meaningful digits
$"{1234.5678:e2}"          "1.23e+003"      standard exponential with 2 digits after the decimal point, notice "e"
$"{1234.5678:E3}"          "1.235E+003"     standard exponential with 3 digits after the decimal point, notice "E"
$"{1234.5678:N2}"          "1,234.57"       standard numeric, notice the comma
$"{1234.5678:C2}"          "$1,234.57"      standard currency, notice the dollar sign
$"{1234.5678:P2}"          "123,456.78 %"   standard percent, notice that value is multiplied by 100
$"{1234.5678:2}"           "2"              :)

Performance Warning

Interpolated strings are slow. In my experience this is the order (fast to slow):

  1. value.ToString(format)+" blah blah"
  2. string.Format("{0:format} blah blah", value)
  3. $"{value:format} blah blah"

How to draw a filled triangle in android canvas?

You need remove path.moveTo after first initial.

Path path = new Path();
path.moveTo(point1_returned.x, point1_returned.y);
path.lineTo(point2_returned.x, point2_returned.y);
path.lineTo(point3_returned.x, point3_returned.y);
path.lineTo(point1_returned.x, point1_returned.y);
path.close();

How to stop a setTimeout loop?

I know this is an old question, I'd like to post my approach anyway. This way you don't have to handle the 0 trick that T. J. Crowder expained.

var keepGoing = true;

function myLoop() {
    // ... Do something ...

    if(keepGoing) {
        setTimeout(myLoop, 1000);
    }
}

function startLoop() {
    keepGoing = true;
    myLoop();
}

function stopLoop() {
    keepGoing = false;
}

what does -zxvf mean in tar -zxvf <filename>?

  • z means (un)z_ip.
  • x means ex_tract files from the archive.
  • v means print the filenames v_erbosely.
  • f means the following argument is a f_ilename.

For more details, see tar's man page.

Inserting a blank table row with a smaller height

You don't need an extra table row to create space inside a table. See this jsFiddle.
(I made the gap light grey in colour, so you can see it, but you can change that to transparent.)

Using a table row just for display purposes is table abuse!

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

Can I add and remove elements of enumeration at runtime in Java

You could try to assign properties to the ENUM you're trying to create and statically contruct it by using a loaded properties file. Big hack, but it works :)

How to join components of a path when you are constructing a URL in Python

How about this: It is Somewhat Efficient & Somewhat Simple. Only need to join '2' parts of url path:

def UrlJoin(a , b):
    a, b = a.strip(), b.strip()
    a = a if a.endswith('/') else a + '/'
    b = b if not b.startswith('/') else b[1:]
    return a + b

OR: More Conventional, but Not as efficient if joining only 2 url parts of a path.

def UrlJoin(*parts):
    return '/'.join([p.strip().strip('/') for p in parts])

Test Cases:

>>> UrlJoin('https://example.com/', '/TestURL_1')
'https://example.com/TestURL_1'

>>> UrlJoin('https://example.com', 'TestURL_2')
'https://example.com/TestURL_2'

Note: I may be splitting hairs here, but it is at least good practice and potentially more readable.

Progress Bar with HTML and CSS

2014 answer: Since 2014 HTML now 5 includes a <progress> element that does not need JavaScript. The percent value moves with the progress using inline content. Tested only in webkit. Hope it helps:

jsFiddle

CSS:

_x000D_
_x000D_
progress {_x000D_
 display:inline-block;_x000D_
 width:190px;_x000D_
 height:20px;_x000D_
 padding:15px 0 0 0;_x000D_
 margin:0;_x000D_
 background:none;_x000D_
 border: 0;_x000D_
 border-radius: 15px;_x000D_
 text-align: left;_x000D_
 position:relative;_x000D_
 font-family: Arial, Helvetica, sans-serif;_x000D_
 font-size: 0.8em;_x000D_
}_x000D_
progress::-webkit-progress-bar {_x000D_
 height:11px;_x000D_
 width:150px;_x000D_
 margin:0 auto;_x000D_
 background-color: #CCC;_x000D_
 border-radius: 15px;_x000D_
 box-shadow:0px 0px 6px #777 inset;_x000D_
}_x000D_
progress::-webkit-progress-value {_x000D_
 display:inline-block;_x000D_
 float:left;_x000D_
 height:11px;_x000D_
 margin:0px -10px 0 0;_x000D_
 background: #F70;_x000D_
 border-radius: 15px;_x000D_
 box-shadow:0px 0px 6px #777 inset;_x000D_
}_x000D_
progress:after {_x000D_
 margin:-26px 0 0 -7px;_x000D_
 padding:0;_x000D_
 display:inline-block;_x000D_
 float:left;_x000D_
 content: attr(value) '%';_x000D_
}
_x000D_
<progress id="progressBar" max="100" value="77"></progress>
_x000D_
_x000D_
_x000D_

Uninstall old versions of Ruby gems

You might need to set GEM_HOME for the cleanup to work. You can check what paths exist for gemfiles by running:

gem env

Take note of the GEM PATHS section.

In my case, for example, with gems installed in my user home:

export GEM_HOME="~/.gem/ruby/2.4.0"
gem cleanup

How to use the CSV MIME-type?

You could try to force the browser to open a "Save As..." dialog by doing something like:

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";

Which should work across most major browsers.

HTML 5: Is it <br>, <br/>, or <br />?

In HTML <br> and in XHTML <br/>.

I will suggest you to use <br/>.

Test credit card numbers for use with PayPal sandbox

It turns out, after messing around with all of the settings in the test business account, that one (or more) of the fraud related settings in the payment receiving preferences / security settings screens were causing the test payments to fail (without any useful error).

Spring Data JPA find by embedded object property

According to me, Spring doesn't handle all the cases with ease. In your case the following should do the trick

Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);  

or

Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);

However, it also depends on the naming convention of fields that you have in your @Embeddable class,

e.g. the following field might not work in any of the styles that mentioned above

private String cRcdDel;

I tried with both the cases (as follows) and it didn't work (it seems like Spring doesn't handle this type of naming conventions(i.e. to many Caps , especially in the beginning - 2nd letter (not sure about if this is the only case though)

Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable); 

or

Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable);

When I renamed column to

private String rcdDel;

my following solutions work fine without any issue:

Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable); 

OR

Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable);

HTML.HiddenFor value set

For setting value in hidden field do in the following way:

@Html.HiddenFor(model => model.title, 
                new { id= "natureOfVisitField", Value = @Model.title})

It will work

Find by key deep in a nested array

I'd like to suggest an amendment to Zach/RegularMike's answer (but don't have the "reputation" to be able to comment!). I found there solution a very useful basis, but suffered in my application because if there are strings within arrays it would recursively call the function for every character in the string (which caused IE11 & Edge browsers to fail with "out of stack space" errors). My simple optimization was to add the same test used in the "object" clause recursive call to the one in the "array" clause:

if (arrayElem instanceof Object || arrayElem instanceof Array) {

Thus my full code (which is now looking for all instances of a particular key, so slightly different to the original requirement) is:

// Get all instances of specified property deep within supplied object
function getPropsInObject(theObject, targetProp) {
    var result = [];
    if (theObject instanceof Array) {
        for (var i = 0; i < theObject.length; i++) {
            var arrayElem = theObject[i];
            if (arrayElem instanceof Object || arrayElem instanceof Array) {
                result = result.concat(getPropsInObject(arrayElem, targetProp));
            }
        }
    } else {
        for (var prop in theObject) {
            var objProp = theObject[prop];
            if (prop == targetProp) {
                return theObject[prop];
            }
            if (objProp instanceof Object || objProp instanceof Array) {
                result = result.concat(getPropsInObject(objProp, targetProp));
            }
        }
    }
    return result;
}

What's the difference between @Component, @Repository & @Service annotations in Spring?

Difference between @Component, @Repository, @Controller & @Service annotations

@Component – generic and can be used across application.
@Service – annotate classes at service layer level.
@Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
@Repository – annotate classes at persistence layer, which will act as database repository.

@Controller = @Component ( Internal Annotation ) + Presentation layer Features
@Service = @Component ( Internal Annotation ) + Service layer Features
@Component = Actual Components ( Beans )
@Repository = @Component ( Internal Annotation ) + Data Layer Features ( use for handling the Domain Beans )

How to compare dates in Java?

tl;dr

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
Boolean isBetween = 
    ( ! today.isBefore( localDate1 ) )  // “not-before” is short for “is-equal-to or later-than”.
    &&
    today.isBefore( localDate3 ) ; 

Or, better, if you add the ThreeTen-Extra library to your project.

LocalDateRange.of(
    LocalDate.of( … ) ,
    LocalDate.of( … )
).contains(
    LocalDate.now()
)

Half-open approach, where beginning is inclusive while ending is exclusive.

Bad Choice of Format

By the way, that is a bad choice of format for a text representation of a date or date-time value. Whenever possible, stick with the standard ISO 8601 formats. ISO 8601 formats are unambiguous, understandable across human cultures, and are easy to parse by machine.

For a date-only value, the standard format is YYYY-MM-DD. Note how this format has the benefit of being chronological when sorted alphabetically.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

Table of all date-time types in Java, both modern and legacy

DateTimeFormatter

As your input strings are non-standard format, we must define a formatting pattern to match.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );

Use that to parse the input strings.

LocalDate start = LocalDate.parse( "22-02-2010" , f );
LocalDate stop = LocalDate.parse( "25-12-2010" , f );

In date-time work, usually best to define a span of time by the Half-Open approach where the beginning is inclusive while the ending is exclusive. So we want to know if today is the same or later than the start and also before the stop. A briefer way of saying “is the same or later than the start” is “not before the start”.

Boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;

See the Answer by gstackoverflow showing the list of comparison methods you can call.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


UPDATE: This “Joda-Time” section below is left intact as history. The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

Joda-Time

Other answers are correct with regard to the bundled java.util.Date and java.util.Calendar classes. But those classes are notoriously troublesome. So here's some example code using the Joda-Time 2.3 library.

If you truly want a date without any time portion and no time zone, then use the LocalDate class in Joda-Time. That class provides methods of comparison including compareTo (used with Java Comparators), isBefore, isAfter, and isEqual.

Inputs…

String string1 = "22-02-2010";
String string2 = "07-04-2010";
String string3 = "25-12-2010";

Define a formatter describing the input strings…

DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );

Use formatter to parse the strings into LocalDate objects…

LocalDate localDate1 = formatter.parseLocalDate( string1 );
LocalDate localDate2 = formatter.parseLocalDate( string2 );
LocalDate localDate3 = formatter.parseLocalDate( string3 );

boolean is1After2 = localDate1.isAfter( localDate2 );
boolean is2Before3 = localDate2.isBefore( localDate3 );

Dump to console…

System.out.println( "Dates: " + localDate1 + " " + localDate2 + " " + localDate3 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );

When run…

Dates: 2010-02-22 2010-04-07 2010-12-25
is1After2 false
is2Before3 true

So see if the second is between the other two (exclusively, meaning not equal to either endpoint)…

boolean is2Between1And3 = ( ( localDate2.isAfter( localDate1 ) ) && ( localDate2.isBefore( localDate3 ) ) );

Working With Spans Of Time

If you are working with spans of time, I suggest exploring in Joda-Time the classes: Duration, Interval, and Period. Methods such as overlap and contains make comparisons easy.

For text representations, look at the ISO 8601 standard’s:

  • duration
    Format: PnYnMnDTnHnMnS
    Example: P3Y6M4DT12H30M5S
    (Means “three years, six months, four days, twelve hours, thirty minutes, and five seconds”)
  • interval
    Format: start/end
    Example: 2007-03-01T13:00:00Z/2008-05-11T15:30:00Z

Joda-Time classes can work with strings in both those formats, both as input (parsing) and output (generating strings).

Joda-Time performs comparisons using the Half-Open approach where the beginning of the span is inclusive while the ending is exclusive. This approach is a wise one for handling spans of time. Search StackOverflow for more info.

How can I find the first occurrence of a sub-string in a python string?

verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n And yet don’t look too good, nor talk too wise:"

enter code here

print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))

Adding +1 to a variable inside a function

Move points into test:

def test():
    points = 0
    addpoint = raw_input ("type ""add"" to add a point")
    ...

or use global statement, but it is bad practice. But better way it move points to parameters:

def test(points=0):
    addpoint = raw_input ("type ""add"" to add a point")
    ...

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

Ignoring NaNs with str.contains

df[df.col.str.contains("foo").fillna(False)]

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

Adding a file, and then deleting it is the kind of operation that's considered an error - and so SVN is telling you. You told it to expect some file data and then don't supply it when you commit, the red lights flash and the sirens go off!

The answer is to undo your add, alternatively commit the file and then use 'svn rm' to remove it from the filesystem and the repo.

anaconda - path environment variable in windows

I want to mention that in some win 10 systems, Microsoft pre-installed a python. Thus, in order to invoke the python installed in the anaconda, you should adjust the order of the environment variable to ensure that the anaconda has a higher priority.

V