Programs & Examples On #High traffic

python pip on Windows - command 'cl.exe' failed

  1. Install Microsoft visual c++ 14.0 build tool.(Windows 7)
  2. create a virtual environment using conda.
  3. Activate the environment and use conda to install the necessary package.

For example: conda install -c conda-forge spacy

What's the difference between deadlock and livelock?

I just planned to share some knowledge.

Deadlocks A set of threads/processes is deadlocked, if each thread/process in the set is waiting for an event that only another process in the set can cause.

The important thing here is another process is also in the same set. that means another process also blocked and no one can proceed.

Deadlocks occur when processes are granted exclusive access to resources.

These four conditions should be satisfied to have a deadlock.

  1. Mutual exclusion condition (Each resource is assigned to 1 process)
  2. Hold and wait condition (Process holding resources and at the same time it can ask other resources).
  3. No preemption condition (Previously granted resources can not forcibly be taken away) #This condition depends on the application
  4. Circular wait condition (Must be a circular chain of 2 or more processes and each is waiting for resource held by the next member of the chain) # It will happen dynamically

If we found these conditions then we can say there may be occurred a situation like a deadlock.

LiveLock

Each thread/process is repeating the same state again and again but doesn't progress further. Something similar to a deadlock since the process can not enter the critical section. However in a deadlock, processes are wait without doing anything but in livelock, the processes are trying to proceed but processes are repeated to the same state again and again.

(In a deadlocked computation there is no possible execution sequence which succeeds. but In a livelocked computation, there are successful computations, but there are one or more execution sequences in which no process enters its critical section.)

Difference from deadlock and livelock

When deadlock happens, No execution will happen. but in livelock, some executions will happen but those executions are not enough to enter the critical section.

An object reference is required to access a non-static member

playSound is a static method meaning it exists when the program is loaded. audioSounds and minTime are SoundManager instance variable, meaning they will exist within an instance of SoundManager. You have not created an instance of SoundManager so audioSounds doesn't exist (or it does but you do not have a reference to a SoundManager object to see that).

To solve your problem you can either make audioSounds static:

public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

so they will be created and may be referenced in the same way that PlaySound will be. Alternatively you can create an instance of SoundManager from within your method:

SoundManager soundManager = new SoundManager();
foreach (AudioSource sound in soundManager.audioSounds) // Loop through List with foreach
{
    if (sourceSound.name != sound.name && sound.time <= soundManager.minTime)
    {
        playsound = true;
    }
}

How to compare arrays in C#?

There is no static Equals method in the Array class, so what you are using is actually Object.Equals, which determines if the two object references point to the same object.

If you want to check if the arrays contains the same items in the same order, you can use the SequenceEquals extension method:

childe1.SequenceEqual(grandFatherNode)

Edit:

To use SequenceEquals with multidimensional arrays, you can use an extension to enumerate them. Here is an extension to enumerate a two dimensional array:

public static IEnumerable<T> Flatten<T>(this T[,] items) {
  for (int i = 0; i < items.GetLength(0); i++)
    for (int j = 0; j < items.GetLength(1); j++)
      yield return items[i, j];
}

Usage:

childe1.Flatten().SequenceEqual(grandFatherNode.Flatten())

If your array has more dimensions than two, you would need an extension that supports that number of dimensions. If the number of dimensions varies, you would need a bit more complex code to loop a variable number of dimensions.

You would of course first make sure that the number of dimensions and the size of the dimensions of the arrays match, before comparing the contents of the arrays.

Edit 2:

Turns out that you can use the OfType<T> method to flatten an array, as RobertS pointed out. Naturally that only works if all the items can actually be cast to the same type, but that is usually the case if you can compare them anyway. Example:

childe1.OfType<Person>().SequenceEqual(grandFatherNode.OfType<Person>())

How to iterate over array of objects in Handlebars?

I meant in the template() call..

You just need to pass the results as an object. So instead of calling

var html = template(data);

do

var html = template({apidata: data});

and use {{#each apidata}} in your template code

demo at http://jsfiddle.net/KPCh4/4/
(removed some leftover if code that crashed)

NameError: uninitialized constant (rails)

In my case, I named a column name type and tried to set its value as UNPREPARED. And I got an error message like this:

Caused by: api_1 | NameError: uninitialized constant UNPREPARED

In rails, column type is reserved:

ActiveRecord::SubclassNotFound: The single-table inheritance mechanism failed to locate the subclass: 'UNPREPARED'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Pl ease rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Food.inheritance_column to use another column for that information

Assigning strings to arrays of characters

What I would use is

char *s = "abcd";

how to get current datetime in SQL?

I always just use NOW():

INSERT INTO table (lastModifiedTime) VALUES (NOW())

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_now

Drawing Isometric game worlds

You could use euclidean distance from the point highest and nearest the viewer, except that is not quite right. It results in spherical sort order. You can straighten that out by looking from further away. Further away the curvature becomes flattened out. So just add say 1000 to each of the x,y and z components to give x',y' and z'. The sort on x'*x'+y'*y'+z'*z'.

how to stop a running script in Matlab

To add on:

you can insert a time check within a loop with intensive or possible deadlock, ie.

:
section_toc_conditionalBreakOff;
:

where within this section

if (toc > timeRequiredToBreakOff)     % time conditional break off
      return;
      % other options may be:                         
      % 1. display intermediate values with pause;
      % 2. exit;                           % in some cases, extreme : kill/ quit matlab
end

What's the most efficient way to check if a record exists in Oracle?

here you can check only y , n if we need to select a name as well that whether this name exists or not.

select name , decode(count(name),0, 'N', 'Y')
  from table
 group by name;

Here when it is Y only then it will return output otherwise it will give null always. Whts ths way to get the records not existing with N like in output we will get Name , N. When name is not existing in table

Check if a string is html or not

/<\/?[^>]*>/.test(str) Only detect whether it contains html tags, may be a xml

How to style UITextview to like Rounded Rect text field?

this code worked well for me:

    [yourTextView.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
    [yourTextView.layer setBorderColor: [[UIColor grayColor] CGColor]];
    [yourTextView.layer setBorderWidth: 1.0];
    [yourTextView.layer setCornerRadius:8.0f];
    [yourTextView.layer setMasksToBounds:YES];

Python vs Cpython

implementation means what language was used to implement Python and not how python Code would be implemented. The advantage of using CPython is the availability of C Run-time as well as easy integration with C/C++.

So CPython was originally implemented using C. There were other forks to the original implementation which enabled Python to lever-edge Java (JYthon) or .NET Runtime (IronPython).

Based on which Implementation you use, library availability might vary, for example Ctypes is not available in Jython, so any library which uses ctypes would not work in Jython. Similarly, if you want to use a Java Class, you cannot directly do so from CPython. You either need a glue (JEPP) or need to use Jython (The Java Implementation of Python)

Dockerfile if else condition with external arguments

Using Bash script and Alpine/Centos

Dockerfile

FROM alpine  #just change this to centos 

ARG MYARG=""
ENV E_MYARG=$MYARG

ADD . /tmp
RUN chmod +x /tmp/script.sh && /tmp/script.sh

script.sh

#!/usr/bin/env sh

if [ -z "$E_MYARG" ]; then
    echo "NO PARAM PASSED"
else
    echo $E_MYARG
fi

Passing arg: docker build -t test --build-arg MYARG="this is a test" .

....
Step 5/5 : RUN chmod +x /tmp/script.sh && /tmp/script.sh
 ---> Running in 10b0e07e33fc
this is a test
Removing intermediate container 10b0e07e33fc
 ---> f6f085ffb284
Successfully built f6f085ffb284

Without arg: docker build -t test .

....
Step 5/5 : RUN chmod +x /tmp/script.sh && /tmp/script.sh
 ---> Running in b89210b0cac0
NO PARAM PASSED
Removing intermediate container b89210b0cac0
....

Is ASCII code 7-bit or 8-bit?

ASCII was indeed originally conceived as a 7-bit code. This was done well before 8-bit bytes became ubiquitous, and even into the 1990s you could find software that assumed it could use the 8th bit of each byte of text for its own purposes ("not 8-bit clean"). Nowadays people think of it as an 8-bit coding in which bytes 0x80 through 0xFF have no defined meaning, but that's a retcon.

There are dozens of text encodings that make use of the 8th bit; they can be classified as ASCII-compatible or not, and fixed- or variable-width. ASCII-compatible means that regardless of context, single bytes with values from 0x00 through 0x7F encode the same characters that they would in ASCII. You don't want to have anything to do with a non-ASCII-compatible text encoding if you can possibly avoid it; naive programs expecting ASCII tend to misinterpret them in catastrophic, often security-breaking fashion. They are so deprecated nowadays that (for instance) HTML5 forbids their use on the public Web, with the unfortunate exception of UTF-16. I'm not going to talk about them any more.

A fixed-width encoding means what it sounds like: all characters are encoded using the same number of bytes. To be ASCII-compatible, a fixed-with encoding must encode all its characters using only one byte, so it can have no more than 256 characters. The most common such encoding nowadays is Windows-1252, an extension of ISO 8859-1.

There's only one variable-width ASCII-compatible encoding worth knowing about nowadays, but it's very important: UTF-8, which packs all of Unicode into an ASCII-compatible encoding. You really want to be using this if you can manage it.

As a final note, "ASCII" nowadays takes its practical definition from Unicode, not its original standard (ANSI X3.4-1968), because historically there were several dozen variations on the ASCII 127-character repertoire -- for instance, some of the punctuation might be replaced with accented letters to facilitate the transmission of French text. Nowadays all of those variations are obsolescent, and when people say "ASCII" they mean that the bytes with value 0x00 through 0x7F encode Unicode codepoints U+0000 through U+007F. This will probably only matter to you if you ever find yourself writing a technical standard.

If you're interested in the history of ASCII and the encodings that preceded it, start with the paper "The Evolution of Character Codes, 1874-1968" (samizdat copy at http://falsedoor.com/doc/ascii_evolution-of-character-codes.pdf) and then chase its references (many of which are not available online and may be hard to find even with access to a university library, I regret to say).

Formatting "yesterday's" date in python

This should do what you want:

import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")

Convert String XML fragment to Document Node in Java

Element node =  DocumentBuilderFactory
    .newInstance()
    .newDocumentBuilder()
    .parse(new ByteArrayInputStream("<node>value</node>".getBytes()))
    .getDocumentElement();

Dealing with commas in a CSV file

There is a library available through nuget for dealing with pretty much any well formed CSV (.net) - CsvHelper

Example to map to a class:

var csv = new CsvReader( textReader );
var records = csv.GetRecords<MyClass>();

Example to read individual fields:

var csv = new CsvReader( textReader );
while( csv.Read() )
{
    var intField = csv.GetField<int>( 0 );
    var stringField = csv.GetField<string>( 1 );
    var boolField = csv.GetField<bool>( "HeaderName" );
}

Letting the client drive the file format:
, is the standard field delimiter, " is the standard value used to escape fields that contain a delimiter, quote, or line ending.

To use (for example) # for fields and ' for escaping:

var csv = new CsvReader( textReader );
csv.Configuration.Delimiter = "#";
csv.Configuration.Quote = ''';
// read the file however meets your needs

More Documentation

How to set multiple commands in one yaml file with Kubernetes?

Here is another way to run multi line commands.

apiVersion: batch/v1
kind: Job
metadata:
  name: multiline
spec:
  template:
    spec:
      containers:
      - command:
        - /bin/bash
        - -exc
        - |
          set +x
          echo "running below scripts"
          if [[ -f "if-condition.sh" ]]; then
            echo "Running if success"
          else
            echo "Running if failed"
          fi
        name: ubuntu
        image: ubuntu
      restartPolicy: Never
  backoffLimit: 1

css absolute position won't work with margin-left:auto margin-right: auto

I've used this trick to center an absolutely positioned element. Though, you have to know the element's width.

.divtagABS {
    width: 100px;
    position: absolute;
    left: 50%;
    margin-left: -50px;
  }

Basically, you use left: 50%, then back it out half of it's width with a negative margin.

How to "perfectly" override a dict?

All you will have to do is

class BatchCollection(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(*args, **kwargs)

OR

class BatchCollection(dict):
    def __init__(self, inpt={}):
        super(BatchCollection, self).__init__(inpt)

A sample usage for my personal use

### EXAMPLE
class BatchCollection(dict):
    def __init__(self, inpt={}):
        dict.__init__(*args, **kwargs)

    def __setitem__(self, key, item):
        if (isinstance(key, tuple) and len(key) == 2
                and isinstance(item, collections.Iterable)):
            # self.__dict__[key] = item
            super(BatchCollection, self).__setitem__(key, item)
        else:
            raise Exception(
                "Valid key should be a tuple (database_name, table_name) "
                "and value should be iterable")

Note: tested only in python3

How to configure welcome file list in web.xml

I simply declared as below in web.xml file and Its working for me :

 <welcome-file-list>
    <welcome-file>/WEB-INF/jsps/index.jsp</welcome-file>
</welcome-file-list>

And NO html/jsp pages present in public directory except static resources(css, js, images). Now I can access my index page with URL like : http://localhost:8080/app/ Its calling /WEB-INF/jsps/index.jsp page. When hosted live in production the final URL looks like https://eisdigital.com/

Jquery button click() function is not working

You need to use a delegated event handler, as the #add elements dynamically appended won't have the click event bound to them. Try this:

$("#buildyourform").on('click', "#add", function() {
    // your code...
});

Also, you can make your HTML strings easier to read by mixing line quotes:

var fieldWrapper = $('<div class="fieldwrapper" name="field' + intId + '" id="field' + intId + '"/>');

Or even supplying the attributes as an object:

var fieldWrapper = $('<div></div>', { 
    'class': 'fieldwrapper',
    'name': 'field' + intId,
    'id': 'field' + intId
});

jQuery input button click event listener

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

Remove char at specific index - python

Use slicing, rebuilding the string minus the index you want to remove:

newstr = oldstr[:4] + oldstr[5:]

How is Pythons glob.glob ordered?

From @Johan La Rooy's solution, sorting the images using sorted(glob.glob('*.png')) does not work for me, the output list is still not ordered by their names.

However, the sorted(glob.glob('*.png'), key=os.path.getmtime) works perfectly.

I am a bit confused how can sorting by their names does not work here.

Thank @Martin Thoma for posting this great question and @Johan La Rooy for the helpful solutions.

extra qualification error in C++

This is because you have the following code:

class JSONDeserializer
{
    Value JSONDeserializer::ParseValue(TDR type, const json_string& valueString);
};

This is not valid C++ but Visual Studio seems to accept it. You need to change it to the following code to be able to compile it with a standard compliant compiler (gcc is more compliant to the standard on this point).

class JSONDeserializer
{
    Value ParseValue(TDR type, const json_string& valueString);
};

The error come from the fact that JSONDeserializer::ParseValue is a qualified name (a name with a namespace qualification), and such a name is forbidden as a method name in a class.

"CSV file does not exist" for a filename with embedded quotes

I am using a Mac. I had the same problem wherein .csv file was in the same folder where the python script was placed, however, Spyder still was unable to locate the file. I changed the file name from capital letters to all small letters and it worked.

PHP XML Extension: Not installed

Had the same problem running PHP 7.2. I had to do the following :

sudo apt-get install php7.2-xml

How does EL empty operator work in JSF?

From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):

1.10 Empty Operator - empty A

The empty operator is a prefix operator that can be used to determine if a value is null or empty.

To evaluate empty A

  • If A is null, return true
  • Otherwise, if A is the empty string, then return true
  • Otherwise, if A is an empty array, then return true
  • Otherwise, if A is an empty Map, return true
  • Otherwise, if A is an empty Collection, return true
  • Otherwise return false

So, considering the interfaces, it works on Collection and Map only. In your case, I think Collection is the best option. Or, if it's a Javabean-like object, then Map. Either way, under the covers, the isEmpty() method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException.

List of standard lengths for database fields

Some probably correct column lengths

                            Min Max

Hostname                    1   255
Domain Name                 4   253
Email Address               7   254
Email Address [1]           3   254
Telephone Number            10  15      
Telephone Number [2]        3   26  
HTTP(S) URL w domain name   11  2083        
URL [3]                     6   2083    
Postal Code [4]             2   11
IP Address (incl ipv6)      7   45
Longitude                   numeric 9,6
Latitude                    numeric 8,6
Money[5]                    numeric 19,4

[1] Allow local domains or TLD-only domains
[2] Allow short numbers like 911 and extensions like 16045551212x12345
[3] Allow local domains, tv:// scheme
[4] http://en.wikipedia.org/wiki/List_of_postal_codes. Use max 12 if storing dash or space
[5] http://stackoverflow.com/questions/224462/storing-money-in-a-decimal-column-what-precision-and-scale

A long rant on personal names

A personal name is either a Polynym (a name with multiple sortable components), a Mononym (a name with only one component), or a Pictonym (a name represented by a picture - this exists due to people like Prince).

A person can have multiple names, playing roles, such as LEGAL, MARITAL, MAIDEN, PREFERRED, SOBRIQUET, PSEUDONYM, etc. You might have business rules, such as "a person can only have one legal name at a time, but multiple pseudonyms at a time".

Some examples:

names: [
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"George",
    middle:"Herman",
    moniker:"Babe",
    surname:"Ruth",
    generation:"JUNIOR"
  },
  {
    type:"MONONYM",
    role:"SOBRIQUET",
    mononym:"The Bambino" /* mononyms can be more than one word, but only one component */
  },
  {
    type:"MONONYM",
    role:"SOBRIQUET",
    mononym:"The Sultan of Swat"
  }
]

or

names: [
  {
    type:"POLYNYM",
    role:"PREFERRED",
    given:"Malcolm",
    surname:"X"
  },
  {
    type:"POLYNYM",
    role:"BIRTH",
    given:"Malcolm",
    surname:"Little"
  },
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"Malik",
    surname:"El-Shabazz"
  }
]

or

names:[
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"Prince",
    middle:"Rogers",
    surname:"Nelson"
  },
  {
    type:"MONONYM",
    role:"SOBRIQUET",
    mononym:"Prince"
  },
  {
    type:"PICTONYM",
    role:"LEGAL",
    url:"http://upload.wikimedia.org/wikipedia/en/thumb/a/af/Prince_logo.svg/130px-Prince_logo.svg.png"
  }
]

or

names:[
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"Juan Pablo",
    surname:"Fernández de Calderón",
    secondarySurname:"García-Iglesias" /* hispanic people often have two surnames. it can be impolite to use the wrong one. Portuguese and Spaniards differ as to which surname is important */
  }
]

Given names, middle names, surnames can be multiple words such as "Billy Bob" Thornton, or Ralph "Vaughn Williams".

R - Markdown avoiding package loading messages

My best solution on R Markdown was to create a code chunk only to load libraries and exclude everything in the chunk.

{r results='asis', echo=FALSE, include=FALSE,}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE)
#formating tables
library(xtable)

#data wrangling
library(dplyr)

#text processing
library(stringi)

The server principal is not able to access the database under the current security context in SQL Server MS 2012

I encountered the same error while using Server Management Objects (SMO) in vb.net (I'm sure it's the same in C#)

Techie Joe's comment on the initial post was a useful warning that in shared hosting a lot of additional things are going on. It took a little time to figure out, but the code below shows how one has to be very specific in the way they access SQL databases. The 'server principal...' error seemed to show up whenever the SMO calls were not precisely specific in the shared hosting environment.

This first section of code was against a local SQL Express server and relied on simple Windows Authentication. All the code used in these samples are based on the SMO tutorial by Robert Kanasz in this Code Project website article:

  Dim conn2 = New ServerConnection()
  conn2.ServerInstance = "<local pc name>\SQLEXPRESS"
  Try
    Dim testConnection As New Server(conn2)
    Debug.WriteLine("Server: " + testConnection.Name)
    Debug.WriteLine("Edition: " + testConnection.Information.Edition)
    Debug.WriteLine(" ")

    For Each db2 As Database In testConnection.Databases
      Debug.Write(db2.Name & " - ")
      For Each fg As FileGroup In db2.FileGroups
        Debug.Write(fg.Name & " - ")
        For Each df As DataFile In fg.Files
          Debug.WriteLine(df.Name + " - " + df.FileName)
        Next
      Next
    Next
    conn2.Disconnect()

  Catch err As Exception
    Debug.WriteLine(err.Message)
  End Try

The code above finds the .mdf files for every database on the local SQLEXPRESS server just fine because authentication is handled by Windows and it is broad across all the databases.

In the following code there are 2 sections iterating for the .mdf files. In this case only the first iteration looking for a filegroup works, and it only finds a single file because the connection is to only a single database in the shared hosting environment.

The second iteration, which is a copy of the iteration that worked above, chokes immediately because the way it is written it tries to access the 1st database in the shared environment, which is not the one to which the User ID/Password apply, so the SQL server returns an authorization error in the form of the 'server principal...' error.

Dim sqlConnection1 As New System.Data.SqlClient.SqlConnection
sqlConnection1.ConnectionString = "connection string with User ID/Password to a specific database in a shared hosting system. This string will likely also include the Data Source and Initial Catalog parameters"
Dim conn1 As New ServerConnection(sqlConnection1)
Try
  Dim testConnection As New Server(conn1)
  Debug.WriteLine("Server: " + testConnection.Name)
  Debug.WriteLine("Edition: " + testConnection.Information.Edition)
  Debug.WriteLine(" ")

  Dim db2 = testConnection.Databases("the name of the database to which the User ID/Password in the connection string applies")
  For Each fg As FileGroup In db2.FileGroups
    Debug.Write(fg.Name & " - ")
    For Each df As DataFile In fg.Files
      Debug.WriteLine(df.Name + " - " + df.FileName)
    Next
  Next

  For Each db3 As Database In testConnection.Databases
    Debug.Write(db3.Name & " - ")
    For Each fg As FileGroup In db3.FileGroups
      Debug.Write(fg.Name & " - ")
      For Each df As DataFile In fg.Files
        Debug.WriteLine(df.Name + " - " + df.FileName)
      Next
    Next
  Next

  conn1.Disconnect()

Catch err As Exception
  Debug.WriteLine(err.Message)
End Try

In that second iteration loop, the code compiles fine, but because SMO wasn't setup to access precisely the correct database with the precise syntax, that attempt fails.

As I'm just learning SMO I thought other newbies might appreciate knowing there's also a more simple explanation for this error - we just coded it wrong.

Adding Table rows Dynamically in Android

public Boolean addArtist(String artistName){

        SQLiteDatabase db= getWritableDatabase();

        ContentValues data=new ContentValues();
        data.put(ArtistMaster.ArtistDetails.COLUMN_ARTIST_NAME,artistName);
        long id = db.insert(ArtistMaster.ArtistDetails.TABLE_NAME,null,data);

        if(id>0){
            return true;
        }else{
            return false;
        }
    }

Is an empty href valid?

Although this question is already answered (tl;dr: yes, an empty href value is valid), none of the existing answers references the relevant specifications.

An empty string can’t be a URI. However, the href attribute doesn’t only take URIs as value, but also URI references. An empty string may be a URI reference.

HTML 4.01

HTML 4.01 uses RFC 2396, where it says in section 4.2. Same-document References (bold emphasis mine):

A URI reference that does not contain a URI is a reference to the current document. In other words, an empty URI reference within a document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference to the identified fragment of that document.

RFC 2396 is obsoleted by RFC 3986 (which is currently IETF’s URI standard), which essentially says the same.

HTML5

HTML5 uses (valid URL potentially surrounded by spaces ? valid URL) W3C’s URL spec, which has been discontinued. WHATWG’s URL Standard should be used instead (see the last section).

HTML 5.1

HTML 5.1 uses (valid URL potentially surrounded by spaces ? valid URL) WHATWG’s URL Standard (see the next section).

WHATWG HTML

WHATWG’s HTML uses (valid URL potentially surrounded by spaces) the definition of valid URL string from WHATWG’s URL Standard, where it says that it can be a relative-URL-with-fragment string, which must at least be a relative-URL string, which can be a path-relative-scheme-less-URL string, which is a path-relative-URL string that doesn’t start with a scheme string followed by :, and its definition says (bold emphasis mine):

A path-relative-URL string must be zero or more URL-path-segment strings, separated from each other by U+002F (/), and not start with U+002F (/).

Handle Button click inside a row in RecyclerView

You need to return true inside onInterceptTouchEvent() when you handle click event.

How to select date without time in SQL

In case if you need the time to be zeros like 2018-01-17 00:00:00.000:

SELECT CONVERT(DATETIME, CONVERT(DATE, GETDATE()), 121)

Illegal Character when trying to compile java code

That's a byte order mark, as everyone says.

javac does not understand the BOM, not even when you try something like

javac -encoding UTF8 Test.java

You need to strip the BOM or convert your source file to another encoding. Notepad++ can convert a single files encoding, I'm not aware of a batch utility on the Windows platform for this.

The java compiler will assume the file is in your platform default encoding, so if you use this, you don't have to specify the encoding.

jQuery 'if .change() or .keyup()'

you can bind to multiple events by separating them with a space:

$(":input").on("keyup change", function(e) {
    // do stuff!
})

docs here.

hope that helps. cheers!

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

It can come from the fact that you have control dragged and created an outlet or action, and forgot to delete it. Even if you deleted the code, or even if you have made enough cmd+Z, you'll need to go in the connection inspector of your storyboard and see if the action or outlet you created is still here or not.

How to have stored properties in Swift, the same way I had on Objective-C?

Another example with using Objective-C associated objects and computed properties for Swift 3 and Swift 4

import CoreLocation

extension CLLocation {

    private struct AssociatedKeys {
        static var originAddress = "originAddress"
        static var destinationAddress = "destinationAddress"
    }

    var originAddress: String? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.originAddress) as? String
        }
        set {
            if let newValue = newValue {
                objc_setAssociatedObject(
                    self,
                    &AssociatedKeys.originAddress,
                    newValue as NSString?,
                    .OBJC_ASSOCIATION_RETAIN_NONATOMIC
                )
            }
        }
    }

    var destinationAddress: String? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.destinationAddress) as? String
        }
        set {
            if let newValue = newValue {
                objc_setAssociatedObject(
                    self,
                    &AssociatedKeys.destinationAddress,
                    newValue as NSString?,
                    .OBJC_ASSOCIATION_RETAIN_NONATOMIC
                )
            }
        }
    }

}

error: expected class-name before ‘{’ token

If you forward-declare Flight and Landing in Event.h, then you should be fixed.

Remember to #include "Flight.h" and #include "Landing.h" in your implementation file for Event.

The general rule of thumb is: if you derive from it, or compose from it, or use it by value, the compiler must know its full definition at the time of declaration. If you compose from a pointer-to-it, the compiler will know how big a pointer is. Similarly, if you pass a reference to it, the compiler will know how big the reference is, too.

Sort an Array by keys based on another Array?

Another way for PHP >= 5.3.0:

$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';

$customerSorted = array_replace(array_flip(array('name', 'dob', 'address')), $customer);

Result:

Array (
  [name] => Tim
  [dob] => 12/08/1986
  [address] => 123 fake st
  [dontSortMe] => this value doesnt need to be sorted
)

Works fine with string and numeric keys.

What does the "@" symbol do in Powershell?

You can also wrap the output of a cmdlet (or pipeline) in @() to ensure that what you get back is an array rather than a single item.

For instance, dir usually returns a list, but depending on the options, it might return a single object. If you are planning on iterating through the results with a foreach-object, you need to make sure you get a list back. Here's a contrived example:

$results = @( dir c:\autoexec.bat)

One more thing... an empty array (like to initialize a variable) is denoted @().

How to use componentWillMount() in React Hooks?

It might be clear for most, but have in mind that a function called inside the function component's body, acts as a beforeRender. This doesn't answer the question of running code on ComponentWillMount (before the first render) but since it is related and might help others I'm leaving it here.

const MyComponent = () => {
  const [counter, setCounter] = useState(0)
  
  useEffect(() => {
    console.log('after render')
  })

  const iterate = () => {
    setCounter(prevCounter => prevCounter+1)
  }

  const beforeRender = () => {
    console.log('before render')
  }

  beforeRender()

  return (
    <div>
      <div>{counter}</div>
      <button onClick={iterate}>Re-render</button>
    </div>
  )
}

export default MyComponent

Accessing Objects in JSON Array (JavaScript)

You can loop the array with a for loop and the object properties with for-in loops.

for (var i=0; i<result.length; i++)
    for (var name in result[i]) {
        console.log("Item name: "+name);
        console.log("Source: "+result[i][name].sourceUuid);
        console.log("Target: "+result[i][name].targetUuid);
    }

How can I print literal curly-brace characters in a string and also use .format on it?

Use escape sequences to escape the curly braces in the f-string. Ex:print(f'{a={1}}')

jQuery function to open link in new window

http://www.jquerybyexample.net/2012/05/open-link-in-new-tab-or-new-popup.html

$(document).ready(function() {
$('A.BLAH').click(function() {
var NWin = window.open($(this).prop('href'), '', 'height=600,width=1000');
if (window.focus)
{
NWin.focus();
}
return false;
});
});

How to use aria-expanded="true" to change a css property

If you were open to using JQuery, you could modify the background color for any link that has the property aria-expanded set to true by doing the following...

$("a[aria-expanded='true']").css("background-color", "#42DCA3");

Depending on how specific you want to be regarding which links this applies to, you may have to slightly modify your selector.

TypeError: argument of type 'NoneType' is not iterable

The python error says that wordInput is not an iterable -> it is of NoneType.

If you print wordInput before the offending line, you will see that wordInput is None.

Since wordInput is None, that means that the argument passed to the function is also None. In this case word. You assign the result of pickEasy to word.

The problem is that your pickEasy function does not return anything. In Python, a method that didn't return anything returns a NoneType.

I think you wanted to return a word, so this will suffice:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

Get value from SimpleXMLElement Object

You have to cast simpleXML Object to a string.

$value = (string) $xml->code[0]->lat;

Maven : error in opening zip file when running maven

I had the same problem but previous solutions not work for me. The only solution works for me is the following URL.

https://enlightensoft.wordpress.com/2013/01/15/maven-error-reading-error-in-opening-zip-file/

[EDIT]

Here I explain more about it

Suppose you got an error like below

[ERROR] error: error reading C:\Users\user\.m2\repository\org\jdom\jdom\1.1\jdom-1.1.jar; error in opening zip file

Then you have to follow these steps.

  1. First, delete the existing jar C:\Users\user\.m2\repository\org\jdom\jdom\1.1\jdom-1.1.jar
  2. Then you have to manually download relevant jar from Maven central repository. You can download from this link here
  3. After that, you have to copy that downloaded jar into the previous directory.C:\Users\user\.m2\repository\org\jdom\jdom\1.1\

Then you can build your project using mvn clean install

hope this will help somebody.

On Selenium WebDriver how to get Text from Span Tag

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));

kk.getText().toString();

System.out.println(+kk.getText().toString());

how to query LIST using linq

I would also suggest LinqPad as a convenient way to tackle with Linq for both advanced and beginners.

Example:
enter image description here

Extract data from XML Clob using SQL from Oracle Database

This should work

SELECT EXTRACTVALUE(column_name, '/DCResponse/ContextData/Decision') FROM traptabclob;

I have assumed the ** were just for highlighting?

How can I make an "are you sure" prompt in a Windows batchfile?

Open terminal. Type the following

echo>sure.sh
chmod 700 sure.sh

Paste this inside sure.sh

#!\bin\bash

echo -n 'Are you sure? [Y/n] '
read yn

if [ "$yn" = "n" ]; then
    exit 1
fi

exit 0

Close sure.sh and type this in terminal.

alias sure='~/sure&&'

Now, if you type sure before typing the command it will give you an are you sure prompt before continuing the command.

Hope this is helpful!

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

MySQL error: key specification without a key length

I know it's quite late, but removing the Unique Key Constraint solved the problem. I didn't use the TEXT or LONGTEXT column as PK , but I was trying to make it unique. I got the 1170 error, but when I removed UK, the error was removed too.

I don't fully understand why.

Why maven? What are the benefits?

I've never come across point 2? Can you explain why you think this affects deployment in any way. If anything maven allows you to structure your projects in a modularised way that actually allows hot fixes for bugs in a particular tier, and allows independent development of an API from the remainder of the project for example.

It is possible that you are trying to cram everything into a single module, in which case the problem isn't really maven at all, but the way you are using it.

std::string to float or double

   double myAtof ( string &num){
      double tmp;
      sscanf ( num.c_str(), "%lf" , &tmp);
      return tmp;
   }

Is it possible to remove the focus from a text input when a page loads?

I would add that HTMLElement has a built-in .blur method as well.

Here's a demo using both .focus and .blur which work in similar ways.

_x000D_
_x000D_
const input = document.querySelector("#myInput");
_x000D_
<input id="myInput" value="Some Input">_x000D_
_x000D_
<button type="button" onclick="input.focus()">Focus</button>_x000D_
<button type="button" onclick="input.blur()">Lose focus</button>
_x000D_
_x000D_
_x000D_

Angular-Material DateTime Picker Component?

Angular Material 10 now includes a new date range picker.

To use the new date range picker, you can use the mat-date-range-input and mat-date-range-picker components.

Example

HTML

<mat-form-field>
  <mat-label>Enter a date range</mat-label>
  <mat-date-range-input [rangePicker]="picker">
    <input matStartDate matInput placeholder="Start date">
    <input matEndDate matInput placeholder="End date">
  </mat-date-range-input>
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>

You can read and learn more about this in their official documentation.

Unfortunately, they still haven't build a timepicker on this release.

Forcing Internet Explorer 9 to use standards document mode

 <!doctype html>
 <meta http-equiv="X-UA-Compatible" content="IE=Edge">

This makes each version of IE use its standard mode, so IE 9 will use IE 9 standards mode. (If instead you wanted newer versions of IE to also specifically use IE 9 standards mode, you would replace Edge by 9. But it is difficult to see why you would want that.)

For explanations, see http://hsivonen.iki.fi/doctype/#ie8 (it looks rather messy, but that’s because IE is messy in its behaviors).

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

How do I check if a type is a subtype OR the type of an object?

If you're trying to do it in a Xamarin Forms PCL project, the above solutions using IsAssignableFrom gives an error:

Error: 'Type' does not contain a definition for 'IsAssignableFrom' and no extension method 'IsAssignableFrom' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)

because IsAssignableFrom asks for a TypeInfo object. You can use the GetTypeInfo() method from System.Reflection:

typeof(BaseClass).GetTypeInfo().IsAssignableFrom(typeof(unknownType).GetTypeInfo())

How can I make the computer beep in C#?

In .Net 2.0, you can use Console.Beep().

// Default beep
Console.Beep();

You can also specify the frequency and length of the beep in milliseconds.

// Beep at 5000 Hz for 1 second
Console.Beep(5000, 1000);

For more information refer http://msdn.microsoft.com/en-us/library/8hftfeyw%28v=vs.110%29.aspx

How to clear the canvas for redrawing

Use clearRect method by passing x,y co-ordinates and height and width of canvas. ClearRect will clear whole canvas as :

canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);

Android how to convert int to String?

You called an incorrect method of String class, try:

int tmpInt = 10;
String tmpStr10 = String.valueOf(tmpInt);

You can also do:

int tmpInt = 10;
String tmpStr10 = Integer.toString(tmpInt);

CSS Background Image Not Displaying

According to your CSS file path, I will suppose it is at the same directory with your HTML page, you have to change the url as follows:

body { background: url(img/debut_dark.png) repeat 0 0; }

CSS3 Box Shadow on Top, Left, and Right Only

I found a way to cover the shadow with ":after", here is my code:

#div:after {
    content:"";
    position:absolute;
    width:5px;
    background:#fff;
    height:38px;
    top:1px;
    right:-5px;
}

Get name of current class?

I think, it should be like this:

    class foo():
        input = get_input(__qualname__)

E: Unable to locate package npm

in my jenkins/jenkins docker sudo always generates error:

bash: sudo: command not found

I needed update repo list with:

curl -sL https://deb.nodesource.com/setup_10.x | apt-get update

then,

 apt-get install nodejs

All the command line results like this:

root@76e6f92724d1:/# curl -sL https://deb.nodesource.com/setup_10.x | apt-get update
Ign:1 http://deb.debian.org/debian stretch InRelease
Get:2 http://security.debian.org/debian-security stretch/updates InRelease [94.3 kB]
Get:3 http://deb.debian.org/debian stretch-updates InRelease [91.0 kB]
Get:4 http://deb.debian.org/debian stretch Release [118 kB]
Get:5 http://security.debian.org/debian-security stretch/updates/main amd64 Packages [520 kB]
Get:6 http://deb.debian.org/debian stretch-updates/main amd64 Packages [27.9 kB]
Get:8 http://deb.debian.org/debian stretch Release.gpg [2410 B]
Get:9 http://deb.debian.org/debian stretch/main amd64 Packages [7083 kB]
Get:7 https://packagecloud.io/github/git-lfs/debian stretch InRelease [23.2 kB]
Get:10 https://packagecloud.io/github/git-lfs/debian stretch/main amd64 Packages [4675 B]
Fetched 7965 kB in 20s (393 kB/s)
Reading package lists... Done
root@76e6f92724d1:/#  apt-get install nodejs
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  libicu57 libuv1
The following NEW packages will be installed:
  libicu57 libuv1 nodejs
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 11.2 MB of archives.
After this operation, 45.2 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://deb.debian.org/debian stretch/main amd64 libicu57 amd64 57.1-6+deb9u3 [7705 kB]
Get:2 http://deb.debian.org/debian stretch/main amd64 libuv1 amd64 1.9.1-3 [84.4 kB]
Get:3 http://deb.debian.org/debian stretch/main amd64 nodejs amd64 4.8.2~dfsg-1 [3440 kB]
Fetched 11.2 MB in 26s (418 kB/s)
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package libicu57:amd64.
(Reading database ... 12488 files and directories currently installed.)
Preparing to unpack .../libicu57_57.1-6+deb9u3_amd64.deb ...
Unpacking libicu57:amd64 (57.1-6+deb9u3) ...
Selecting previously unselected package libuv1:amd64.
Preparing to unpack .../libuv1_1.9.1-3_amd64.deb ...
Unpacking libuv1:amd64 (1.9.1-3) ...
Selecting previously unselected package nodejs.
Preparing to unpack .../nodejs_4.8.2~dfsg-1_amd64.deb ...
Unpacking nodejs (4.8.2~dfsg-1) ...
Setting up libuv1:amd64 (1.9.1-3) ...
Setting up libicu57:amd64 (57.1-6+deb9u3) ...
Processing triggers for libc-bin (2.24-11+deb9u4) ...
Setting up nodejs (4.8.2~dfsg-1) ...
update-alternatives: using /usr/bin/nodejs to provide /usr/bin/js (js) in auto mode

How to add two strings as if they were numbers?

If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:

function addStrings(str1, str2){
  str1a = str1.split('').reverse();
  str2a = str2.split('').reverse();
  let output = '';
  let longer = Math.max(str1.length, str2.length);
  let carry = false;
  for (let i = 0; i < longer; i++) {
    let result
    if (str1a[i] && str2a[i]) {
      result = parseInt(str1a[i]) + parseInt(str2a[i]);

    } else if (str1a[i] && !str2a[i]) {
      result = parseInt(str1a[i]);

    } else if (!str1a[i] && str2a[i]) {
      result = parseInt(str2a[i]);
    }

    if (carry) {
        result += 1;
        carry = false;
    }
    if(result >= 10) {
      carry = true;
      output += result.toString()[1];
    }else {
      output += result.toString();
    }
  }
  output = output.split('').reverse().join('');

  if(carry) {
    output = '1' + output;
  }
  return output;
}

Linear Layout and weight in Android

You are not setting the layout_weight property. Your code reads weight="1" and it should read android:layout_weight="1".

Error when trying vagrant up

edit the vagrant file created by vagrant init in the same directory and enter the box name in the line config.vm.box = "ubuntu/trusty64" where ubuntu/trusty64 is your base box. Now vagrant up will download and set ubuntu/trusty64 as base box for you.

Submit button not working in Bootstrap form

Replace this

 <button type="button" value=" Send" class="btn btn-success" type="submit" id="submit">

with

<button  value=" Send" class="btn btn-success" type="submit" id="submit">

How do I implement charts in Bootstrap?

Update 2018

Here's a simple example using Bootstrap 4 with ChartJs. Use an HTML5 Canvas element for the chart...

<div class="container">
    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-body">
                    <canvas id="chLine"></canvas>
                </div>
            </div>
        </div>
     </div>     
</div>

And then the appropriate JS to populate the chart...

var colors = ['#007bff','#28a745'];
var chLine = document.getElementById("chLine");
var chartData = {
  labels: ["S", "M", "T", "W", "T", "F", "S"],
  datasets: [{
    data: [589, 445, 483, 503, 689, 692, 634],
    borderColor: colors[0],
    borderWidth: 4,
    pointBackgroundColor: colors[0]
  },
  {
    data: [639, 465, 493, 478, 589, 632, 674],
    borderColor: colors[1],
    borderWidth: 4,
    pointBackgroundColor: colors[1]
  }]
};
if (chLine) {
  new Chart(chLine, {
  type: 'line',
  data: chartData,
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: false
        }
      }]
    },
    legend: {
      display: false
    }
  }
  });
}

Bootstrap 4 Charts Demo

Reading Xml with XmlReader in C#

For sub-objects, ReadSubtree() gives you an xml-reader limited to the sub-objects, but I really think that you are doing this the hard way. Unless you have very specific requirements for handling unusual / unpredicatable xml, use XmlSerializer (perhaps coupled with sgen.exe if you really want).

XmlReader is... tricky. Contrast to:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
public class ApplicationPool {
    private readonly List<Account> accounts = new List<Account>();
    public List<Account> Accounts {get{return accounts;}}
}
public class Account {
    public string NameOfKin {get;set;}
    private readonly List<Statement> statements = new List<Statement>();
    public List<Statement> StatementsAvailable {get{return statements;}}
}
public class Statement {}
static class Program {
    static void Main() {
        XmlSerializer ser = new XmlSerializer(typeof(ApplicationPool));
        ser.Serialize(Console.Out, new ApplicationPool {
            Accounts = { new Account { NameOfKin = "Fred",
                StatementsAvailable = { new Statement {}, new Statement {}}}}
        });
    }
}

change the date format in laravel view page

Easy to use date in blade template use Carbon that way

{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}

How do I create a SQL table under a different schema?

The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.

USE [DBName] 
GO 
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema] 
GO

Two onClick actions one button

<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />

How to make php display \t \n as tab and new line instead of characters

You can use HTML,

foreach(...)
echo $data1 . '&nbsp' . $data2 . '&nbsp' . $data3 . '<br/>';

Use string.Contains() with switch()

Faced with this issue when determining an environment, I came up with the following one-liner:

string ActiveEnvironment = localEnv.Contains("LIVE") ? "LIVE" : (localEnv.Contains("TEST") ? "TEST" : (localEnv.Contains("LOCAL") ? "LOCAL" : null));

That way, if it can't find anything in the provided string that matches the "switch" conditions, it gives up and returns null. This could easily be amended to return a different value.

It's not strictly a switch, more a cascading if statement but it's neat and it worked.

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

You can replace IList<DzieckoAndOpiekun> resultV with var resultV.

Can I configure a subdomain to point to a specific port on my server

If you have access to SRV Records, you can use them to get what you want :)

E.G

A Records

Name: mc1.domain.com
Value: <yourIP>

Name: mc2.domain.com
Value: <yourIP>

SRV Records

Name: _minecraft._tcp.mc1.domain.com
Priority: 5
Weight: 5
Port: 25565
Value: mc1.domain.com

Name: _minecraft._tcp.mc2.domain.com
Priority: 5
Weight: 5
Port: 25566
Value: mc2.domain.com

then in minecraft you can use

mc1.domain.com which will sign you into server 1 using port 25565

and

mc2.domain.com which will sign you into server 2 using port 25566

then on your router you can have it point 25565 and 25566 to the machine with both servers on and Voilà!

Source: This works for me running 2 minecraft servers on the same machine with ports 50500 and 50501

Android: Center an image

change layout weight according you will get....

Enter this:

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_weight="0.03">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:layout_gravity="center"
        android:src="@drawable/logo" />

</LinearLayout>

From milliseconds to hour, minutes, seconds and milliseconds

Good question. Yes, one can do this more efficiently. Your CPU can extract both the quotient and the remainder of the ratio of two integers in a single operation. In <stdlib.h>, the function that exposes this CPU operation is called div(). In your psuedocode, you'd use it something like this:

function to_tuple(x):
    qr = div(x, 1000)
    ms = qr.rem
    qr = div(qr.quot, 60)
    s  = qr.rem
    qr = div(qr.quot, 60)
    m  = qr.rem
    h  = qr.quot

A less efficient answer would use the / and % operators separately. However, if you need both quotient and remainder, anyway, then you might as well call the more efficient div().

How can I get client information such as OS and browser

The browser sends this information in the HTTP header. See the snoop example of Tomcat for some code (source, online demo).

Note that this information is not reliable. Browser can and do lie about who they are and what OS they run on.

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

How do I measure request and response times at once using cURL?

Here's a Bash one-liner to hit the same server repeatedly:

for i in {1..1000}; do curl -s -o /dev/null -w "%{time_total}\n" http://server/get_things; done

What is the main difference between Inheritance and Polymorphism?

Inheritance refers to using the structure and behavior of a super class in a subclass.

Polymorphism refers to changing the behavior of a super class in the subclass.

how I can show the sum of in a datagridview column?

you can do it better with two datagridview, you add the same datasource , hide the headers of the second, set the height of the second = to the height of the rows of the first, turn off all resizable atributes of the second, synchronize the scrollbars of both, only horizontal, put the second on the botton of the first etc.

take a look:

   dgv3.ColumnHeadersVisible = false;
   dgv3.Height = dgv1.Rows[0].Height;
   dgv3.Location = new Point(Xdgvx, this.dgv1.Height - dgv3.Height - SystemInformation.HorizontalScrollBarHeight);
   dgv3.Width = dgv1.Width;

   private void dgv1_Scroll(object sender, ScrollEventArgs e)
        {
            if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
            {
                dgv3.HorizontalScrollingOffset = e.NewValue;
            }
        }

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

SQL Server AS statement aliased column within WHERE statement

This would work on your edited question !

SELECT * FROM (SELECT <Column_List>,  
( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) )  
AS distance 
FROM poi_table) TMP
WHERE distance < 500; 

Illegal Escape Character "\"

I think ("\") may be causing the problem because \ is the escape character. change it to ("\\")

failed to load ad : 3

I hadn't published a version of my app with ads yet.

I was seeing error code 3: ERROR_CODE_NO_FILL after I switched from emulators with a debug version to a real device with the release version (installed through adb shell commands).

I waited 12+ hours and I could see ad requests on the AdMob portal, but no matches (match rate of 0%). I went to the Play Console > Store Presence > Pricing & distribution and switched the radio button for Contains ads to Yes, it has ads. I even tried uploading my app bundle (without publishing) to the Play Console. Neither of these worked.

Various AdMob help articles (including the one linked below) mention that if you've been seeing test ads (ads labeled with "Test Ad"), then your code is working and real ads should work as expected (once they build up inventory).

With that in mind, I went ahead and published my app to the Play Store and once the update was live, I downloaded it via the Play Store app on my real phone and the ads loaded no problem and my match rate is now sitting at 66% on AdMob. From the AdMob FAQ article, it sounds like it typically takes a few hours and could have taken up to 24 hours for ads to start showing.

ad mob FAQ re: how long does it take ads to show

Source: https://support.google.com/admob/answer/2993019?hl=en

How do I discard unstaged changes in Git?

I had a weird situation where a file is always unstaged, this helps me to resolve.

git rm .gitattributes
git add -A
git reset --hard

Where is the web server root directory in WAMP?

this is the path to the web root directory c:\wamp\www

you can create different projects by adding different folders to this directory and call them like:

localhost/project1 from browser

this will run the index.html or index.php, lying inside project1

How to delete a certain row from mysql table with same column values?

There are already answers for Deleting row by LIMIT. Ideally you should have primary key in your table. But if there is not.

I will give other ways:

  1. By creating Unique index

I see id_users and id_product should be unique in your example.

ALTER IGNORE TABLE orders ADD UNIQUE INDEX unique_columns_index (id_users, id_product)

These will delete duplicate rows with same data.

But if you still get an error, even if you use IGNORE clause, try this:

ALTER TABLE orders ENGINE MyISAM;
ALTER IGNORE TABLE orders ADD UNIQUE INDEX unique_columns_index (id_users, id_product)
ALTER TABLE orders ENGINE InnoDB; 
  1. By creating table again

If there are multiple rows who have duplicate values, then you can also recreate table

RENAME TABLE `orders` TO `orders2`;

CREATE TABLE `orders` 
SELECT * FROM `orders2` GROUP BY id_users, id_product;

How to write logs in text file when using java.util.logging.Logger

Hope people find this helpful

public static void writeLog(String info) {
    String filename = "activity.log";
    String FILENAME = "C:\\testing\\" + filename;
    BufferedWriter bw = null;
    FileWriter fw = null;
    try {
        fw = new FileWriter(FILENAME, true);
        bw = new BufferedWriter(fw);
        bw.write(info);
        bw.write("\n");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bw != null)
                bw.close();
            if (fw != null)
                fw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

For those wanting to use Postgresql on OpenSuse (and co), try the following:

zypper --no-refresh in php5-pgsql

How to use auto-layout to move other views when a view is hidden?

Instead of hiding view, create the width constrain and change it to 0 in code when you want to hide the UIView.

It may be the simplest way to do so. Also, it will preserve the view and you don't need to recreate it if you want to show it again (ideal to use inside table cells). To change the constant value you need to create a constant reference outlet (the same way as you do outlets for the view).

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

My solution uses positioning to get wrapped lines automatically line up correctly. So you don't have to worry about setting padding-right on the li:before.

_x000D_
_x000D_
ul {_x000D_
  margin-left: 0;_x000D_
  padding-left: 0;_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
  position: relative;_x000D_
  margin-left: 1em;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  position: absolute;_x000D_
  left: -1em;_x000D_
  content: "+";_x000D_
}
_x000D_
<ul>_x000D_
  <li>Item 1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 2 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 3 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam</li>_x000D_
  <li>Item 4</li>_x000D_
  <li>Item 5</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to pass a null variable to a SQL Stored Procedure from C#.net code

You can pass the DBNull.Value into the parameter's .Value property:

    SqlParameters[0] = new SqlParameter("LedgerID", SqlDbType.BigInt );
    SqlParameters[0].Value = DBNull.Value;

Just adjust for your two DateTime parameters, obviously - just showing how to use the DBNull.Value property value here.

Marc

Angular2 - Input Field To Accept Only Numbers

Casting because it works also with leading 0 like 00345

@Directive({
  selector: '[appOnlyDigits]'
})
export class AppOnlyDigitsDirective {
  @HostListener('input', ['$event'])
  onKeyDown(ev: KeyboardEvent) {
    const input = ev.target as HTMLInputElement;
    input.value = String(input.value.replace(/\D+/g, ''));
  }
}

Create a HTML table where each TR is a FORM

If you can use javascript and strictly require it on your web, you can put textboxes, checkboxes and whatever on each row of your table and at the end of each row place button (or link of class rowSubmit) "save". Without any FORM tag. Form than will be simulated by JS and Ajax like this:

<script type="text/javascript">
$(document).ready(function(){
  $(".rowSubmit").click(function()
  {
     var form = '<form><table><tr>' + $(this).closest('tr').html() + '</tr></table></form>';
     var serialized = $(form).serialize(); 
     $.get('url2action', serialized, function(data){
       // ... can be empty
     }); 
   });
});        
</script>

What do you think?

PS: If you write in jQuery this:

$("valid HTML string")
$(variableWithValidHtmlString)

It will be turned into jQuery object and you can work with it as you are used to in jQuery.

prevent iphone default keyboard when focusing an <input>

Below code works for me:

<input id="myDatePicker" class="readonlyjm"/>


$('#myDatePicker').datepicker({
/* options */
});

$('.readonlyjm').on('focus',function(){
$(this).trigger('blur');
});

Why is Android Studio reporting "URI is not registered"?

For me this was because I was using a debug and release build variant. I added the new folders src/debug/res/layout/some_layout.xml file manually, and it didn't recognize the URI. I switched the build variant to release, and then back to debug. This caused Android Studio to reload something, and the error went away.

EDIT: Also check that you have the correct filename. I had this issue again by adding a debug AndroidManifest.xml, but mistakenly named it AndroidManifest.xml.xml.

How to set custom ActionBar color / style?

I can change ActionBar text color by using titleTextColor

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="titleTextColor">#333333</item>
</style>

CSS property to pad text inside of div

Padding is a way to add kind of a margin inside the Div.
Just Use

div { padding-left: 20px; }

And to mantain the size, you would have to -20px from the original width of the Div.

Multidimensional arrays in Swift

Your original logic for creating the matrix is indeed correct, and it even works in Swift 2. The problem is that in the print loop, you have the row and column variables reversed. If you change it to:

for row in 0...2 {
  for column in 0...2 {
    print("column: \(column) row: \(row) value:\(array[column][row])")

  }
}

you will get the correct results. Hope this helps!

How do I get the offset().top value of an element without using jQuery?

use getBoundingClientRect if $el is the actual DOM object:

var top = $el.getBoundingClientRect().top;

JSFiddle

Fiddle will show that this will get the same value that jquery's offset top will give you

Edit: as mentioned in comments this does not account for scrolled content, below is the code that jQuery uses

https://github.com/jquery/jquery/blob/master/src/offset.js (5/13/2015)

offset: function( options ) {
    //...

    var docElem, win, rect, doc,
        elem = this[ 0 ];

    if ( !elem ) {
        return;
    }

    rect = elem.getBoundingClientRect();

    // Make sure element is not hidden (display: none) or disconnected
    if ( rect.width || rect.height || elem.getClientRects().length ) {
        doc = elem.ownerDocument;
        win = getWindow( doc );
        docElem = doc.documentElement;

        return {
            top: rect.top + win.pageYOffset - docElem.clientTop,
            left: rect.left + win.pageXOffset - docElem.clientLeft
        };
    }
}

Cassandra port usage - how are the ports used?

8080 - JMX (remote)

8888 - Remote debugger (removed in 0.6.0)

7000 - Used internal by Cassandra
(7001 - Obsolete, removed in 0.6.0. Used for membership communication, aka gossip)

9160 - Thrift client API

Cassandra FAQ What ports does Cassandra use?

What's causing my java.net.SocketException: Connection reset?

I got this error when the text file I was trying to read contained a string that matched an antivirus signature on our firewall.

How to make HTML open a hyperlink in another window or tab?

You can also accomplish this by adding the following to your page's header:

<base target="_blank">

This will make ALL links on your page open in a new tab

How to smooth a curve in the right way?

EDIT: look at this answer. Using np.cumsum is much faster than np.convolve

A quick and dirty way to smooth data I use, based on a moving average box (by convolution):

x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.8

def smooth(y, box_pts):
    box = np.ones(box_pts)/box_pts
    y_smooth = np.convolve(y, box, mode='same')
    return y_smooth

plot(x, y,'o')
plot(x, smooth(y,3), 'r-', lw=2)
plot(x, smooth(y,19), 'g-', lw=2)

enter image description here

How to count instances of character in SQL Column

for example to calculate the count instances of character (a) in SQL Column ->name is column name '' ( and in doblequote's is empty i am replace a with nocharecter @'')

select len(name)- len(replace(name,'a','')) from TESTING

select len('YYNYNYYNNNYYNY')- len(replace('YYNYNYYNNNYYNY','y',''))

Spring Boot - How to get the running port

Starting with Spring Boot 1.4.0 you can use this in your test:

import org.springframework.boot.context.embedded.LocalServerPort;

@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {

  @LocalServerPort
  int randomPort;

  // ...
}

Change Select List Option background colour on hover in html

No, it's not possible.

It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".

How to get absolute value from double - c-language

I have found that using cabs(double), cabsf(float), cabsl(long double), __cabsf(float), __cabs(double), __cabsf(long double) is the solution

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I had this same problem when trying to upgrade pm2 to the latest version.

Thanks to sdm's answer I did npm update npm -g and it did the trick for me.

Most efficient way to create a zero filled JavaScript array?

By default Uint8Array, Uint16Array and Uint32Array classes keep zeros as its values, so you don't need any complex filling techniques, just do:

var ary = new Uint8Array(10);

all elements of array ary will be zeros by default.

Memory address of variables in Java

It is possible using sun.misc.Unsafe : see this great answer from @Peter Lawrey -> Is there a way to get a reference address?

Using its code for printAddresses() :

    public static void printAddresses(String label, Object... objects) {
    System.out.print(label + ": 0x");
    long last = 0;
    int offset = unsafe.arrayBaseOffset(objects.getClass());
    int scale = unsafe.arrayIndexScale(objects.getClass());
    switch (scale) {
    case 4:
        long factor = is64bit ? 8 : 1;
        final long i1 = (unsafe.getInt(objects, offset) & 0xFFFFFFFFL) * factor;
        System.out.print(Long.toHexString(i1));
        last = i1;
        for (int i = 1; i < objects.length; i++) {
            final long i2 = (unsafe.getInt(objects, offset + i * 4) & 0xFFFFFFFFL) * factor;
            if (i2 > last)
                System.out.print(", +" + Long.toHexString(i2 - last));
            else
                System.out.print(", -" + Long.toHexString( last - i2));
            last = i2;
        }
        break;
    case 8:
        throw new AssertionError("Not supported");
    }
    System.out.println();
}

I set up this test :

    //hashcode
    System.out.println("Hashcode :       "+myObject.hashCode());
    System.out.println("Hashcode :       "+System.identityHashCode(myObject));
    System.out.println("Hashcode (HEX) : "+Integer.toHexString(myObject.hashCode()));

    //toString
    System.out.println("toString :       "+String.valueOf(myObject));

    printAddresses("Address", myObject);

Here is the output :

Hashcode :       125665513
Hashcode :       125665513
Hashcode (HEX) : 77d80e9
toString :       java.lang.Object@77d80e9
Address: 0x7aae62270

Conclusion :

  • hashcode != address
  • toString = class@HEX(hashcode)

How can I correctly format currency using jquery?

Try regexp currency with jQuery (no plugin):

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('#test').click(function() {_x000D_
    TESTCURRENCY = $('#value').val().toString().match(/(?=[\s\d])(?:\s\.|\d+(?:[.]\d+)*)/gmi);_x000D_
    if (TESTCURRENCY.length <= 1) {_x000D_
      $('#valueshow').val(_x000D_
        parseFloat(TESTCURRENCY.toString().match(/^\d+(?:\.\d{0,2})?/))_x000D_
      );_x000D_
    } else {_x000D_
      $('#valueshow').val('Invalid a value!');_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="text" value="12345.67890" id="value">_x000D_
<input type="button" id="test" value="CLICK">_x000D_
<input type="text" value="" id="valueshow">
_x000D_
_x000D_
_x000D_

Edit: New check a value to valid/invalid

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

This issue is happening because you have installed jre1.8.0_101-1.8.0_101-fcs.i58.rpm as well jdk-1.7.0_80-fcs.x86_64.rpm. so just uninstall your jre rpm & restart your application. It should work out.

Separators for Navigation

You can add one li element where you want to add divider

<ul>
    <li> your content </li>
    <li class="divider-vertical-second-menu"></li>
    <li> NExt content </li>
    <li class="divider-vertical-second-menu"></li>
    <li> last item </li>
</ul>

In CSS you can Add following code.

.divider-vertical-second-menu{
   height: 40px;
   width: 1px;
   margin: 0 5px;
   overflow: hidden;
   background-color: #DDD;
   border-right: 2px solid #FFF;
}

This will increase you speed of execution as it will not load any image. just test it out.. :)

formGroup expects a FormGroup instance

I had a the same error and solved it after moving initialization of formBuilder from ngOnInit to constructor.

Concatenating Files And Insert New Line In Between Files

You can do:

for f in *.txt; do (cat "${f}"; echo) >> finalfile.txt; done

Make sure the file finalfile.txt does not exist before you run the above command.

If you are allowed to use awk you can do:

awk 'FNR==1{print ""}1' *.txt > finalfile.txt

How do I draw a shadow under a UIView?

Same solution, but just to remind you: You can define the shadow directly in the storyboard.

Ex:

enter image description here

Extract the first word of a string in a SQL Server query

I wanted to do something like this without making a separate function, and came up with this simple one-line approach:

DECLARE @test NVARCHAR(255)
SET @test = 'First Second'

SELECT SUBSTRING(@test,1,(CHARINDEX(' ',@test + ' ')-1))

This would return the result "First"

It's short, just not as robust, as it assumes your string doesn't start with a space. It will handle one-word inputs, multi-word inputs, and empty string or NULL inputs.

How do you underline a text in Android XML?

Use this:

TextView txt = (TextView) findViewById(R.id.Textview1);
txt.setPaintFlags(txt.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

100% width table overflowing div container

Well, given your constraints, I think setting overflow: scroll; on the .page div is probably your only option. 280 px is pretty narrow, and given your font size, word wrapping alone isn't going to do it. Some words are just long and can't be wrapped. You can either reduce your font size drastically or go with overflow: scroll.

How to cherry pick a range of commits and merge into another branch?

Assume that you have 2 branches,

"branchA" : includes commits you want to copy (from "commitA" to "commitB"

"branchB" : the branch you want the commits to be transferred from "branchA"

1)

 git checkout <branchA>

2) get the IDs of "commitA" and "commitB"

3)

git checkout <branchB>

4)

git cherry-pick <commitA>^..<commitB>

5) In case you have a conflict, solve it and type

git cherry-pick --continue

to continue the cherry-pick process.

Simple check for SELECT query empty result

SELECT * FROM service s WHERE s.service_id = ?;
BEGIN
   print 'no data'
END

Is SQL syntax case sensitive?

SQL keywords are case insensitive themselves.

Names of tables, columns etc, have a case sensitivity which is database dependent - you should probably assume that they are case sensitive unless you know otherwise (In many databases they aren't though; in MySQL table names are SOMETIMES case sensitive but most other names are not).

Comparing data using =, >, < etc, has a case awareness which is dependent on the collation settings which are in use on the individual database, table or even column in question. It's normal however, to keep collation fairly consistent within a database. We have a few columns which need to store case-sensitive values; they have a collation specifically set.

Changing the color of a clicked table row using jQuery

Here's a possible solution that will color the entire row for your table.

CSS

tr.highlighted td {
    background: red;
}

jQuery

$('#data tr').click(function(e) {
    $('#data tr').removeClass('highlighted');
    $(this).toggleClass('highlighted');   
});

Demo: http://jsfiddle.net/jrthib/HVw7E/2/

PHP - find entry by object property from an array of objects

I sometimes like using the array_reduce() function to carry out the search. It's similar to array_filter() but does not affect the searched array, allowing you to carry out multiple searches on the same array of objects.

$haystack = array($obj1, $obj2, ...); //some array of objects
$needle = 'looking for me?'; //the value of the object's property we want to find

//carry out the search
$search_results_array = array_reduce(
  $haystack,

  function($result_array, $current_item) use ($needle){
      //Found the an object that meets criteria? Add it to the the result array 
      if ($current_item->someProperty == $needle){
          $result_array[] = $current_item;
      }
      return $result_array;
  },
  array() //initially the array is empty (i.e.: item not found)
);

//report whether objects found
if (count($search_results_array) > 0){
  echo "found object(s): ";
  print_r($search_results_array[0]); //sample object found
} else {
  echo "did not find object(s): ";
}

how to make a cell of table hyperlink

Not exactly making the cell a link, but the table itself. I use this as a button in e-mails, giving me div-like controls.

_x000D_
_x000D_
<a href="https://www.foo.bar" target="_blank" style="color: white; font-weight: bolder; text-decoration: none;">
  <table style="margin-left: auto; margin-right: auto;" align="center">
    <tr>
      <td style="padding: 20px; height: 60px;" bgcolor="#00b389">Go to Foo Bar</td>
    </tr>
  </table>
</a>
_x000D_
_x000D_
_x000D_

Stratified Train/Test-split in scikit-learn

In addition to the accepted answer by @Andreas Mueller, just want to add that as @tangy mentioned above:

StratifiedShuffleSplit most closely resembles train_test_split(stratify = y) with added features of:

  1. stratify by default
  2. by specifying n_splits, it repeatedly splits the data

Pass accepts header parameter to jquery ajax

Try this:

$.ajax({
        beforeSend: function (xhr){ 
        xhr.setRequestHeader("Content-Type","application/json");
        xhr.setRequestHeader("Accept","text/json");
    }, 
    type: "POST",
    //........
});

Cannot load properties file from resources directory

Using ClassLoader.getSystemClassLoader()

Sample code :

Properties prop = new Properties();
InputStream input = null;
try {
    input = ClassLoader.getSystemClassLoader().getResourceAsStream("conf.properties");
    prop.load(input);

} catch (IOException io) {
    io.printStackTrace();
}

PHP mySQL - Insert new record into table with auto-increment on primary key

I prefer this syntaxis:

$query = "INSERT INTO myTable SET fname='Fname',lname='Lname',website='Website'";

How do I update an entity using spring-data-jpa?

Since the answer by @axtavt focuses on JPA not spring-data-jpa

To update an entity by querying then saving is not efficient because it requires two queries and possibly the query can be quite expensive since it may join other tables and load any collections that have fetchType=FetchType.EAGER

Spring-data-jpa supports update operation.
You have to define the method in Repository interface.and annotated it with @Query and @Modifying.

@Modifying
@Query("update User u set u.firstname = ?1, u.lastname = ?2 where u.id = ?3")
void setUserInfoById(String firstname, String lastname, Integer userId);

@Query is for defining custom query and @Modifying is for telling spring-data-jpa that this query is an update operation and it requires executeUpdate() not executeQuery().

You can specify other return types:
int - the number of records being updated.
boolean - true if there is a record being updated. Otherwise, false.


Note: Run this code in a Transaction.

Java Command line arguments

Try to pass value a and compare using the equals method like this:

public static void main(String str[]) {

    boolean b = str[0].equals("a");

    System.out.println(b);

}

Follow this link to know more about Command line argument in Java

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

additionally for accepted answer you can use UseSubmitBehavior="false" MSDN

Get value of div content using jquery

Use .text() to extract the content of the div

var text = $('#field-function_purpose').text()

calling another method from the main method in java

Check out for the static before the main method, this declares the method as a class method, which means it needs no instance to be called. So as you are going to call a non static method, Java complains because you are trying to call a so called "instance method", which, of course needs an instance first ;)

If you want a better understanding about classes and instances, create a new class with instance and class methods, create a object in your main loop and call the methods!

 class Foo{

    public static void main(String[] args){
       Bar myInstance = new Bar();
       myInstance.do(); // works!
       Bar.do(); // doesn't work!

       Bar.doSomethingStatic(); // works!
    }
 }

class Bar{

   public do() {
   // do something
   }

   public static doSomethingStatic(){
   }
}

Also remember, classes in Java should start with an uppercase letter.

Remove sensitive files and their commits from Git history

In my android project I had admob_keys.xml as separated xml file in app/src/main/res/values/ folder. To remove this sensitive file I used below script and worked perfectly.

git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch  app/src/main/res/values/admob_keys.xml' \
--prune-empty --tag-name-filter cat -- --all

'str' object has no attribute 'decode'. Python 3 error?

I'm not familiar with the library, but if your problem is that you don't want a byte array, one easy way is to specify an encoding type straight in a cast:

>>> my_byte_str
b'Hello World'

>>> str(my_byte_str, 'utf-8')
'Hello World'

Saving an Object (Data persistence)

You could use the pickle module in the standard library. Here's an elementary application of it to your example:

import pickle

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

with open('company_data.pkl', 'wb') as output:
    company1 = Company('banana', 40)
    pickle.dump(company1, output, pickle.HIGHEST_PROTOCOL)

    company2 = Company('spam', 42)
    pickle.dump(company2, output, pickle.HIGHEST_PROTOCOL)

del company1
del company2

with open('company_data.pkl', 'rb') as input:
    company1 = pickle.load(input)
    print(company1.name)  # -> banana
    print(company1.value)  # -> 40

    company2 = pickle.load(input)
    print(company2.name) # -> spam
    print(company2.value)  # -> 42

You could also define your own simple utility like the following which opens a file and writes a single object to it:

def save_object(obj, filename):
    with open(filename, 'wb') as output:  # Overwrites any existing file.
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

# sample usage
save_object(company1, 'company1.pkl')

Update

Since this is such a popular answer, I'd like touch on a few slightly advanced usage topics.

cPickle (or _pickle) vs pickle

It's almost always preferable to actually use the cPickle module rather than pickle because the former is written in C and is much faster. There are some subtle differences between them, but in most situations they're equivalent and the C version will provide greatly superior performance. Switching to it couldn't be easier, just change the import statement to this:

import cPickle as pickle

In Python 3, cPickle was renamed _pickle, but doing this is no longer necessary since the pickle module now does it automatically—see What difference between pickle and _pickle in python 3?.

The rundown is you could use something like the following to ensure that your code will always use the C version when it's available in both Python 2 and 3:

try:
    import cPickle as pickle
except ModuleNotFoundError:
    import pickle

Data stream formats (protocols)

pickle can read and write files in several different, Python-specific, formats, called protocols as described in the documentation, "Protocol version 0" is ASCII and therefore "human-readable". Versions > 0 are binary and the highest one available depends on what version of Python is being used. The default also depends on Python version. In Python 2 the default was Protocol version 0, but in Python 3.8.1, it's Protocol version 4. In Python 3.x the module had a pickle.DEFAULT_PROTOCOL added to it, but that doesn't exist in Python 2.

Fortunately there's shorthand for writing pickle.HIGHEST_PROTOCOL in every call (assuming that's what you want, and you usually do), just use the literal number -1 — similar to referencing the last element of a sequence via a negative index. So, instead of writing:

pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

You can just write:

pickle.dump(obj, output, -1)

Either way, you'd only have specify the protocol once if you created a Pickler object for use in multiple pickle operations:

pickler = pickle.Pickler(output, -1)
pickler.dump(obj1)
pickler.dump(obj2)
   etc...

Note: If you're in an environment running different versions of Python, then you'll probably want to explicitly use (i.e. hardcode) a specific protocol number that all of them can read (later versions can generally read files produced by earlier ones).

Multiple Objects

While a pickle file can contain any number of pickled objects, as shown in the above samples, when there's an unknown number of them, it's often easier to store them all in some sort of variably-sized container, like a list, tuple, or dict and write them all to the file in a single call:

tech_companies = [
    Company('Apple', 114.18), Company('Google', 908.60), Company('Microsoft', 69.18)
]
save_object(tech_companies, 'tech_companies.pkl')

and restore the list and everything in it later with:

with open('tech_companies.pkl', 'rb') as input:
    tech_companies = pickle.load(input)

The major advantage is you don't need to know how many object instances are saved in order to load them back later (although doing so without that information is possible, it requires some slightly specialized code). See the answers to the related question Saving and loading multiple objects in pickle file? for details on different ways to do this. Personally I like @Lutz Prechelt's answer the best. Here's it adapted to the examples here:

class Company:
    def __init__(self, name, value):
        self.name = name
        self.value = value

def pickled_items(filename):
    """ Unpickle a file of pickled data. """
    with open(filename, "rb") as f:
        while True:
            try:
                yield pickle.load(f)
            except EOFError:
                break

print('Companies in pickle file:')
for company in pickled_items('company_data.pkl'):
    print('  name: {}, value: {}'.format(company.name, company.value))

automatically execute an Excel macro on a cell change

I prefer this way, not using a cell but a range

    Dim cell_to_test As Range, cells_changed As Range

    Set cells_changed = Target(1, 1)
    Set cell_to_test = Range( RANGE_OF_CELLS_TO_DETECT )

    If Not Intersect(cells_changed, cell_to_test) Is Nothing Then 
       Macro
    End If

Trigger standard HTML5 validation (form) without using submit button?

form.submit() doesn't work cause the HTML5 validation is performed before the form submition. When you click on a submit button, the HTML5 validation is trigerred and then the form is submited if validation was successfull.

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

I just ran into this problem myself.

First, modify your code slightly:

var download = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                  +"<"+this.gamesave.tagName+">"
                  +this.xml.firstChild.innerHTML
                  +"</"+this.gamesave.tagName+">";

this.loader.src = "data:application/x-forcedownload;base64,"+
                  btoa(download);

Then use your favorite web inspector, put a breakpoint on the line of code that assigns this.loader.src, then execute this code:

for (var i = 0; i < download.length; i++) {
  if (download[i].charCodeAt(0) > 255) {
    console.warn('found character ' + download[i].charCodeAt(0) + ' "' + download[i] + '" at position ' + i);
  }
}

Depending on your application, replacing the characters that are out of range may or may not work, since you'll be modifying the data. See the note on MDN about unicode characters with the btoa method:

https://developer.mozilla.org/en-US/docs/Web/API/window.btoa

What do two question marks together mean in C#?

It's short hand for the ternary operator.

FormsAuth = (formsAuth != null) ? formsAuth : new FormsAuthenticationWrapper();

Or for those who don't do ternary:

if (formsAuth != null)
{
  FormsAuth = formsAuth;
}
else
{
  FormsAuth = new FormsAuthenticationWrapper();
}

Why use pip over easy_install?

Many of the answers here are out of date for 2015 (although the initially accepted one from Daniel Roseman is not). Here's the current state of things:

  • Binary packages are now distributed as wheels (.whl files)—not just on PyPI, but in third-party repositories like Christoph Gohlke's Extension Packages for Windows. pip can handle wheels; easy_install cannot.
  • Virtual environments (which come built-in with 3.4, or can be added to 2.6+/3.1+ with virtualenv) have become a very important and prominent tool (and recommended in the official docs); they include pip out of the box, but don't even work properly with easy_install.
  • The distribute package that included easy_install is no longer maintained. Its improvements over setuptools got merged back into setuptools. Trying to install distribute will just install setuptools instead.
  • easy_install itself is only quasi-maintained.
  • All of the cases where pip used to be inferior to easy_install—installing from an unpacked source tree, from a DVCS repo, etc.—are long-gone; you can pip install ., pip install git+https://.
  • pip comes with the official Python 2.7 and 3.4+ packages from python.org, and a pip bootstrap is included by default if you build from source.
  • The various incomplete bits of documentation on installing, using, and building packages have been replaced by the Python Packaging User Guide. Python's own documentation on Installing Python Modules now defers to this user guide, and explicitly calls out pip as "the preferred installer program".
  • Other new features have been added to pip over the years that will never be in easy_install. For example, pip makes it easy to clone your site-packages by building a requirements file and then installing it with a single command on each side. Or to convert your requirements file to a local repo to use for in-house development. And so on.

The only good reason that I know of to use easy_install in 2015 is the special case of using Apple's pre-installed Python versions with OS X 10.5-10.8. Since 10.5, Apple has included easy_install, but as of 10.10 they still don't include pip. With 10.9+, you should still just use get-pip.py, but for 10.5-10.8, this has some problems, so it's easier to sudo easy_install pip. (In general, easy_install pip is a bad idea; it's only for OS X 10.5-10.8 that you want to do this.) Also, 10.5-10.8 include readline in a way that easy_install knows how to kludge around but pip doesn't, so you also want to sudo easy_install readline if you want to upgrade that.

How to round a number to n decimal places in Java

To achieve this we can use this formatter:

 DecimalFormat df = new DecimalFormat("#.00");
 String resultado = df.format(valor)

or:

DecimalFormat df = new DecimalFormat("0.00"); :

Use this method to get always two decimals:

   private static String getTwoDecimals(double value){
      DecimalFormat df = new DecimalFormat("0.00"); 
      return df.format(value);
    }

Defining this values:

91.32
5.22
11.5
1.2
2.6

Using the method we can get this results:

91.32
5.22
11.50
1.20
2.60

demo online.

PHP cURL, extract an XML response

<?php
function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);          
    curl_close($ch);
    return $retValue;
}

$sXML = download_page('http://alanstorm.com/atom');
$oXML = new SimpleXMLElement($sXML);

foreach($oXML->entry as $oEntry){
    echo $oEntry->title . "\n";
}

What are CN, OU, DC in an LDAP search?

At least with Active Directory, I have been able to search by DistinguishedName by doing an LDAP query in this format (assuming that such a record exists with this distinguishedName):

"(distinguishedName=CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com)"

How do I add an active class to a Link from React Router?

One of the way you can use it

When you are using the Functional component then follow the instruction here.

  • add a variable in your component
  • create an event change browser URL change/or other change
  • re-assign the current path (URL)
  • use javascript match function and set active or others

Use the above code here.

import React, { useEffect } from 'react';
import { Link } from 'react-router-dom';

const NavItems = () => {
    let pathname = window.location.pathname;
    useEffect(() => {
        pathname = window.location.pathname;
    }, [window.location.pathname]);

    return (
        <>
            <li className="px-4">
                <Link to="/home" className={`${pathname.match('/home') ? 'link-active' : ''}`}>Home</Link>
            </li>
            <li className="px-4">
                <Link to="/about-me" className={`${pathname.match('/about-me') ? 'link-active' : ''}`}>About-me</Link>
            </li>
            <li className="px-4">
                <Link to="/skill" className={`${pathname.match('/skill') ? 'link-active' : ''}`}>Skill</Link>
            </li>
            <li className="px-4">
                <Link to="/protfolio" className={`${pathname.match('/protfolio') ? 'link-active' : ''}`}>Protfolio</Link>
            </li>
            <li className="pl-4">
                <Link to="/contact" className={`${pathname.match('/contact') ? 'link-active' : ''}`}>Contact</Link>
            </li>
        </>
    );
}

export default NavItems;

--- Thanks ---

Python String and Integer concatenation

Concatenation of a string and integer is simple: just use

abhishek+str(2)

Postgresql -bash: psql: command not found

perhaps psql isn't in the PATH of the postgres user. Use the locate command to find where psql is and ensure that it's path is in the PATH for the postgres user.

How do I remove accents from characters in a PHP string?

In laravel you can simply use str_slug($accentedPhrase) and if you care about dash (-) that this method substitute with space you can use str_replace('-', ' ', str_slug($accentedPhrase))

SELECT query with CASE condition and SUM()

Use an "Or"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where (CPaymentType='Check' Or CPaymentType='Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

or an "IN"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType IN ('Check', 'Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

ViewBag, ViewData and TempData

Also the scope is different between viewbag and temptdata. viewbag is based on first view (not shared between action methods) but temptdata can be shared between an action method and just one another.

Get text of the selected option with jQuery

Also u can consider this

$('#select_2').find('option:selected').text();

which might be a little faster solution though I am not sure.

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

This is if you see Java classes in red and get this error, "Cannot resolve symbol".

If you're importing projects into IntelliJ and none of the above solutions worked for you then give this a try. This is what worked for me when everything else failed.

Go to to your project folder and rename/delete the .idea folder which has the idea settings for your project. This would have been created from your old IntelliJ version. Once you have renamed/deleted the .idea folder, import your project into IntelliJ. You should not see any errors for your Java classes now. Hope this helped.

Switch statement equivalent in Windows batch file

Compact form for short commands (no 'echo'):

IF "%ID%"=="0" ( ... & ... & ... ) ELSE ^
IF "%ID%"=="1" ( ... ) ELSE ^
IF "%ID%"=="2" ( ... ) ELSE ^
REM default case...

After ^ must be an immediate line end, no spaces.

How can I change the default Django date template format?

If you need to show short date and time (11/08/2018 03:23 a.m.) you can do it like this:

{{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}

Details for this tag here and more about dates according to the given format here

Example:

<small class="text-muted">Last updated: {{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}</small>

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

Several possiblies that causes this problem. The root cause is mismatched of compiler version between projects and IDE. For windows environment you can refer to this blog to do the detail troubleshooting.

How do I make a MySQL database run completely in memory?

Assuming you understand the consequences of using the MEMORY engine as mentioned in comments, and here, as well as some others you'll find by searching about (no transaction safety, locking issues, etc) - you can proceed as follows:

MEMORY tables are stored differently than InnoDB, so you'll need to use an export/import strategy. First dump each table separately to a file using SELECT * FROM tablename INTO OUTFILE 'table_filename'. Create the MEMORY database and recreate the tables you'll be using with this syntax: CREATE TABLE tablename (...) ENGINE = MEMORY;. You can then import your data using LOAD DATA INFILE 'table_filename' INTO TABLE tablename for each table.

Changing Node.js listening port

There is no config file unless you create one yourself. However, the port is a parameter of the listen() function. For example, to listen on port 8124:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

If you're having problems finding a port that's open, you can go to the command line and type:

netstat -ano

To see a list of all ports in use per adapter.

CSS-Only Scrollable Table with fixed headers

Only with CSS :

CSS:

tr {
  width: 100%;
  display: inline-table;
  table-layout: fixed;
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
}
tbody{
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl

Fatal error: Maximum execution time of 30 seconds exceeded

Edit php.ini

Find this line:

max_execution_time

Change its value to 300:

max_execution_time = 300

300 means 5 minutes of execution time for the http request.

How to tell which commit a tag points to in Git?

On my repository, git show-ref TAG shows the tag's hash, not the hash of the commit it points to.

git show-ref --dereference TAG shows, additionally, the commit being pointed at.

How do I turn off PHP Notices?

Use phpinfo() and search for Configuration File (php.ini) Path to see which config file path for php is used. PHP can have multiple config files depending on environment it's running. Usually, for console it's:

/etc/php5/cli/php.ini

and for php run by apache it's:

/etc/php5/apache2/php.ini

And then set error_reporting the way you need it:

http://www.phpknowhow.com/configuration/php-ini-error-settings/ http://www.zootemplate.com/news-updates/how-to-disable-notice-and-warning-in-phpini-file

Using client certificate in Curl command

TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.

If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.

As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/chainedcert.pem;  # server certificate
    ssl_certificate_key /path/to/key;          # server key

    ssl_client_certificate /path/to/ca.pem;    # client CA
    ssl_verify_client on;
    proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;

    location / {
        proxy_pass http://localhost:3000;
    }
}

How do you open an SDF file (SQL Server Compact Edition)?

Try the sql server management studio (version 2008 or earlier) from Microsoft. Download it from here. Not sure about the license, but it seems to be free if you download the EXPRESS EDITION.

You might also be able to use later editions of SSMS. For 2016, you will need to install an extension.

If you have the option you can copy the sdf file to a different machine which you are allowed to pollute with additional software.

Update: comment from Nick Westgate in nice formatting

The steps are not all that intuitive:

  1. Open SQL Server Management Studio, or if it's running select File -> Connect Object Explorer...
  2. In the Connect to Server dialog change Server type to SQL Server Compact Edition
  3. From the Database file dropdown select < Browse for more...>
  4. Open your SDF file.

Delete a row in Excel VBA

Something like this will do it:

Rows("12:12").Select
Selection.Delete

So in your code it would look like something like this:

Rows(CStr(rand) & ":" & CStr(rand)).Select
Selection.Delete

How to reset Android Studio

Windows Users: Look for C:->Users->YourUserName->.AndroidStudio or .AndroidStudioBeta folder. Delete that.

Mac Users: Delete these using the terminal (usage: rm -rf folderpath): ~/Library/Preferences/AndroidStudioBeta ~/Library/Application Support/AndroidStudioBeta ~/Library/Caches/AndroidStudioBeta ~/Library/Logs/AndroidStudioBeta

Linus Users: Delete these using the terminal (usage: rm -r folderpath): ~/.AndroidStudioBeta/config or ~/.AndroidStudio/config

Wait for all promises to resolve

The accepted answer is correct. I would like to provide an example to elaborate it a bit to those who aren't familiar with promise.

Example:

In my example, I need to replace the src attributes of img tags with different mirror urls if available before rendering the content.

var img_tags = content.querySelectorAll('img');

function checkMirrorAvailability(url) {

    // blah blah 

    return promise;
}

function changeSrc(success, y, response) {
    if (success === true) {
        img_tags[y].setAttribute('src', response.mirror_url);
    } 
    else {
        console.log('No mirrors for: ' + img_tags[y].getAttribute('src'));
    }
}

var promise_array = [];

for (var y = 0; y < img_tags.length; y++) {
    var img_src = img_tags[y].getAttribute('src');

    promise_array.push(
        checkMirrorAvailability(img_src)
        .then(

            // a callback function only accept ONE argument. 
            // Here, we use  `.bind` to pass additional arguments to the
            // callback function (changeSrc).

            // successCallback
            changeSrc.bind(null, true, y),
            // errorCallback
            changeSrc.bind(null, false, y)
        )
    );
}

$q.all(promise_array)
.then(
    function() {
        console.log('all promises have returned with either success or failure!');
        render(content);
    }
    // We don't need an errorCallback function here, because above we handled
    // all errors.
);

Explanation:

From AngularJS docs:

The then method:

then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason.

$q.all(promises)

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

The promises param can be an array of promises.

About bind(), More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

How to measure elapsed time

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

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

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

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

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

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

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

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

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

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

        endTime = System.nanoTime();

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

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

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

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

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

        stopwatch.stop(); // optional

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

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

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

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

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

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

        stopwatch.stop();    // Optional

        long timeElapsed = stopwatch.getNanoTime();

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

Byte Array to Image object

From Database.
Blob blob = resultSet.getBlob("pictureBlob");               
byte [] data = blob.getBytes( 1, ( int ) blob.length() );
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data));
} catch (IOException e) {
    e.printStackTrace();
}
drawPicture(img);  //  void drawPicture(Image img);

How to redirect stderr and stdout to different files in the same line in script?

Just add them in one line command 2>> error 1>> output

However, note that >> is for appending if the file already has data. Whereas, > will overwrite any existing data in the file.

So, command 2> error 1> output if you do not want to append.

Just for completion's sake, you can write 1> as just > since the default file descriptor is the output. so 1> and > is the same thing.

So, command 2> error 1> output becomes, command 2> error > output

Execute a PHP script from another PHP script

you can use the backtick notation:

`php file.php`;

You can also put this at the top of the php file to indicate the interpreter:

#!/usr/bin/php

Change it to where you put php. Then give execute permission on the file and you can call the file without specifying php:

`./file.php`

If you want to capture the output of the script:

$output = `./file.php`;
echo $output;

Why is datetime.strptime not working in this simple example?

If in the folder with your project you created a file with the name "datetime.py"

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

Find all IntelliJ (v15) symbols over here: https://www.jetbrains.com/idea/help/symbols.html

This site states that this icon stands for "Java class located out of the source root. Refer to the section Configuring Content Roots for details."

pip cannot install anything

I had that problem too, after I tried to reset my network settings. it solves problem.

proper hibernate annotation for byte[]

Thanks Justin, Pascal for guiding me to the right direction. I was also facing the same issue with Hibernate 3.5.3. Your research and pointers to the right classes had helped me identify the issue and do a fix.

For the benefit for those who are still stuck with Hibernate 3.5 and using oid + byte[] + @LoB combination, following is what I have done to fix the issue.

  1. I created a custom BlobType extending MaterializedBlobType and overriding the set and the get methods with the oid style access.

    public class CustomBlobType extends MaterializedBlobType {
    
    private static final String POSTGRESQL_DIALECT = PostgreSQLDialect.class.getName();
    
    /**
     * Currently set dialect.
     */
    private String dialect = hibernateConfiguration.getProperty(Environment.DIALECT);
    
    /*
     * (non-Javadoc)
     * @see org.hibernate.type.AbstractBynaryType#set(java.sql.PreparedStatement, java.lang.Object, int)
     */
    @Override
    public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
        byte[] internalValue = toInternalFormat(value);
    
        if (POSTGRESQL_DIALECT.equals(dialect)) {
            try {
    
    //I had access to sessionFactory through a custom sessionFactory wrapper.
    st.setBlob(index, Hibernate.createBlob(internalValue, sessionFactory.getCurrentSession()));
                } catch (SystemException e) {
                    throw new HibernateException(e);
                }
            } else {
                st.setBytes(index, internalValue);
            }
        }
    
    /*
     * (non-Javadoc)
     * @see org.hibernate.type.AbstractBynaryType#get(java.sql.ResultSet, java.lang.String)
     */
    @Override
    public Object get(ResultSet rs, String name) throws HibernateException, SQLException {
        Blob blob = rs.getBlob(name);
        if (rs.wasNull()) {
            return null;
        }
        int length = (int) blob.length();
        return toExternalFormat(blob.getBytes(1, length));
      }
    }
    
    1. Register the CustomBlobType with Hibernate. Following is what i did to achieve that.

      hibernateConfiguration= new AnnotationConfiguration();
      Mappings mappings = hibernateConfiguration.createMappings();
      mappings.addTypeDef("materialized_blob", "x.y.z.BlobType", null);
      

Generating random numbers in C

#include <stdlib.h>

int main()
{
    int x;
    x = rand(6);
    printf("%d", x);
}

Especially as a beginner, you should ask your compiler to print every warning about bad code that it can generate. Modern compilers know lots of different warnings which help you to program better. For example, when you compile this program with the GNU C Compiler:

$ gcc -W -Wall rand.c
rand.c: In function `main':
rand.c:5: error: too many arguments to function `rand'
rand.c:6: warning: implicit declaration of function `printf'

You get two warnings here. The first one says that the rand function only takes zero arguments, not one as you tried. To get a random number between 0 and n, you can use the expression rand() % n, which is not perfect but ok for small n. The resulting random numbers are normally not evenly distributed; smaller values are returned more often.

The second warning tells you that you are calling a function that the compiler doesn't know at that point. You have to tell the compiler by saying #include <stdio.h>. Which include files are needed for which functions is not always simple, but asking the Open Group specification for portable operating systems works in many cases: http://www.google.com/search?q=opengroup+rand.

These two warnings tell you much about the history of the C programming language. 40 years back, the definition of a function didn't include the number of parameters or the types of the parameters. It was also ok to call an unknown function, which in most cases worked. If you want to write code today, you should not rely on these old features but instead enable your compiler's warnings, understand the warnings and then fix them properly.

Delete worksheet in Excel using VBA

You could use On Error Resume Next then there is no need to loop through all the sheets in the workbook.

With On Error Resume Next the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.

Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.

Dim book
Dim sht as Worksheet

set book= Workbooks("SomeBook.xlsx")

On Error Resume Next

Application.DisplayAlerts=False 

Set sht = book.Worksheets("ID Sheet")
sht.Delete

Set sht = book.Worksheets("Summary")
sht.Delete

Application.DisplayAlerts=True 

On Error GoTo 0

Does Java read integers in little endian or big endian?

There are no unsigned integers in Java. All integers are signed and in big endian.

On the C side the each byte has tne LSB at the start is on the left and the MSB at the end.

It sounds like you are using LSB as Least significant bit, are you? LSB usually stands for least significant byte. Endianness is not bit based but byte based.

To convert from unsigned byte to a Java integer:

int i = (int) b & 0xFF;

To convert from unsigned 32-bit little-endian in byte[] to Java long (from the top of my head, not tested):

long l = (long)b[0] & 0xFF;
l += ((long)b[1] & 0xFF) << 8;
l += ((long)b[2] & 0xFF) << 16;
l += ((long)b[3] & 0xFF) << 24;