Programs & Examples On #Cp

cp is a UNIX command used to copy a file

CentOS: Copy directory to another directory

As I understand, you want to recursively copy test directory into /home/server/ path...

This can be done as:

-cp -rf /home/server/folder/test/* /home/server/

Hope this helps

How to copy a file from remote server to local machine?

The scp operation is separate from your ssh login. You will need to issue an ssh command similar to the following one assuming jdoe is account with which you log into the remote system and that the remote system is example.com:

scp [email protected]:/somedir/table /home/me/Desktop/.

The scp command issued from the system where /home/me/Desktop resides is followed by the userid for the account on the remote server. You then add a ":" followed by the directory path and file name on the remote server, e.g., /somedir/table. Then add a space and the location to which you want to copy the file. If you want the file to have the same name on the client system, you can indicate that with a period, i.e. "." at the end of the directory path; if you want a different name you could use /home/me/Desktop/newname, instead. If you were using a nonstandard port for SSH connections, you would need to specify that port with a "-P n" (capital P), where "n" is the port number. The standard port is 22 and if you aren't specifying it for the SSH connection then you won't need that.

Copy files from one directory into an existing directory

cp dir1/* dir2

Or if you have directories inside dir1 that you'd want to copy as well

cp -r dir1/* dir2

How to force cp to overwrite without confirmation

By default cp has aliase to cp -i. You can check it, type alias and you can see some like:

alias cp='cp -i'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'

To solve this problem just use /bin/cp /from /to command instead cp /from /to

How do I copy folder with files to another folder in Unix/Linux?

The option you're looking for is -R.

cp -R path_to_source path_to_destination/
  • If destination doesn't exist, it will be created.
  • -R means copy directories recursively. You can also use -r since it's case-insensitive.
  • Note the nuances with adding the trailing / as per @muni764's comment.

OS X cp command in Terminal - No such file or directory

I know this question has already been answered, but another option is simply to open the destination and source folders in Finder and then drag and drop them into the terminal. The paths will automatically be copied and properly formatted (thus negating the need to actually figure out proper file names/extensions).

I have to do over-network copies between Mac and Windows machines, sometimes fairly deep down in filetrees, and have found this the most effective way to do so.

So, as an example:

cp -r [drag and drop source folder from finder] [drag and drop destination folder from finder]

How to resolve /var/www copy/write permission denied?

First off, this has nothing to do with php. This is a unix permission issue. You need to login as a superuser ( sudo/su ) and type your password, then try that command.

$ su
(type password )
\# your command

$ sudo command
$ (type password)

It might also help if you actually specified the operating system you use.

Copy all files with a certain extension from all subdirectories

From all of the above, I came up with this version. This version also works for me in the mac recovery terminal.

find ./ -name '*.xsl' -exec cp -prv '{}' '/path/to/targetDir/' ';'

It will look in the current directory and recursively in all of the sub directories for files with the xsl extension. It will copy them all to the target directory.

cp flags are:

  • p - preserve attributes of the file
  • r - recursive
  • v - verbose (shows you whats being copied)

How to move or copy files listed by 'find' command in unix?

find /PATH/TO/YOUR/FILES -name NAME.EXT -exec cp -rfp {} /DST_DIR \;

Copy or rsync command

Rsync is better since it will only copy only the updated parts of the updated file, instead of the whole file. It also uses compression and encryption if you want. Check out this tutorial.

How to force 'cp' to overwrite directory instead of creating another one inside?

The following command ensures dotfiles (hidden files) are included in the copy:

$ cp -Rf foo/. bar

How to have the cp command create any necessary folders for copying a file to a destination

I didn't know you could do that with cp.

You can do it with mkdir ..

mkdir -p /var/path/to/your/dir

EDIT See lhunath's answer for incorporating cp.

Linux: copy and create destination dir if it does not exist

Just had the same issue. My approach was to just tar the files into an archive like so:

tar cf your_archive.tar file1 /path/to/file2 path/to/even/deeper/file3

tar automatically stores the files in the appropriate structure within the archive. If you run

tar xf your_archive.tar

the files are extracted into the desired directory structure.

How to use 'cp' command to exclude a specific directory?

Just move it temporally into a hidden directory (and rename it after, if wanted).

mkdir .hiddendir
cp * .hiddendir -R
mv .hiddendir realdirname

How can I list the scheduled jobs running in my database?

Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:

GRANT CREATE JOB TO scott;

After this statement is executed, scott can create jobs, schedules, or programs in his schema.

copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239

jQuery Scroll to Div

You can also use 'name' instead of 'href' for a cleaner url:

    $('a[name^=#]').click(function(){
    var target = $(this).attr('name');
    if (target == '#')
      $('html, body').animate({scrollTop : 0}, 600);
    else
      $('html, body').animate({
        scrollTop: $(target).offset().top - 100
    }, 600);
});

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Is Unit Testing worth the effort?

I'm agree with the point of view opposite to the majority here: It's OK Not to Write Unit Tests Especially prototype-heavy programming (AI for example) is difficult to combine with unit testing.

How to get just the parent directory name of a specific file

In Groovy:

There is no need to create a File instance to parse the string in groovy. It can be done as follows:

String path = "C:/aaa/bbb/ccc/ddd/test.java"
path.split('/')[-2]  // this will return ddd

The split will create the array [C:, aaa, bbb, ccc, ddd, test.java] and index -2 will point to entry before the last one, which in this case is ddd

Insert into ... values ( SELECT ... FROM ... )

This is another example using values with select:

INSERT INTO table1(desc, id, email) 
SELECT "Hello World", 3, email FROM table2 WHERE ...

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

For me, works this way: mvn -f /path/to/pom.xml [goals]

Access is denied when attaching a database

I found this solution: Right click on folder where you store your .mdf file --> click Properties --> choose Security tab, click Edit... and give it full control. Hope this helps!

Using Colormaps to set color of line in matplotlib

U may do as I have written from my deleted account (ban for new posts :( there was). Its rather simple and nice looking.

Im using 3-rd one of these 3 ones usually, also I wasny checking 1 and 2 version.

from matplotlib.pyplot import cm
import numpy as np

#variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
#version 1:

color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
   ax1.plot(x, y,c=c)

#or version 2: - faster and better:

color=iter(cm.rainbow(np.linspace(0,1,n)))
c=next(color)
plt.plot(x,y,c=c)

#or version 3:

color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
   c=next(color)
   ax1.plot(x, y,c=c)

example of 3:

Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

As @Sean said, fcntl() is largely standardized, and therefore available across platforms. The ioctl() function predates fcntl() in Unix, but is not standardized at all. That the ioctl() worked for you across all the platforms of relevance to you is fortunate, but not guaranteed. In particular, the names used for the second argument are arcane and not reliable across platforms. Indeed, they are often unique to the particular device driver that the file descriptor references. (The ioctl() calls used for a bit-mapped graphics device running on an ICL Perq running PNX (Perq Unix) of twenty years ago never translated to anything else anywhere else, for example.)

IntelliJ how to zoom in / out

Double click Shift to open the quick actions. Then search for "Decrease Font Size" or "Increase Font Size" and hit Enter. To repeat the action you can doubleclick Shift and Enter

I prefer that way because it works even when you're using not your own Computer without opening settings. Also works without leaving fullscreen, which is useful if you are live coding.

How to sort mongodb with pymongo

TLDR: Aggregation pipeline is faster as compared to conventional .find().sort().

Now moving to the real explanation. There are two ways to perform sorting operations in MongoDB:

  1. Using .find() and .sort().
  2. Or using the aggregation pipeline.

As suggested by many .find().sort() is the simplest way to perform the sorting.

.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])

However, this is a slow process compared to the aggregation pipeline.

Coming to the aggregation pipeline method. The steps to implement simple aggregation pipeline intended for sorting are:

  1. $match (optional step)
  2. $sort

NOTE: In my experience, the aggregation pipeline works a bit faster than the .find().sort() method.

Here's an example of the aggregation pipeline.

db.collection_name.aggregate([{
    "$match": {
        # your query - optional step
    }
},
{
    "$sort": {
        "field_1": pymongo.ASCENDING,
        "field_2": pymongo.DESCENDING,
        ....
    }
}])

Try this method yourself, compare the speed and let me know about this in the comments.

Edit: Do not forget to use allowDiskUse=True while sorting on multiple fields otherwise it will throw an error.

The order of keys in dictionaries

Python 3.7+

In Python 3.7.0 the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.

Python 3.6 (CPython)

As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default. This is considered an implementation detail though; you should still use collections.OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python.

Python >=2.7 and <3.6

Use the collections.OrderedDict class when you need a dict that remembers the order of items inserted.

Adding additional data to select options using jQuery

I made two examples from what I think your question might be:

http://jsfiddle.net/grdn4/

Check this out for storing additional values. It uses data attributes to store the other value:

http://jsfiddle.net/27qJP/1/

How to serialize an object to XML without getting xmlns="..."?

I Suggest this helper class:

public static class Xml
{
    #region Fields

    private static readonly XmlWriterSettings WriterSettings = new XmlWriterSettings {OmitXmlDeclaration = true, Indent = true};
    private static readonly XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces(new[] {new XmlQualifiedName("", "")});

    #endregion

    #region Methods

    public static string Serialize(object obj)
    {
        if (obj == null)
        {
            return null;
        }

        return DoSerialize(obj);
    }

    private static string DoSerialize(object obj)
    {
        using (var ms = new MemoryStream())
        using (var writer = XmlWriter.Create(ms, WriterSettings))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj, Namespaces);
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }

    public static T Deserialize<T>(string data)
        where T : class
    {
        if (string.IsNullOrEmpty(data))
        {
            return null;
        }

        return DoDeserialize<T>(data);
    }

    private static T DoDeserialize<T>(string data) where T : class
    {
        using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
        {
            var serializer = new XmlSerializer(typeof (T));
            return (T) serializer.Deserialize(ms);
        }
    }

    #endregion
}

:)

Generate random string/characters in JavaScript

I loved the brievety of doubletap's Math.random().toString(36).substring(7) answer, but not that it had so many collisions as hacklikecrack correctly pointed out. It generated 11-chacter strings but has a duplicate rate of 11% in a sample size of 1 million.

Here's a longer (but still short) and slower alternative that had only 133 duplicates in a sample space of 1 million. In rare cases the string will still be shorter than 11 chars:

Math.abs(Math.random().toString().split('')
    .reduce(function(p,c){return (p<<5)-p+c})).toString(36).substr(0,11);

npm ERR cb() never called

For mac users (HighSierra), do not install node using brew. It'll mess up with npm. I had to uninstall node and install using the package in the main nodejs.org source : https://nodejs.org/en/

Here's a simple guide that doesn't use brew: https://coolestguidesontheplanet.com/installing-node-js-on-macos/

How to SELECT based on value of another SELECT

If you want to SELECT based on the value of another SELECT, then you probably want a "subselect":

http://beginner-sql-tutorial.com/sql-subquery.htm

For example, (from the link above):

  1. You want the first and last names from table "student_details" ...

  2. But you only want this information for those students in "science" class:

     SELECT id, first_name
     FROM student_details
     WHERE first_name IN (SELECT first_name
     FROM student_details
     WHERE subject= 'Science'); 
    

Frankly, I'm not sure this is what you're looking for or not ... but I hope it helps ... at least a little...

IMHO...

Entity Framework - Linq query with order by and group by

Your requirements are all over the place, but this is the solution to my understanding of them:

To group by Reference property:

var refGroupQuery = (from m in context.Measurements
            group m by m.Reference into refGroup
            select refGroup);

Now you say you want to limit results by "most recent numOfEntries" - I take this to mean you want to limit the returned Measurements... in that case:

var limitedQuery = from g in refGroupQuery
                   select new
                   {
                       Reference = g.Key,
                       RecentMeasurements = g.OrderByDescending( p => p.CreationTime ).Take( numOfEntries )
                   }

To order groups by first Measurement creation time (note you should order the measurements; if you want the earliest CreationTime value, substitue "g.SomeProperty" with "g.CreationTime"):

var refGroupsOrderedByFirstCreationTimeQuery = limitedQuery.OrderBy( lq => lq.RecentMeasurements.OrderBy( g => g.SomeProperty ).First().CreationTime );

To order groups by average CreationTime, use the Ticks property of the DateTime struct:

var refGroupsOrderedByAvgCreationTimeQuery = limitedQuery.OrderBy( lq => lq.RecentMeasurements.Average( g => g.CreationTime.Ticks ) );

TSQL CASE with if comparison in SELECT statement

Please select the same in the outer select. You can't access the alias name in the same query.

SELECT *, (CASE
        WHEN articleNumber < 2 THEN 'Ama'
        WHEN articleNumber < 5 THEN 'SemiAma' 
        WHEN articleNumber < 7 THEN 'Good'  
        WHEN articleNumber < 9 THEN 'Better' 
        WHEN articleNumber < 12 THEN 'Best'
        ELSE 'Outstanding'
        END) AS ranking 
FROM(
    SELECT registrationDate, (SELECT COUNT(*) FROM Articles WHERE Articles.userId = Users.userId) as articleNumber, 
    hobbies, etc...
    FROM USERS
)x

Convert Select Columns in Pandas Dataframe to Numpy Array

the easy way is the "values" property df.iloc[:,1:].values

a=df.iloc[:,1:]
b=df.iloc[:,1:].values

print(type(df))
print(type(a))
print(type(b))

so, you can get type

<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'numpy.ndarray'>

Height equal to dynamic width (CSS fluid layout)

Simple and neet : use vw units for a responsive height/width according to the viewport width.

vw : 1/100th of the width of the viewport. (Source MDN)

DEMO

HTML:

<div></div>

CSS for a 1:1 aspect ratio:

div{
    width:80vw;
    height:80vw; /* same as width */
}

Table to calculate height according to the desired aspect ratio and width of element.

   aspect ratio  |  multiply width by
    -----------------------------------
         1:1      |         1
         1:3      |         3
         4:3      |        0.75
        16:9      |       0.5625

This technique allows you to :

  • insert any content inside the element without using position:absolute;
  • no unecessary HTML markup (only one element)
  • adapt the elements aspect ratio according to the height of the viewport using vh units
  • you can make a responsive square or other aspect ratio that alway fits in viewport according to the height and width of the viewport (see this answer : Responsive square according to width and height of viewport or this demo)

These units are supported by IE9+ see canIuse for more info

How to use AND in IF Statement

If there are no typos in the question, you got the conditions wrong:

You said this:

IF cells (i,"A") contains the text 'Miami'

...but your code says:

If Cells(i, "A") <> "Miami"

--> <> means that the value of the cell is not equal to "Miami", so you're not checking what you think you are checking.

I guess you want this instead:

If Cells(i, "A") like "*Miami*"

EDIT:

Sorry, but I can't really help you more. As I already said in a comment, I'm no Excel VBA expert.
Normally I would open Excel now and try your code myself, but I don't even have Excel on any of my machines at home (I use OpenOffice).

Just one general thing: can you identify the row that does not work?
Maybe this helps someone else to answer the question.

Does it ever execute (or at least try to execute) the Cells(i, "C").Value = "BA" line?
Or is the If Cells(i, "A") like "*Miami*" stuff already False?
If yes, try checking just one cell and see if that works.

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag

The rules for turning on the carry flag in binary/integer math are two:

  1. The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)

  2. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).

    • 0111 + 0001 = 1000 (carry flag is turned off [zero])
    • 1000 - 0001 = 0111 (carry flag is turned off [zero])

In unsigned arithmetic, watch the carry flag to detect errors.

In signed arithmetic, the carry flag tells you nothing interesting.

Overflow Flag

The rules for turning on the overflow flag in binary/integer math are two:

  1. If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)

  2. If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)

Otherwise the "overflow" flag is turned off

  • 0100 + 0001 = 0101 (overflow flag is turned off)
  • 0110 + 1001 = 1111 (overflow flag turned off)
  • 1000 + 0001 = 1001 (overflow flag turned off)
  • 1100 + 1100 = 1000 (overflow flag is turned off)

Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.

If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.

If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt

How to check if a string is numeric?

If you are allowed to use third party libraries, suggest the following.

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html

NumberUtils.isDigits(str:String):boolean
NumberUtils.isNumber(str:String):boolean

Get first and last day of month using threeten, LocalDate

The API was designed to support a solution that matches closely to business requirements

import static java.time.temporal.TemporalAdjusters.*;

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.with(firstDayOfMonth());
LocalDate end = initial.with(lastDayOfMonth());

However, Jon's solutions are also fine.

Difference between Select Unique and Select Distinct

  1. Unique was the old syntax while Distinct is the new syntax,which is now the Standard sql.
  2. Unique creates a constraint that all values to be inserted must be different from the others. An error can be witnessed if one tries to enter a duplicate value. Distinct results in the removal of the duplicate rows while retrieving data.
  3. Example: SELECT DISTINCT names FROM student ;

    CREATE TABLE Persons ( Id varchar NOT NULL UNIQUE, Name varchar(20) );

How to prevent errno 32 broken pipe?

Your server process has received a SIGPIPE writing to a socket. This usually happens when you write to a socket fully closed on the other (client) side. This might be happening when a client program doesn't wait till all the data from the server is received and simply closes a socket (using close function).

In a C program you would normally try setting to ignore SIGPIPE signal or setting a dummy signal handler for it. In this case a simple error will be returned when writing to a closed socket. In your case a python seems to throw an exception that can be handled as a premature disconnect of the client.

Hash String via SHA-256 in Java

I suppose you are using a relatively old Java Version without SHA-256. So you must add the BouncyCastle Provider to the already provided 'Security Providers' in your java version.

    // NEEDED if you are using a Java version without SHA-256    
    Security.addProvider(new BouncyCastleProvider());

    // then go as usual 
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    String text = "my string...";
    md.update(text.getBytes("UTF-8")); // or UTF-16 if needed
    byte[] digest = md.digest();

Post to another page within a PHP script

index.php

$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);

$options = ['http' => [
    'method' => 'POST',
    'header' => 'Content-type:application/json',
    'content' => $json
]];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

test.php

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

What does this format means T00:00:00.000Z?

i suggest you use moment.js for this. In moment.js you can:

var localTime = moment().format('YYYY-MM-DD'); // store localTime
var proposedDate = localTime + "T00:00:00.000Z";

now that you have the right format for a time, parse it if it's valid:

var isValidDate = moment(proposedDate).isValid();
// returns true if valid and false if it is not.

and to get time parts you can do something like:

var momentDate = moment(proposedDate)
var hour = momentDate.hours();
var minutes = momentDate.minutes();
var seconds = momentDate.seconds();

// or you can use `.format`:
console.log(momentDate.format("YYYY-MM-DD hh:mm:ss A Z"));

More info about momentjs http://momentjs.com/

Is there an "if -then - else " statement in XPath?

Somewhat simpler XPath 1.0 solution, adapted from Tomalek's (posted here) and Dimitre's (here):

concat(substring($s1, 1 div number($cond)), substring($s2, 1 div number(not($cond))))

Note: I found an explicit number() was required to convert the bool to an int otherwise some XPath evaluators threw a type mismatch error. Depending on how strict your XPath processor is type-matching you may not need it.

Find difference between timestamps in seconds in PostgreSQL

SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;

In case if someone is having an issue using extract.

What is the native keyword in Java for?

It marks a method, that it will be implemented in other languages, not in Java. It works together with JNI (Java Native Interface).

Native methods were used in the past to write performance critical sections but with Java getting faster this is now less common. Native methods are currently needed when

  • You need to call a library from Java that is written in other language.

  • You need to access system or hardware resources that are only reachable from the other language (typically C). Actually, many system functions that interact with real computer (disk and network IO, for instance) can only do this because they call native code.

See Also Java Native Interface Specification

How to have Java method return generic list of any type?

Let us have List<Object> objectList which we want to cast to List<T>

public <T> List<T> list(Class<T> c, List<Object> objectList){        
    List<T> list = new ArrayList<>();       
    for (Object o : objectList){
        T t = c.cast(o);
        list.add(t);
    }
    return list;
}

Best way to move files between S3 buckets?

The new official AWS CLI natively supports most of the functionality of s3cmd. I'd previously been using s3cmd or the ruby AWS SDK to do things like this, but the official CLI works great for this.

http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html

aws s3 sync s3://oldbucket s3://newbucket

Storing Python dictionaries

Pickle save:

try:
    import cPickle as pickle
except ImportError:  # Python 3.x
    import pickle

with open('data.p', 'wb') as fp:
    pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)

See the pickle module documentation for additional information regarding the protocol argument.

Pickle load:

with open('data.p', 'rb') as fp:
    data = pickle.load(fp)

JSON save:

import json

with open('data.json', 'w') as fp:
    json.dump(data, fp)

Supply extra arguments, like sort_keys or indent, to get a pretty result. The argument sort_keys will sort the keys alphabetically and indent will indent your data structure with indent=N spaces.

json.dump(data, fp, sort_keys=True, indent=4)

JSON load:

with open('data.json', 'r') as fp:
    data = json.load(fp)

How to revert to origin's master branch's version of file

I've faced same problem and came across to this thread but my problem was with upstream. Below git command worked for me.

Syntax

git checkout {remoteName}/{branch} -- {../path/file.js}

Example

git checkout upstream/develop -- public/js/index.js

How can I take a screenshot/image of a website using Python?

can do using Selenium

from selenium import webdriver

DRIVER = 'chromedriver'
driver = webdriver.Chrome(DRIVER)
driver.get('https://www.spotify.com')
screenshot = driver.save_screenshot('my_screenshot.png')
driver.quit()

https://sites.google.com/a/chromium.org/chromedriver/getting-started

How to get "GET" request parameters in JavaScript?

A map-reduce solution:

var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) {
        return paramPair.split(/=(.+)?/).slice(0, 2);
    }).reduce(function (obj, pairArray) {            
        obj[pairArray[0]] = pairArray[1];
        return obj;
    }, {});

Usage:

For url: http://example.com?one=1&two=2
console.log(urlParams.one) // 1
console.log(urlParams.two) // 2

How to remove html special chars?

If you want to convert the HTML special characters and not just remove them as well as strip things down and prepare for plain text this was the solution that worked for me...

function htmlToPlainText($str){
    $str = str_replace('&nbsp;', ' ', $str);
    $str = html_entity_decode($str, ENT_QUOTES | ENT_COMPAT , 'UTF-8');
    $str = html_entity_decode($str, ENT_HTML5, 'UTF-8');
    $str = html_entity_decode($str);
    $str = htmlspecialchars_decode($str);
    $str = strip_tags($str);

    return $str;
}

$string = '<p>this is (&nbsp;) a test</p>
<div>Yes this is! &amp; does it get "processed"? </div>'

htmlToPlainText($string);
// "this is ( ) a test. Yes this is! & does it get processed?"`

html_entity_decode w/ ENT_QUOTES | ENT_XML1 converts things like &#39; htmlspecialchars_decode converts things like &amp; html_entity_decode converts things like '&lt; and strip_tags removes any HTML tags left over.

EDIT - Added str_replace(' ', ' ', $str); and several other html_entity_decode() as continued testing has shown a need for them.

Spring JPA @Query with LIKE

For your case, you can directly use JPA methods. That is like bellow:

Containing: select ... like %:username%

List<User> findByUsernameContainingIgnoreCase(String username);

here, IgnoreCase will help you to search item with ignoring the case.

Here are some related methods:

  1. Like findByFirstnameLike

    … where x.firstname like ?1

  2. StartingWith findByFirstnameStartingWith

    … where x.firstname like ?1 (parameter bound with appended %)

  3. EndingWith findByFirstnameEndingWith

    … where x.firstname like ?1 (parameter bound with prepended %)

  4. Containing findByFirstnameContaining

    … where x.firstname like ?1 (parameter bound wrapped in %)

More info , view this link and this link

Hope this will help you :)

Django {% with %} tags within {% if %} {% else %} tags?

Like this:

{% if age > 18 %}
    {% with patient as p %}
    <my html here>
    {% endwith %}
{% else %}
    {% with patient.parent as p %}
    <my html here>
    {% endwith %}
{% endif %}

If the html is too big and you don't want to repeat it, then the logic would better be placed in the view. You set this variable and pass it to the template's context:

p = (age > 18 && patient) or patient.parent

and then just use {{ p }} in the template.

How to generate gcc debug symbol outside the build target?

No answer so far mentions eu-strip --strip-debug -f <out.debug> <input>.

  • This is provided by elfutils package.
  • The result will be that <input> file has been stripped of debug symbols which are now all in <out.debug>.

upgade python version using pip

pip is designed to upgrade python packages and not to upgrade python itself. pip shouldn't try to upgrade python when you ask it to do so.

Don't type pip install python but use an installer instead.

npm install error - unable to get local issuer certificate

Anyone gets this error when 'npm install' is trying to fetch a package from HTTPS server with a self-signed or invalid certificate.

Quick and insecure solution:

npm config set strict-ssl false

Why this solution is insecure? The above command tells npm to connect and fetch module from server even server do not have valid certificate and server identity is not verified. So if there is a proxy server between npm client and actual server, it provided man in middle attack opportunity to an intruder.

Secure solution:

If any module in your package.json is hosted on a server with self-signed CA certificate then npm is unable to identify that server with an available system CA certificates. So you need to provide CA certificate for server validation with the explicit configuration in .npmrc. In .npmrc you need to provide cafile, please refer more detail about cafile configuration here

cafile=./ca-certs.pem

In ca-certs file, you can add any number of CA certificates(public) that you required to identify servers. The certificate should be in “Base-64 encoded X.509 (.CER)(PEM)” format.

For example,

# cat ca-certs.pem 
DigiCert Global Root CA
=======================
-----BEGIN CERTIFICATE-----
CAUw7C29C79Fv1C5qfPrmAE.....
-----END CERTIFICATE-----

VeriSign Class 3 Public Primary Certification Authority - G5
========================================
-----BEGIN CERTIFICATE-----
MIIE0zCCA7ugAwIBAgIQ......
-----END CERTIFICATE-----

Note: once you provide cafile configuration in .npmrc, npm try to identify all server using CA certificate(s) provided in cafile only, it won't check system CA certificate bundles then. If someone wants all well-known public CA authority certificat bundle then can get from here.

One other situation when you get this error:

If you have mentioned Git URL as a dependency in package.json and git is on invalid/self-signed certificate then also npm throws a similar error. You can fix it with following configuration for git client

git config --global http.sslVerify false 

Looping through a Scripting.Dictionary using index/item number

According to the documentation of the Item property:

Sets or returns an item for a specified key in a Dictionary object.

In your case, you don't have an item whose key is 1 so doing:

s = d.Item(i)

actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem argument.

The Dictionary also has the Items method which allows looping over the indices:

a = d.Items
For i = 0 To d.Count - 1
    s = a(i)
Next i

Mock a constructor with parameter

To my knowledge, you can't mock constructors with mockito, only methods. But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class. then you can mock out that method. Below is an excerpt directly from the Mockito wiki:

Pattern 1 - using one-line methods for object creation

To use pattern 1 (testing a class called MyClass), you would replace a call like

   Foo foo = new Foo( a, b, c );

with

   Foo foo = makeFoo( a, b, c );

and write a one-line method

   Foo makeFoo( A a, B b, C c ) { 
        return new Foo( a, b, c );
   }

It's important that you don't include any logic in the method; just the one line that creates the object. The reason for this is that the method itself is never going to be unit tested.

When you come to test the class, the object that you test will actually be a Mockito spy, with this method overridden, to return a mock. What you're testing is therefore not the class itself, but a very slightly modified version of it.

Your test class might contain members like

  @Mock private Foo mockFoo;
  private MyClass toTest = spy(new MyClass());

Lastly, inside your test method you mock out the call to makeFoo with a line like

  doReturn( mockFoo )
      .when( toTest )
      .makeFoo( any( A.class ), any( B.class ), any( C.class ));

You can use matchers that are more specific than any() if you want to check the arguments that are passed to the constructor.

If you're just wanting to return a mocked object of your class I think this should work for you. In any case you can read more about mocking object creation here:

http://code.google.com/p/mockito/wiki/MockingObjectCreation

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

you just need to reset dependencies in app.gradle file like old one as

androidTestImplementation 'com.android.support.test:runner:0.5'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'

to new one as

androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

How to set my default shell on Mac?

heimdall:~ leeg$ dscl
Entering interactive mode... (type "help" for commands)
 > cd /Local/Default/Users/
/Local/Default/Users > read <<YOUR_USER>>
[...]
UserShell: /bin/bash
/Local/Default/Users >

just change that value (with the write command in dscl).

SQL select everything in an array

// array of $ids that you need to select
$ids = array('1', '2', '3', '4', '5', '6', '7', '8');

// create sql part for IN condition by imploding comma after each id
$in = '(' . implode(',', $ids) .')';

// create sql
$sql = 'SELECT * FROM products WHERE catid IN ' . $in;

// see what you get
var_dump($sql);

Update: (a short version and update missing comma)

$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';

"register" keyword in C?

Actually, register tells the compiler that the variable does not alias with anything else in the program (not even char's).

That can be exploited by modern compilers in a variety of situations, and can help the compiler quite a bit in complex code - in simple code the compilers can figure this out on their own.

Otherwise, it serves no purpose and is not used for register allocation. It does not usually incur performance degradation to specify it, as long as your compiler is modern enough.

expected constructor, destructor, or type conversion before ‘(’ token

The first constructor in the header should not end with a semicolon. #include <string> is missing in the header. string is not qualified with std:: in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream is broken. I suggest learning C++ before trying to use it.

Let's fix this up:

//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

#include <iostream>
#include <string>    

class Polygone {
public:
  // declarations have to end with a semicolon, definitions do not
  Polygone(){} // why would we needs this?
  Polygone(const std::string& fichier);
};

# endif

and

//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>


Polygone::Polygone(const std::string& nom)
{
  std::ifstream fichier (nom, ios::in);


  if (fichier.is_open())
  {
    // keep the scope as tiny as possible
    std::string line;
    // getline returns the stream and streams convert to booleans
    while ( std::getline(fichier, line) )
    {
      std::cout << line << std::endl;
    }
  }
  else
  {
    std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
  }
}

What is the syntax for Typescript arrow functions with generics?

In case you'd like to do it with async:

const request = async <T>(param1: string, param2: number) => {
  const res = await func();
  return res.response() as T;
}

And a more complex pattern, in case you'd like to wrap your function inside a generic counterpart, such as memoization (Example uses fast-memoize):

const request = memoize(
  async <T>(
    url: string,
    token?: string
  ) => {
    // Perform your code here
  }
);

See how you define the generic after the memoizing function.

How to backup a local Git repository?

You can backup the git repo with git-copy . git-copy saved new project as a bare repo, it means minimum storage cost.

git copy /path/to/project /backup/project.backup

Then you can restore your project with git clone

git clone /backup/project.backup project

Get the IP address of the machine

I like jjvainio's answer. As Zan Lnyx says, it uses the local routing table to find the IP address of the ethernet interface that would be used for a connection to a specific external host. By using a connected UDP socket, you can get the information without actually sending any packets. The approach requires that you choose a specific external host. Most of the time, any well-known public IP should do the trick. I like Google's public DNS server address 8.8.8.8 for this purpose, but there may be times you'd want to choose a different external host IP. Here is some code that illustrates the full approach.

void GetPrimaryIp(char* buffer, size_t buflen) 
{
    assert(buflen >= 16);

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    assert(sock != -1);

    const char* kGoogleDnsIp = "8.8.8.8";
    uint16_t kDnsPort = 53;
    struct sockaddr_in serv;
    memset(&serv, 0, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_addr.s_addr = inet_addr(kGoogleDnsIp);
    serv.sin_port = htons(kDnsPort);

    int err = connect(sock, (const sockaddr*) &serv, sizeof(serv));
    assert(err != -1);

    sockaddr_in name;
    socklen_t namelen = sizeof(name);
    err = getsockname(sock, (sockaddr*) &name, &namelen);
    assert(err != -1);

    const char* p = inet_ntop(AF_INET, &name.sin_addr, buffer, buflen);
    assert(p);

    close(sock);
}

Open file with associated application

This is an old thread but just in case anyone comes across it like I did. pi.FileName needs to be set to the file name (and possibly full path to file ) of the executable you want to use to open your file. The below code works for me to open a video file with VLC.

var path = files[currentIndex].fileName;
var pi = new ProcessStartInfo(path)
{
    Arguments = Path.GetFileName(path),
    UseShellExecute = true,
    WorkingDirectory = Path.GetDirectoryName(path),
    FileName = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe",
    Verb = "OPEN"
};
Process.Start(pi)

Tigran's answer works but will use windows' default application to open your file, so using ProcessStartInfo may be useful if you want to open the file with an application that is not the default.

Get HTML code using JavaScript with a URL

First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).

In PHP, this is how you do it:

file_get_contents($theUrl);

In javascript, there is three ways :

Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/

var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
    if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);

Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/

var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
    alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);

Thirdly, by jQuery : [http://jsfiddle.net/edggD/2/

$.get('../edggD',function(data)//Remember, same domain
{
    alert(data);
});

]4

RecyclerView - How to smooth scroll to top of item on a certain position?

I have create an extension method based on position of items in a list which is bind with recycler view

Smooth scroll in large list takes longer time to scroll , use this to improve speed of scrolling and also have the smooth scroll animation. Cheers!!

fun RecyclerView?.perfectScroll(size: Int,up:Boolean = true ,smooth: Boolean = true) {
this?.apply {
    if (size > 0) {
        if (smooth) {
            val minDirectScroll = 10 // left item to scroll
            //smooth scroll
            if (size > minDirectScroll) {
                //scroll directly to certain position
                val newSize = if (up) minDirectScroll else size - minDirectScroll
                //scroll to new position
                val newPos = newSize  - 1
                //direct scroll
                scrollToPosition(newPos)
                //smooth scroll to rest
                perfectScroll(minDirectScroll, true)

            } else {
                //direct smooth scroll
                smoothScrollToPosition(if (up) 0 else size-1)
            }
        } else {
            //direct scroll
            scrollToPosition(if (up) 0 else size-1)
        }
    }
} }

Just call the method anywhere using

rvList.perfectScroll(list.size,up=true,smooth=true)

jQuery selector for id starts with specific text

Let me offer a more extensive answer considering things that you haven't mentioned as yet but will find useful.

For your current problem the answer is

$("div[id^='editDialog']");

The caret (^) is taken from regular expressions and means starts with.

Solution 1

// Select elems where 'attribute' ends with 'Dialog'
$("[attribute$='Dialog']"); 

// Selects all divs where attribute is NOT equal to value    
$("div[attribute!='value']"); 

// Select all elements that have an attribute whose value is like
$("[attribute*='value']"); 

// Select all elements that have an attribute whose value has the word foobar
$("[attribute~='foobar']"); 

// Select all elements that have an attribute whose value starts with 'foo' and ends
//  with 'bar'
$("[attribute^='foo'][attribute$='bar']");

attribute in the code above can be changed to any attribute that an element may have, such as href, name, id or src.

Solution 2

Use classes

// Matches all items that have the class 'classname'
$(".className");

// Matches all divs that have the class 'classname'
$("div.className");

Solution 3

List them (also noted in previous answers)

$("#id1,#id2,#id3");

Solution 4

For when you improve, regular expression (Never actually used these, solution one has always been sufficient, but you never know!

// Matches all elements whose id takes the form editDialog-{one_or_more_integers}
$('div').filter(function () {this.id.match(/editDialog\-\d+/)});

How to handle floats and decimal separators with html5 input type number

Use valueAsNumber instead of .val().

input . valueAsNumber [ = value ]

Returns a number representing the form control's value, if applicable; otherwise, returns null.
Can be set, to change the value.
Throws an INVALID_STATE_ERR exception if the control is neither date- or time-based nor numeric.

How can I truncate a double to only two decimal places in Java?

If, for whatever reason, you don't want to use a BigDecimal you can cast your double to an int to truncate it.

If you want to truncate to the Ones place:

  • simply cast to int

To the Tenths place:

  • multiply by ten
  • cast to int
  • cast back to double
  • and divide by ten.

Hundreths place

  • multiply and divide by 100 etc.

Example:

static double truncateTo( double unroundedNumber, int decimalPlaces ){
    int truncatedNumberInt = (int)( unroundedNumber * Math.pow( 10, decimalPlaces ) );
    double truncatedNumber = (double)( truncatedNumberInt / Math.pow( 10, decimalPlaces ) );
    return truncatedNumber;
}

In this example, decimalPlaces would be the number of places PAST the ones place you wish to go, so 1 would round to the tenths place, 2 to the hundredths, and so on (0 rounds to the ones place, and negative one to the tens, etc.)

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

I haven't worked much with phones, so I dont't know if this would work. But just from a html/javascript point of view, you could just open a different url depending on what the user's device is?

<a style="cursor: pointer;" onclick="myNavFunc()">Take me there!</a>

function myNavFunc(){
    // If it's an iPhone..
    if( (navigator.platform.indexOf("iPhone") != -1) 
        || (navigator.platform.indexOf("iPod") != -1)
        || (navigator.platform.indexOf("iPad") != -1))
         window.open("maps://www.google.com/maps/dir/?api=1&travelmode=driving&layer=traffic&destination=[YOUR_LAT],[YOUR_LNG]");
    else
         window.open("https://www.google.com/maps/dir/?api=1&travelmode=driving&layer=traffic&destination=[YOUR_LAT],[YOUR_LNG]");
}

How to get a user's time zone?

NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];

The name will be something like "Australia/Sydney", or "Europe/Lisbon".

Since it sounds like you might only care about the continent, that might be all you need.

How to add a Hint in spinner in XML

make your hint at final position in your string array like this City is the hint here

array_city = new String[]{"Irbed", "Amman", "City"};

and then in your array adapter

ArrayAdapter<String> adapter_city = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, array_city) {
            @Override
            public int getCount() {
                // to show hint "Select Gender" and don't able to select
                return array_city.length-1;
            }
        };

so the adapter return just first two item and finally in onCreate() method or what ,,, make Spinner select the hint

yourSpinner.setSelection(array_city.length - 1);

ASP.NET custom error page - Server.GetLastError() is null

Try using something like Server.Transfer("~/ErrorPage.aspx"); from within the Application_Error() method of global.asax.cs

Then from within Page_Load() of ErrorPage.aspx.cs you should be okay to do something like: Exception exception = Server.GetLastError().GetBaseException();

Server.Transfer() seems to keep the exception hanging around.

Updating the value of data attribute using jQuery

I want to change the width and height of a div. data attributes did not change it. Instead I use:

var size = $("#theme_photo_size").val().split("x");
$("#imageupload_img").width(size[0]);
$("#imageupload_img").attr("data-width", size[0]);
$("#imageupload_img").height(size[1]);
$("#imageupload_img").attr("data-height", size[1]);

be careful:

$("#imageupload_img").data("height", size[1]); //did not work

did not set it

$("#imageupload_img").attr("data-height", size[1]); // yes it worked!

this has set it.

Get the year from specified date php

I would use this:

$parts = explode('-', '2068-06-15');
echo $parts[0];

It appears the date is coming from a source where it is always the same, much quicker this way using explode.

$watch an object

you must changes in $watch ....

_x000D_
_x000D_
function MyController($scope) {_x000D_
    $scope.form = {_x000D_
        name: 'my name',_x000D_
    }_x000D_
_x000D_
    $scope.$watch('form.name', function(newVal, oldVal){_x000D_
        console.log('changed');_x000D_
     _x000D_
    });_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>_x000D_
<div ng-app>_x000D_
    <div ng-controller="MyController">_x000D_
        <label>Name:</label> <input type="text" ng-model="form.name"/>_x000D_
            _x000D_
        <pre>_x000D_
            {{ form }}_x000D_
        </pre>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Constructor in an Interface?

This is because interfaces do not allow to define the method body in it.but we should have to define the constructor in the same class as interfaces have by default abstract modifier for all the methods to define. That's why we can not define constructor in the interfaces.

PHP code to get selected text of a combo box

Try with this. You will get the select box value in $_POST['Make'] and name will get in $_POST['selected_text']

<form method="POST" >
<label for="Manufacturer"> Manufacturer : </label>
  <select id="cmbMake" name="Make"     onchange="document.getElementById('selected_text').value=this.options[this.selectedIndex].text">
     <option value="0">Select Manufacturer</option>
     <option value="1">--Any--</option>
     <option value="2">Toyota</option>
     <option value="3">Nissan</option>
</select>
<input type="hidden" name="selected_text" id="selected_text" value="" />
<input type="submit" name="search" value="Search"/>
</form>


 <?php

if(isset($_POST['search']))
{

    $makerValue = $_POST['Make']; // make value

    $maker = mysql_real_escape_string($_POST['selected_text']); // get the selected text
    echo $maker;
}
 ?>

Calling startActivity() from outside of an Activity?

Sometimes this error can occur without an explicit call to startActivity(...). For example, some of you may have seen a stack trace like this in Crashlytics:

Fatal Exception: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
       at android.app.ContextImpl.startActivity(ContextImpl.java:1597)
       at android.app.ContextImpl.startActivity(ContextImpl.java:1584)
       at android.content.ContextWrapper.startActivity(ContextWrapper.java:337)
       at android.text.style.URLSpan.onClick(URLSpan.java:62)
       at android.text.method.LinkMovementMethod.onTouchEvent(LinkMovementMethod.java:217)
       at android.widget.TextView.onTouchEvent(TextView.java:9522)
       at android.view.View.dispatchTouchEvent(View.java:8968)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.widget.AbsListView.dispatchTouchEvent(AbsListView.java:5303)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2709)
       at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2425)
       at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2559)
       at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1767)
       at android.app.Activity.dispatchTouchEvent(Activity.java:2866)
       at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
       at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
       at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2520)
       at android.view.View.dispatchPointerEvent(View.java:9173)
       at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4706)
       at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4544)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4068)
       at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4121)
       at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4087)
       at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4201)
       at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4095)
       at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4258)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4068)
       at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4121)
       at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4087)
       at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4095)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4068)
       at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6564)
       at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6454)
       at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6425)
       at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6654)
       at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
       at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
       at android.os.MessageQueue.next(MessageQueue.java:143)
       at android.os.Looper.loop(Looper.java:130)
       at android.app.ActivityThread.main(ActivityThread.java:5942)
       at java.lang.reflect.Method.invoke(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

And you may wonder what you did wrong, since the trace only includes framework code. Well, here's an example of how this can happen. Let's say we're in a fragment.

Activity activity = getActivity();
Context activityContext = activity;
Context appContext = activityContext.getApplicationContext();
LayoutInflater inflater = LayoutInflater.from(appContext); // whoops!
View view = inflater.inflate(R.layout.some_layout, parent, false);
TextView tvWithLinks = (TextView) view.findViewById(R.id.tv_with_links);

tvWithLinks.setMovementMethod(LinkMovementMethod.getInstance()); // whoops!!

Now, when a user clicks on that text view, your app will crash with the stack trace above. This is because the layout inflater has a reference to the application context, and so therefore your text view has an application context. Clicking on that text view implicitly calls appContext.startActivity(...).

Final note: I tested this on Android 4, 5, 6, and 7 devices. It only affects 4, 5, and 6. Android 7 devices apparently have no trouble calling appContext.startActivity(...).

I hope this helps someone else!

Docker - Container is not running

Here's a solution when the docker container exits normally and you can edit the Dockerfile.

Generally, when a docker container is run, an application is served by running a command. From the Dockerfile reference,

Both CMD and ENTRYPOINT instructions define what command gets executed when running a container. ... Dockerfile should specify at least one of CMD or ENTRYPOINT commands.

When you build a image and not specify any command with CMD or ENTRYPOINT, the base image's CMD or ENTRYPOINT command would be executed.

For example, the Official Ubuntu Dockerfile has CMD ["/bin/bash"] (https://hub.docker.com/_/ubuntu). Now, the bin/bash/ command can accept input and docker run -it IMAGE_ID command attaches STDIN to the container. The result is that you get an interactive terminal and the container keeps running.

When a command with CMD or ENTRYPOINT is specified in the Dockerfile, this command gets executed when running the container. Now, if this command can finish without requiring any input, it will finish and the container will exit. docker run -it IMAGE_ID will NOT provide the interactive terminal in this case. An example would be the docker image built from the Dockerfile below-

FROM ubuntu
ENTRYPOINT echo hello 

If you need to go to the terminal of this image, you will need to keep the container running by modifying the entrypoint command.

FROM ubuntu
ENTRYPOINT echo hello && sleep infinity 

After running the container normally with docker run IMAGE_ID, you can just go to another terminal and use docker exec -it CONTAINER_ID bash to get the container's terminal.

How can I get a collection of keys in a JavaScript dictionary?

A different approach would be to using multi-dimensional arrays:

var driversCounter = [
    ["one", 1], 
    ["two", 2], 
    ["three", 3], 
    ["four", 4], 
    ["five", 5]
]

and access the value by driverCounter[k][j], where j=0,1 in the case.
Add it in a drop down list by:

var dd = document.getElementById('your_dropdown_element');
for(i=0;i<driversCounter.length-1;i++)
{
    dd.options.add(opt);
    opt.text = driversCounter[i][0];
    opt.value = driversCounter[i][1];
}

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

Use header to modify the HTTP header:

header('Content-Type: text/html; charset=utf-8');

Note to call this function before any output has been sent to the client. Otherwise the header has been sent too and you obviously can’t change it any more. You can check that with headers_sent. See the manual page of header for more information.

Reloading module giving NameError: name 'reload' is not defined

For >= Python3.4:

import importlib
importlib.reload(module)

For <= Python3.3:

import imp
imp.reload(module)

For Python2.x:

Use the in-built reload() function.

reload(module)

Is there a better way to run a command N times in bash?

For loops are probably the right way to do it, but here is a fun alternative:

echo -e {1..10}"\n" |xargs -n1 some_command

If you need the iteration number as a parameter for your invocation, use:

echo -e {1..10}"\n" |xargs -I@ echo now I am running iteration @

Edit: It was rightly commented that the solution given above would work smoothly only with simple command runs (no pipes, etc.). you can always use a sh -c to do more complicated stuff, but not worth it.

Another method I use typically is the following function:

rep() { s=$1;shift;e=$1;shift; for x in `seq $s $e`; do c=${@//@/$x};sh -c "$c"; done;}

now you can call it as:

rep 3 10 echo iteration @

The first two numbers give the range. The @ will get translated to the iteration number. Now you can use this with pipes too:

rep 1 10 "ls R@/|wc -l"

with give you the number of files in directories R1 .. R10.

Undefined or null for AngularJS

Why not simply use angular.isObject with negation? e.g.

if (!angular.isObject(obj)) {
    return;
}

Rename Excel Sheet with VBA Macro

Suggest you add handling to test if any of the sheets to be renamed already exist:

Sub Test()

Dim ws As Worksheet
Dim ws1 As Worksheet
Dim strErr As String

On Error Resume Next
For Each ws In ActiveWorkbook.Sheets
Set ws1 = Sheets(ws.Name & "_v1")
    If ws1 Is Nothing Then
        ws.Name = ws.Name & "_v1"
    Else
         strErr = strErr & ws.Name & "_v1" & vbNewLine
    End If
Set ws1 = Nothing
Next
On Error GoTo 0

If Len(strErr) > 0 Then MsgBox strErr, vbOKOnly, "these sheets already existed"

End Sub

RSpec: how to test if a method was called?

In the new rspec expect syntax this would be:

expect(subject).to receive(:bar).with("an argument I want")

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

I have changed in my activity but effected. Here is my code:

View layout = getLayoutInflater().inflate(R.layout.list_group,null);
        try {
            LinearLayout linearLayout = (LinearLayout) layout.findViewById(R.id.ldrawernav);
            linearLayout.setBackgroundColor(Color.parseColor("#ffffff"));
        }
        catch (Exception e) {

        }

    }

Java converting int to hex and back again

Try using BigInteger class, it works.

int Val=-32768;
String Hex=Integer.toHexString(Val);

//int FirstAttempt=Integer.parseInt(Hex,16); // Error "Invalid Int"
//int SecondAttempt=Integer.decode("0x"+Hex);  // Error "Invalid Int"
BigInteger i = new BigInteger(Hex,16);
System.out.println(i.intValue());

ORA-01861: literal does not match format string

Just before executing the query: alter session set NLS_DATE_FORMAT = "DD.MM.YYYY HH24:MI:SS"; or whichever format you are giving the information to the date function. This should fix the ORA error

Rails params explained?

On the Rails side, params is a method that returns an ActionController::Parameters object. See https://stackoverflow.com/a/44070358/5462485

How do I enable index downloads in Eclipse for Maven dependency search?

Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories, and it should work.

The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.

How to check if input date is equal to today's date?

Try using moment.js

moment('dd/mm/yyyy').isSame(Date.now(), 'day');

You can replace 'day' string with 'year, month, minute' if you want.

"Could not find acceptable representation" using spring-boot-starter-web

accepted answer is not right with Spring 5. try changing your URL of your web service to .json! that is the right fix. great details here http://stick2code.blogspot.com/2014/03/solved-orgspringframeworkwebhttpmediaty.html

How to round a number to n decimal places in Java

@Milhous: the decimal format for rounding is excellent:

You can also use the

DecimalFormat df = new DecimalFormat("#.00000");
df.format(0.912385);

to make sure you have the trailing 0's.

I would add that this method is very good at providing an actual numeric, rounding mechanism - not only visually, but also when processing.

Hypothetical: you have to implement a rounding mechanism into a GUI program. To alter the accuracy / precision of a result output simply change the caret format (i.e. within the brackets). So that:

DecimalFormat df = new DecimalFormat("#0.######");
df.format(0.912385);

would return as output: 0.912385

DecimalFormat df = new DecimalFormat("#0.#####");
df.format(0.912385);

would return as output: 0.91239

DecimalFormat df = new DecimalFormat("#0.####");
df.format(0.912385);

would return as output: 0.9124

[EDIT: also if the caret format is like so ("#0.############") and you enter a decimal, e.g. 3.1415926, for argument's sake, DecimalFormat does not produce any garbage (e.g. trailing zeroes) and will return: 3.1415926 .. if you're that way inclined. Granted, it's a little verbose for the liking of some dev's - but hey, it's got a low memory footprint during processing and is very easy to implement.]

So essentially, the beauty of DecimalFormat is that it simultaneously handles the string appearance - as well as the level of rounding precision set. Ergo: you get two benefits for the price of one code implementation. ;)

Start ssh-agent on login

Add this to your ~/.bashrc, then logout and back in to take effect.

if [ ! -S ~/.ssh/ssh_auth_sock ]; then
  eval `ssh-agent`
  ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
fi
export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
ssh-add -l > /dev/null || ssh-add

This should only prompt for a password the first time you login after each reboot. It will keep reusing the same ssh-agent as long as it stays running.

Javascript : array.length returns undefined

It looks as though it's not an array but an arbitrary object. If you have control over the PHP serialization, you might be able to change that.

As raina77ow pointed out, one way to do this in PHP would be by replacing something like this:

json_encode($something) 

with something like:

json_encode(array_values($something))

But don't ignore the other answers here about Object.keys. They should also accomplish what you want if you don't have the ability or the desire to change the serialization of your object.

glob exclude pattern

You can use the below method:

# Get all the files
allFiles = glob.glob("*")
# Files starting with eph
ephFiles = glob.glob("eph*")
# Files which doesnt start with eph
noephFiles = []
for file in allFiles:
    if file not in ephFiles:
        noephFiles.append(file)
# noepchFiles has all the file which doesnt start with eph.

Thank you.  

how to start stop tomcat server using CMD?

You can use the following command c:\path of you tomcat directory\bin>catalina run

How to convert minutes to Hours and minutes (hh:mm) in java

int mHours = t / 60; //since both are ints, you get an int
int mMinutes = t % 60;
System.out.printf("%d:%02d", "" +mHours, "" +mMinutes);

Which characters make a URL invalid?

To add some clarification and directly address the question above, there are several classes of characters that cause problems for URLs and URIs.

There are some characters that are disallowed and should never appear in a URL/URI, reserved characters (described below), and other characters that may cause problems in some cases, but are marked as "unwise" or "unsafe". Explanations for why the characters are restricted are clearly spelled out in RFC-1738 (URLs) and RFC-2396 (URIs). Note the newer RFC-3986 (update to RFC-1738) defines the construction of what characters are allowed in a given context but the older spec offers a simpler and more general description of which characters are not allowed with the following rules.

Excluded US-ASCII Characters disallowed within the URI syntax:

   control     = <US-ASCII coded characters 00-1F and 7F hexadecimal>
   space       = <US-ASCII coded character 20 hexadecimal>
   delims      = "<" | ">" | "#" | "%" | <">

The character "#" is excluded because it is used to delimit a URI from a fragment identifier. The percent character "%" is excluded because it is used for the encoding of escaped characters. In other words, the "#" and "%" are reserved characters that must be used in a specific context.

List of unwise characters are allowed but may cause problems:

   unwise      = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"

Characters that are reserved within a query component and/or have special meaning within a URI/URL:

  reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","

The "reserved" syntax class above refers to those characters that are allowed within a URI, but which may not be allowed within a particular component of the generic URI syntax. Characters in the "reserved" set are not reserved in all contexts. The hostname, for example, can contain an optional username so it could be something like ftp://user@hostname/ where the '@' character has special meaning.

Here is an example of a URL that has invalid and unwise characters (e.g. '$', '[', ']') and should be properly encoded:

http://mw1.google.com/mw-earth-vectordb/kml-samples/gp/seattle/gigapxl/$[level]/r$[y]_c$[x].jpg

Some of the character restrictions for URIs and URLs are programming language-dependent. For example, the '|' (0x7C) character although only marked as "unwise" in the URI spec will throw a URISyntaxException in the Java java.net.URI constructor so a URL like http://api.google.com/q?exp=a|b is not allowed and must be encoded instead as http://api.google.com/q?exp=a%7Cb if using Java with a URI object instance.

How to apply filters to *ngFor?

This is your array

products: any = [
        {
            "name": "John-Cena",
                    },
        {
            "name": "Brock-Lensar",

        }
    ];

This is your ngFor loop Filter By :

<input type="text" [(ngModel)]='filterText' />
    <ul *ngFor='let product of filterProduct'>
      <li>{{product.name }}</li>
    </ul>

There I'm using filterProduct instant of products, because i want to preserve my original data. Here model _filterText is used as a input box.When ever there is any change setter function will call. In setFilterText performProduct is called it will return the result only those who match with the input. I'm using lower case for case insensitive.

filterProduct = this.products;
_filterText : string;
    get filterText() : string {
        return this._filterText;
    }

    set filterText(value : string) {
        this._filterText = value;
        this.filterProduct = this._filterText ? this.performProduct(this._filterText) : this.products;

    } 

    performProduct(value : string ) : any {
            value = value.toLocaleLowerCase();
            return this.products.filter(( products : any ) => 
                products.name.toLocaleLowerCase().indexOf(value) !== -1);
        }

Convert a SQL Server datetime to a shorter date format

Just add date keyword. E.g. select date(orderdate),count(1) from orders where orderdate > '2014-10-01' group by date(orderdate);

orderdate is in date time. This query will show the orders for that date rather than datetime.

Date keyword applied on a datetime column will change it to short date.

Customizing Bootstrap CSS template

The best option in my opinion is to compile a custom LESS file including bootstrap.less, a custom variables.less file and your own rules :

  1. Clone bootstrap in your root folder : git clone https://github.com/twbs/bootstrap.git
  2. Rename it "bootstrap"
  3. Create a package.json file : https://gist.github.com/jide/8440609
  4. Create a Gruntfile.js : https://gist.github.com/jide/8440502
  5. Create a "less" folder
  6. Copy bootstrap/less/variables.less into the "less" folder
  7. Change the font path : @icon-font-path: "../bootstrap/fonts/";
  8. Create a custom style.less file in the "less" folder which imports bootstrap.less and your custom variables.less file : https://gist.github.com/jide/8440619
  9. Run npm install
  10. Run grunt watch

Now you can modify the variables any way you want, override bootstrap rules in your custom style.less file, and if some day you want to update bootstrap, you can replace the whole bootstrap folder !

EDIT: I created a Bootstrap boilerplate using this technique : https://github.com/jide/bootstrap-boilerplate

SQL: How do I SELECT only the rows with a unique value on certain column?

Assuming your table of data is called ProjectInfo:

SELECT DISTINCT Contract, Activity
    FROM ProjectInfo
    WHERE Contract = (SELECT Contract
                          FROM (SELECT DISTINCT Contract, Activity
                                    FROM ProjectInfo) AS ContractActivities
                          GROUP BY Contract
                          HAVING COUNT(*) = 1);

The innermost query identifies the contracts and the activities. The next level of the query (the middle one) identifies the contracts where there is just one activity. The outermost query then pulls the contract and activity from the ProjectInfo table for the contracts that have a single activity.

Tested using IBM Informix Dynamic Server 11.50 - should work elsewhere too.

Search for highest key/index in an array

$keys = array_keys($arr);
$keys = rsort($keys);

print $keys[0];

should print "10"

Checking if a variable is an integer in PHP

When i start reading it i did notice that you guys forgot about abvious think like type of to check if we have int, string, null or Boolean. So i think gettype() should be as 1st answer. Explain: So if we have $test = [1,w2,3.45,sasd]; we start test it

foreach ($test as $value) {
        $check = gettype($value);
        if($check == 'integer'){
            echo "This var is int\r\n";
        }
        if($check != 'integer'){
            echo "This var is {$check}\r\n";
        }
}

And output:

> This var is int 
> This var is string 
> This var is double 
> This var is string

I think this is easiest way to check if our var is int, string, double or Boolean.

How to Code Double Quotes via HTML Codes

There really aren't any differences.

&quot; is processed as &#34; which is the decimal equivalent of &x22; which is the ISO 8859-1 equivalent of ".

The only reason you may be against using &quot; is because it was mistakenly omitted from the HTML 3.2 specification.

Otherwise it all boils down to personal preference.

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

It seems that Firefox gets installed in the App data folder Path C:\Users\users\AppData\Local\Mozilla Firefox

So you can set the firefox bin property as below

System.setProperty("webdriver.firefox.bin", "C:\\Users\\*USERNAME*\\AppData\\Local\\Mozilla Firefox\\Firefox.exe");

Adding this resolved the issue for me

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

'module' has no attribute 'urlencode'

urllib has been split up in Python 3.

The urllib.urlencode() function is now urllib.parse.urlencode(),

the urllib.urlopen() function is now urllib.request.urlopen().

window.open target _self v window.location.href?

window.location.href = "webpage.htm";

How do you write multiline strings in Go?

According to the language specification you can use a raw string literal, where the string is delimited by backticks instead of double quotes.

`line 1
line 2
line 3`

Inner join with 3 tables in mysql

The correct statement should be :

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
  INNER JOIN student
    ON student.studentId = grade.fk_studentId
  INNER JOIN exam
    ON exam.examId = grade.fk_examId
ORDER BY exam.date

A table is refered to other on the basis of the foreign key relationship defined. You should refer the ids properly if you wish the data to show as queried. So you should refer the id's to the proper foreign keys in the table rather than just on the id which doesn't define a proper relation

Delete first character of a string in Javascript

_x000D_
_x000D_
String.prototype.trimStartWhile = function(predicate) {_x000D_
    if (typeof predicate !== "function") {_x000D_
     return this;_x000D_
    }_x000D_
    let len = this.length;_x000D_
    if (len === 0) {_x000D_
        return this;_x000D_
    }_x000D_
    let s = this, i = 0;_x000D_
    while (i < len && predicate(s[i])) {_x000D_
     i++;_x000D_
    }_x000D_
    return s.substr(i)_x000D_
}_x000D_
_x000D_
let str = "0000000000ABC",_x000D_
    r = str.trimStartWhile(c => c === '0');_x000D_
    _x000D_
console.log(r);
_x000D_
_x000D_
_x000D_

How do I correctly use "Not Equal" in MS Access?

Like this

SELECT DISTINCT Table1.Column1
FROM Table1
WHERE NOT EXISTS( SELECT * FROM Table2
    WHERE Table1.Column1 = Table2.Column1  )

You want NOT EXISTS, not "Not Equal"


By the way, you rarely want to write a FROM clause like this:

FROM Table1, Table2

as this means "FROM all combinations of every row in Table1 with every row in Table2..." Usually that's a lot more result rows than you ever want to see. And in the rare case that you really do want to do that, the more accepted syntax is:

FROM Table1 CROSS JOIN Table2

Regex to check if valid URL that ends in .jpg, .png, or .gif

Addition to Dan's Answer.

If there is an IP address instead of domain.

Change regex a bit. (Temporary solution for valid IPv4 and IPv6)

^https?://(?:[a-z0-9\-]+\.)+[a-z0-9]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$

However this can be improved, for IPv4 and IPv6 to validate subnet range(s).

PHP script to loop through all of the files in a directory?

you can do this as well

$path = "/public";

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

foreach ($objects as $name => $object) {
  if ('.' === $object) continue;
  if ('..' === $object) continue;

str_replace('/public/', '/', $object->getPathname());

// for example : /public/admin/image.png => /admin/image.png

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

To use unsafe code blocks, the project has to be compiled with the /unsafe switch on.

Open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox.

Manually map column names with class properties

Here is a simple solution that doesn't require attributes allowing you to keep infrastructure code out of your POCOs.

This is a class to deal with the mappings. A dictionary would work if you mapped all the columns, but this class allows you to specify just the differences. In addition, it includes reverse maps so you can get the field from the column and the column from the field, which can be useful when doing things such as generating sql statements.

public class ColumnMap
{
    private readonly Dictionary<string, string> forward = new Dictionary<string, string>();
    private readonly Dictionary<string, string> reverse = new Dictionary<string, string>();

    public void Add(string t1, string t2)
    {
        forward.Add(t1, t2);
        reverse.Add(t2, t1);
    }

    public string this[string index]
    {
        get
        {
            // Check for a custom column map.
            if (forward.ContainsKey(index))
                return forward[index];
            if (reverse.ContainsKey(index))
                return reverse[index];

            // If no custom mapping exists, return the value passed in.
            return index;
        }
    }
}

Setup the ColumnMap object and tell Dapper to use the mapping.

var columnMap = new ColumnMap();
columnMap.Add("Field1", "Column1");
columnMap.Add("Field2", "Column2");
columnMap.Add("Field3", "Column3");

SqlMapper.SetTypeMap(typeof (MyClass), new CustomPropertyTypeMap(typeof (MyClass), (type, columnName) => type.GetProperty(columnMap[columnName])));

merge one local branch into another local branch

  1. git checkout [branchYouWantToReceiveBranch] - checkout branch you want to receive branch
  2. git merge [branchYouWantToMergeIntoBranch]

Get table column names in MySQL?

The easy way, if loading results using assoc is to do this:

$sql = "SELECT p.* FROM (SELECT 1) as dummy LEFT JOIN `product_table` p on null";
$q = $this->db->query($sql);
$column_names = array_keys($q->row);

This you load a single result using this query, you get an array with the table column names as keys and null as value. E.g.

Array(
'product_id' => null,
'sku' => null,
'price' => null,
...
)

after which you can easily get the table column names using the php function array_keys($result)

How to completely remove Python from a Windows machine?

Almost all of the python files should live in their respective folders (C:\Python26 and C:\Python27). Some installers (ActiveState) will also associate .py* files and add the python path to %PATH% with an install if you tick the "use this as the default installation" box.

Drop columns whose name contains a specific string from pandas DataFrame

You can filter out the columns you DO want using 'filter'

import pandas as pd
import numpy as np

data2 = [{'test2': 1, 'result1': 2}, {'test': 5, 'result34': 10, 'c': 20}]

df = pd.DataFrame(data2)

df

    c   result1     result34    test    test2
0   NaN     2.0     NaN     NaN     1.0
1   20.0    NaN     10.0    5.0     NaN

Now filter

df.filter(like='result',axis=1)

Get..

   result1  result34
0   2.0     NaN
1   NaN     10.0

When do I need to do "git pull", before or after "git add, git commit"?

I think that the best way to do this is:

Stash your local changes:

git stash

Update the branch to the latest code

git pull

Merge your local changes into the latest code:

git stash apply

Add, commit and push your changes

git add
git commit
git push

In my experience this is the path to least resistance with Git (on the command line anyway).

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

Are you using AdSense or other ads in your app, or maybe Google Analytics ? I think if you do so, even if you don't have the android.permission.READ_PHONE_STATE in your manifest this is added by the ads library.

There are free templates that might help you create a privacy policy.

This is the email i received from Google about it :

Hello Google Play Developer, Our records show that your app, xxx, with package name xxx, currently violates our User Data policy regarding Personal and Sensitive Information. Policy issue: Google Play requires developers to provide a valid privacy policy when the app requests or handles sensitive user or device information. Your app requests sensitive permissions (e.g. camera, microphone, accounts, contacts, or phone) or user data, but does not include a valid privacy policy. Action required: Include a link to a valid privacy policy on your app's Store Listing page and within your app. You can find more information in our help center. Alternatively, you may opt-out of this requirement by removing any requests for sensitive permissions or user data. If you have additional apps in your catalog, please make sure they are compliant with our Prominent Disclosure requirements. Please resolve this issue by March 15, 2017, or administrative action will be taken to limit the visibility of your app, up to and including removal from the Play Store. Thanks for helping us provide a clear and transparent experience for Google Play users. Regards, The Google Play Team

Compare dates with javascript

Because of your date format, you can use this code:

if(parseInt(first.replace(/-/g,""),10) > parseInt(second.replace(/-/g,""),10)){
   //...
}

It will check whether 20121121 number is bigger than 20121103 or not.

Python pandas insert list into a cell

I've got a solution that's pretty simple to implement.

Make a temporary class just to wrap the list object and later call the value from the class.

Here's a practical example:

  1. Let's say you want to insert list object into the dataframe.
df = pd.DataFrame([
    {'a': 1},
    {'a': 2},
    {'a': 3},
])

df.loc[:, 'b'] = [
    [1,2,4,2,], 
    [1,2,], 
    [4,5,6]
] # This works. Because the list has the same length as the rows of the dataframe

df.loc[:, 'c'] = [1,2,4,5,3] # This does not work. 

>>> ValueError: Must have equal len keys and value when setting with an iterable

## To force pandas to have list as value in each cell, wrap the list with a temporary class.

class Fake(object):
    def __init__(self, li_obj):
        self.obj = li_obj

df.loc[:, 'c'] = Fake([1,2,5,3,5,7,]) # This works. 

df.c = df.c.apply(lambda x: x.obj) # Now extract the value from the class. This works. 

Creating a fake class to do this might look like a hassle but it can have some practical applications. For an example you can use this with apply when the return value is list.

Pandas would normally refuse to insert list into a cell but if you use this method, you can force the insert.

Are global variables bad?

I usually use globals for values that are rarely changed like singletons or function pointers to functions in dynamically loaded library. Using mutable globals in multithreaded applications tends to lead to hard to track bug so I try to avoid this as a general rule.

Using a global instead of passing an argument is often faster but if you're writing a multithreaded application, which you often do nowadays, it generally doesn't work very well (you can use thread-statics but then the performance gain is questionable).

MySQL: Quick breakdown of the types of joins

Based on your comment, simple definitions of each is best found at W3Schools The first line of each type gives a brief explanation of the join type

  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables

END EDIT

In a nutshell, the comma separated example you gave of

SELECT * FROM a, b WHERE b.id = a.beeId AND ...

is selecting every record from tables a and b with the commas separating the tables, this can be used also in columns like

SELECT a.beeName,b.* FROM a, b WHERE b.id = a.beeId AND ...

It is then getting the instructed information in the row where the b.id column and a.beeId column have a match in your example. So in your example it will get all information from tables a and b where the b.id equals a.beeId. In my example it will get all of the information from the b table and only information from the a.beeName column when the b.id equals the a.beeId. Note that there is an AND clause also, this will help to refine your results.

For some simple tutorials and explanations on mySQL joins and left joins have a look at Tizag's mySQL tutorials. You can also check out Keith J. Brown's website for more information on joins that is quite good also.

I hope this helps you

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

@Configuration annotation will just solve the error

What is an idiomatic way of representing enums in Go?

You can make it so:

type MessageType int32

const (
    TEXT   MessageType = 0
    BINARY MessageType = 1
)

With this code compiler should check type of enum

Getting the index of a particular item in array

     int i=  Array.IndexOf(temp1,  temp1.Where(x=>x.Contains("abc")).FirstOrDefault());

Javamail Could not convert socket to TLS GMail

If your context is android application , then make sure your android device time is set to current date and time. The underlying exception is "The SSL certificates was not getting authenticated."

Maven Unable to locate the Javac Compiler in:

It depends on of Maven version. When you will install newer version of Maven, this error would not appear. You may also add another directory with tools.jar file lib/tools.jar - it also solve this problem.

Maven error :Perhaps you are running on a JRE rather than a JDK?

This is because of running jre rather than jdk, to install jdk follow below steps

Installing java 8 in amazon linux/redhat

--> yum search java | grep openjdk

--> yum install java-1.8.0-openjdk-headless.x86_64

--> yum install java-1.8.0-openjdk-devel.x86_64

--> update-alternatives --config java #pick java 1.8 and press 1

--> update-alternatives --config javac #pick java 1.8 and press 2

Thank You

Is there a way to catch the back button event in javascript?

Use the hashchange event:

window.addEventListener("hashchange", function(e) {
  // ...
})

If you need to support older browsers, check out the hashChange Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.

Trying to detect browser close event

You can try something like this.

<html>
<head>
    <title>test</title>
    <script>
        function openChecking(){
            // alert("open");
            var width = Number(screen.width-(screen.width*0.25));  
            var height = Number(screen.height-(screen.height*0.25));
            var leftscr = Number((screen.width/2)-(width/2)); // center the window
            var topscr = Number((screen.height/2)-(height/2));
            var url = "";
            var title = 'popup';
            var properties = 'width='+width+', height='+height+', top='+topscr+', left='+leftscr;
            var popup = window.open(url, title, properties);
            var crono = window.setInterval(function() {
                if (popup.closed !== false) { // !== opera compatibility reasons
                    window.clearInterval(crono);
                    checkClosed();
                }
            }, 250); //we check if the window is closed every 1/4 second
        }   
        function checkClosed(){
            alert("closed!!");
            // do something
        }
    </script>    
</head>
<body>
    <button onclick="openChecking()">Click Me</button>
</body>
</html>

When the user closes the window, the callback will be fired.

Rails: select unique values from a column

Another way to collect uniq columns with sql:

Model.group(:rating).pluck(:rating)

Is < faster than <=?

You should not be able to notice the difference even if there is any. Besides, in practice, you'll have to do an additional a + 1 or a - 1 to make the condition stand unless you're going to use some magic constants, which is a very bad practice by all means.

What is the difference between partitioning and bucketing a table in Hive ?

There are great responses here. I would like to keep it short to memorize the difference between partition & buckets.

You generally partition on a less unique column. And bucketing on most unique column.

Example if you consider World population with country, person name and their bio-metric id as an example. As you can guess, country field would be the less unique column and bio-metric id would be the most unique column. So ideally you would need to partition the table by country and bucket it by bio-metric id.

Placeholder Mixin SCSS/CSS

I found the approach given by cimmanon and Kurt Mueller almost worked, but that I needed a parent reference (i.e., I need to add the '&' prefix to each vendor prefix); like this:

@mixin placeholder {
    &::-webkit-input-placeholder {@content}
    &:-moz-placeholder           {@content}
    &::-moz-placeholder          {@content}
    &:-ms-input-placeholder      {@content}  
}

I use the mixin like this:

input {
    @include placeholder {
        font-family: $base-font-family;
        color: red;
    }
}

With the parent reference in place, then correct css gets generated, e.g.:

input::-webkit-input-placeholder {
    font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Liberation Serif", Georgia, serif;
    color: red;
}

Without the parent reference (&), then a space is inserted before the vendor prefix and the CSS processor ignores the declaration; that looks like this:

input::-webkit-input-placeholder {
    font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Liberation Serif", Georgia, serif;
    color: red;
}

Navigate to another page with a button in angular 2

Having the router link on the button seems to work fine for me:

<button class="nav-link" routerLink="/" (click)="hideMenu()">
     <i class="fa fa-home"></i> 
     <span>Home</span>
</button>

Is there a way to 'pretty' print MongoDB shell output to a file?

Just put the commands you want to run into a file, then pass it to the shell along with the database name and redirect the output to a file. So, if your find command is in find.js and your database is foo, it would look like this:

./mongo foo find.js >> out.json

Copy files on Windows Command Line with Progress

You could easily write a program to do that, I've got several that I've written, that display bytes copied as the file is being copied. If you're interested, comment and I'll post a link to one.

Sort objects in an array alphabetically on one property of the array

you would have to do something like this:

objArray.sort(function(a, b) {
    var textA = a.DepartmentName.toUpperCase();
    var textB = b.DepartmentName.toUpperCase();
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});

note: changing the case (to upper or lower) ensures a case insensitive sort.

How to load a text file into a Hive table stored as sequence files

The simple way is to create table as textfile and move the file to the appropriate location

CREATE EXTERNAL TABLE mytable(col1 string, col2 string)
row format delimited fields terminated by '|' stored as textfile;

Copy the file to the HDFS Location where table is created.
Hope this helps!!!

How can I download HTML source in C#

You can download files with the WebClient class:

using System.Net;

using (WebClient client = new WebClient ()) // WebClient class inherits IDisposable
{
    client.DownloadFile("http://yoursite.com/page.html", @"C:\localfile.html");

    // Or you can get the file content without saving it
    string htmlCode = client.DownloadString("http://yoursite.com/page.html");
}

How to do join on multiple criteria, returning all combinations of both criteria

It sounds like you want to list all the metrics?

SELECT Criteria1, Criteria2, Metric1 As Metric
FROM Table1
UNION ALL
SELECT Criteria1, Criteria2, Metric2 As Metric
FROM Table2
ORDER BY 1, 2

If you only want one Criteria1+Criteria2 combination, group them:

SELECT Criteria1, Criteia2, SUM(Metric) AS Metric
FROM (
    SELECT Criteria1, Criteria2, Metric1 As Metric
    FROM Table1
    UNION ALL
    SELECT Criteria1, Criteria2, Metric2 As Metric
    FROM Table2
)
ORDER BY Criteria1, Criteria2

Disable eslint rules for folder

The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:

{
    "env": {},
    "extends": [],
    "parser": "",
    "plugins": [],
    "rules": {},
    "overrides": [
      {
        "files": ["test/*.spec.js"], // Or *.test.js
        "rules": {
          "require-jsdoc": "off"
        }
      }
    ],
    "settings": {}
}

How to get an object's properties in JavaScript / jQuery?

To get listing of object properties/values:

  1. In Firefox - Firebug:

    console.dir(<object>);
    
  2. Standard JS to get object keys borrowed from Slashnick:

       var fGetKeys = function(obj){
          var keys = [];
          for(var key in obj){
             keys.push(key);
          }
          return keys;
       }
    
    // Example to call it:
    
       var arrKeys = fGetKeys(document);
    
       for (var i=0, n=arrKeys.length; i<n; i++){
          console.log(i+1 + " - " + arrKeys[i] + document[arrKeys[i]] + "\n");
       }
    

Edits:

  1. <object> in the above is to be replaced with the variable reference to the object.
  2. console.log() is to be used in the console, if you're unsure what that is, you can replace it with an alert()

Execute SQL script from command line

Take a look at the sqlcmd utility. It allows you to execute SQL from the command line.

http://msdn.microsoft.com/en-us/library/ms162773.aspx

It's all in there in the documentation, but the syntax should look something like this:

sqlcmd -U myLogin -P myPassword -S MyServerName -d MyDatabaseName 
    -Q "DROP TABLE MyTable"

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

I am using mongoose version 5.x for my project. After requiring the mongoose package, set the value globally as below.

const mongoose = require('mongoose');

// Set the global useNewUrlParser option to turn on useNewUrlParser for every connection by default.
mongoose.set('useNewUrlParser', true);

How to run SQL script in MySQL?

Give the path of .sql file as:

source c:/dump/SQL/file_name.sql;

See In The Image:

Conditionally Remove Dataframe Rows with R

Subset is your safest and easiest answer.

subset(dataframe, A==B & E!=0)

Real data example with mtcars

subset(mtcars, cyl==6 & am!=0)

Python Prime number checker

This example is use reduce(), but slow it:

def makepnl(pnl, n):
    for p in pnl:
        if n % p == 0:
            return pnl
    pnl.append(n)
    return pnl

def isprime(n):
    return True if n == reduce(makepnl, range(3, n + 1, 2), [2])[-1] else False

for i in range(20):
    print i, isprime(i)

It use Sieve Of Atkin, faster than above:

def atkin(limit):
    if limit > 2:
        yield 2
    if limit > 3:
        yield 3

    import math
    is_prime = [False] * (limit + 1)

    for x in range(1,int(math.sqrt(limit))+1):
        for y in range(1,int(math.sqrt(limit))+1):
            n = 4*x**2 + y**2

            if n<=limit and (n%12==1 or n%12==5):
                # print "1st if"                                                                                                                    
                is_prime[n] = not is_prime[n]
            n = 3*x**2+y**2
            if n<= limit and n%12==7:
                # print "Second if"                                                                                                                 
                is_prime[n] = not is_prime[n]
            n = 3*x**2 - y**2
            if x>y and n<=limit and n%12==11:
                # print "third if"                                                                                                                  
                is_prime[n] = not is_prime[n]

    for n in range(5,int(math.sqrt(limit))):
        if is_prime[n]:
            for k in range(n**2,limit+1,n**2):
                is_prime[k] = False

    for n in range(5,limit):
        if is_prime[n]: yield n

def isprime(n):
    r = list(atkin(n+1))
    if not r: return False
    return True if n == r[-1] else False

for i in range(20):
    print i, isprime(i)

How to add time to DateTime in SQL

Start Day Time : SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), '00:00:00')

End Day Time : SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), '23:59:59')

How to compare values which may both be null in T-SQL

Use ISNULL:

ISNULL(MY_FIELD1, 'NULL') = ISNULL(@IN_MY_FIELD1, 'NULL')

You can change 'NULL' to something like 'All Values' if it makes more sense to do so.

It should be noted that with two arguments, ISNULL works the same as COALESCE, which you could use if you have a few values to test (i.e.-COALESCE(@IN_MY_FIELD1, @OtherVal, 'NULL')). COALESCE also returns after the first non-null, which means it's (marginally) faster if you expect MY_FIELD1 to be blank. However, I find ISNULL much more readable, so that's why I used it, here.

get the margin size of an element with jquery

Exemple, for :

<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>

In this js code :

var myMarginTop = $("#myBlock").css("marginBottom");

The var becomes "15px", a string.

If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.

The fastest is to use native js method :

var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );

What is the difference between Integrated Security = True and Integrated Security = SSPI?

Many questions get answers if we use .Net Reflector to see the actual code of SqlConnection :) true and sspi are the same:

internal class DbConnectionOptions

...

internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
{
    if ((CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true")) || CompareInsensitiveInvariant(stringValue, "yes"))
    {
        return true;
    }
}

...

EDIT 20.02.2018 Now in .Net Core we can see its open source on github! Search for ConvertValueToIntegratedSecurityInternal method:

https://github.com/dotnet/corefx/blob/fdbb160aeb0fad168b3603dbdd971d568151a0c8/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs

WhatsApp API (java/python)

WhatsApp Inc. does not provide an open API but a reverse-engineered library is made available on GitHub by the team Venomous on the GitHub. This however according to my knowledge is made possible in PHP. You can check the link here: https://github.com/venomous0x/WhatsAPI

Hope this helps

CSS - Make divs align horizontally

You can now use css flexbox to align divs horizontally and vertically if you need to. general formula goes like this

parent-div {
  display: flex;
  flex-wrap: wrap;
  /* for horizontal aligning of child divs */
  justify-content: center;
  /* for vertical aligning */
  align-items: center;
}

child-div {
  width: /* yoursize for each div */
  ;
}

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

Java: recommended solution for deep cloning/copying an instance

I'd recommend the DIY way which, combined with a good hashCode() and equals() method should be easy to proof in a unit test.

How to find if directory exists in Python

You're looking for os.path.isdir, or os.path.exists if you don't care whether it's a file or a directory:

>>> import os
>>> os.path.isdir('new_folder')
True
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False

Alternatively, you can use pathlib:

 >>> from pathlib import Path
 >>> Path('new_folder').is_dir()
 True
 >>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
 False

Double value to round up in Java

You could try defining a new DecimalFormat and using it as a Double result to a new double variable.

Example given to make you understand what I just said.

double decimalnumber = 100.2397;
DecimalFormat dnf = new DecimalFormat( "#,###,###,##0.00" );
double roundednumber = new Double(dnf.format(decimalnumber)).doubleValue();

Python : List of dict, if exists increment a dict value, if not append a new dict

To do it exactly your way? You could use the for...else structure

for url in list_of_urls:
    for url_dict in urls:
        if url_dict['url'] == url:
            url_dict['nbr'] += 1
            break
    else:
        urls.append(dict(url=url, nbr=1))

But it is quite inelegant. Do you really have to store the visited urls as a LIST? If you sort it as a dict, indexed by url string, for example, it would be way cleaner:

urls = {'http://www.google.fr/': dict(url='http://www.google.fr/', nbr=1)}

for url in list_of_urls:
    if url in urls:
        urls[url]['nbr'] += 1
    else:
        urls[url] = dict(url=url, nbr=1)

A few things to note in that second example:

  • see how using a dict for urls removes the need for going through the whole urls list when testing for one single url. This approach will be faster.
  • Using dict( ) instead of braces makes your code shorter
  • using list_of_urls, urls and url as variable names make the code quite hard to parse. It's better to find something clearer, such as urls_to_visit, urls_already_visited and current_url. I know, it's longer. But it's clearer.

And of course I'm assuming that dict(url='http://www.google.fr', nbr=1) is a simplification of your own data structure, because otherwise, urls could simply be:

urls = {'http://www.google.fr':1}

for url in list_of_urls:
    if url in urls:
        urls[url] += 1
    else:
        urls[url] = 1

Which can get very elegant with the defaultdict stance:

urls = collections.defaultdict(int)
for url in list_of_urls:
    urls[url] += 1

How to detect current state within directive

If you are using ui-router, try $state.is();

You can use it like so:

$state.is('stateName');

Per the documentation:

$state.is ... similar to $state.includes, but only checks for the full state name.

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

There are two storage areas involved: the stack and the heap.The stack is where the current state of a method call is kept (ie local variables and references), and the heap is where objects are stored. recursion and memory

I gues there are too many keys in the counter dict that will consume too much memory of the heap region, so the Python runtime will raise a OutOfMemory exception.

To save it, don't create a giant object, e.g. the counter.

1.StackOverflow

a program that create too many local variables.

Python 2.7.9 (default, Mar  1 2015, 12:57:24) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('stack_overflow.py','w')
>>> f.write('def foo():\n')
>>> for x in xrange(10000000):
...   f.write('\tx%d = %d\n' % (x, x))
... 
>>> f.write('foo()')
>>> f.close()
>>> execfile('stack_overflow.py')
Killed

2.OutOfMemory

a program that creats a giant dict includes too many keys.

>>> f = open('out_of_memory.py','w')
>>> f.write('def foo():\n')
>>> f.write('\tcounter = {}\n')
>>> for x in xrange(10000000):
...   f.write('counter[%d] = %d\n' % (x, x))
... 
>>> f.write('foo()\n')
>>> f.close()
>>> execfile('out_of_memory.py')
Killed

References

Read input stream twice

For splitting an InputStream in two, while avoiding to load all data in memory, and then process them independently:

  1. Create a couple of OutputStream, precisely: PipedOutputStream
  2. Connect each PipedOutputStream with a PipedInputStream, these PipedInputStream are the returned InputStream.
  3. Connect the sourcing InputStream with just created OutputStream. So, everything read it from the sourcing InputStream, would be written in both OutputStream. There is not need to implement that, because it is done already in TeeInputStream (commons.io).
  4. Within a separated thread read the whole sourcing inputStream, and implicitly the input data is transferred to the target inputStreams.

    public static final List<InputStream> splitInputStream(InputStream input) 
        throws IOException 
    { 
        Objects.requireNonNull(input);      
    
        PipedOutputStream pipedOut01 = new PipedOutputStream();
        PipedOutputStream pipedOut02 = new PipedOutputStream();
    
        List<InputStream> inputStreamList = new ArrayList<>();
        inputStreamList.add(new PipedInputStream(pipedOut01));
        inputStreamList.add(new PipedInputStream(pipedOut02));
    
        TeeOutputStream tout = new TeeOutputStream(pipedOut01, pipedOut02);
    
        TeeInputStream tin = new TeeInputStream(input, tout, true);
    
        Executors.newSingleThreadExecutor().submit(tin::readAllBytes);  
    
        return Collections.unmodifiableList(inputStreamList);
    }
    

Be aware to close the inputStreams after being consumed, and close the thread that runs: TeeInputStream.readAllBytes()

In case, you need to split it into multiple InputStream, instead of just two. Replace in the previous fragment of code the class TeeOutputStream for your own implementation, which would encapsulate a List<OutputStream> and override the OutputStream interface:

public final class TeeListOutputStream extends OutputStream {
    private final List<? extends OutputStream> branchList;

    public TeeListOutputStream(final List<? extends OutputStream> branchList) {
        Objects.requireNonNull(branchList);
        this.branchList = branchList;
    }

    @Override
    public synchronized void write(final int b) throws IOException {
        for (OutputStream branch : branchList) {
            branch.write(b);
        }
    }

    @Override
    public void flush() throws IOException {
        for (OutputStream branch : branchList) {
            branch.flush();
        }
    }

    @Override
    public void close() throws IOException {
        for (OutputStream branch : branchList) {
            branch.close();
        }
    }
}

Remove part of string after "."

You could do:

sub("*\\.[0-9]", "", a)

or

library(stringr)
str_sub(a, start=1, end=-3)

Converting <br /> into a new line for use in a text area

The answer by @Mobilpadde is nice. But this is my solution with regex using preg_replace which might be faster according to my tests.

echo preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");

function function_one() {
    preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");
}

function function_two() {
    str_ireplace(['<br />','<br>','<br/>'], "\r\n", "testing<br/><br /><BR><br>");
}

function benchmark() {
    $count = 10000000;
    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_one();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function one\n";



    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_two();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function two\n";
}
benchmark();

Results:

1.1471637010574E-6 sec/function one (preg_replace)
1.6027762889862E-6 sec/function two (str_ireplace)

How to get exit code when using Python subprocess communicate method?

.poll() will update the return code.

Try

child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
returnCode = child.poll()

In addition, after .poll() is called the return code is available in the object as child.returncode.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

The Web Deployment Agent Service is deployed with WebMatrix and was the cause of my woes. It may also be distributed with other applications installed using Microsoft’s Web Platform Installer.

Uninstall it solved my problems!

How to modify a global variable within a function in bash?

It's because command substitution is performed in a subshell, so while the subshell inherits the variables, changes to them are lost when the subshell ends.

Reference:

Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment

Decreasing for loops in Python impossible?

for n in range(6,0,-1):
    print n
# prints [6, 5, 4, 3, 2, 1]

Git: Find the most recent common ancestor of two branches

You are looking for git merge-base. Usage:

$ git merge-base branch2 branch3
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

Creating the checkbox dynamically using JavaScript?

   /* worked for me  */
     <div id="divid"> </div>
     <script type="text/javascript">
         var hold = document.getElementById("divid");
         var checkbox = document.createElement('input');
         checkbox.type = "checkbox";
         checkbox.name = "chkbox1";
         checkbox.id = "cbid";
         var label = document.createElement('label');
         var tn = document.createTextNode("Not A RoBot");
         label.htmlFor="cbid";
         label.appendChild(tn); 
         hold.appendChild(label);
         hold.appendChild(checkbox);
      </script>  

Can't update data-attribute value

For myself, using Jquery lib 2.1.1 the following did NOT work the way I expected:

Set element data attribute value:

$('.my-class').data('num', 'myValue');
console.log($('#myElem').data('num'));// as expected = 'myValue'

BUT the element itself remains without the attribute:

<div class="my-class"></div>

I needed the DOM updated so I could later do $('.my-class[data-num="myValue"]') //current length is 0

So I had to do

$('.my-class').attr('data-num', 'myValue');

To get the DOM to update:

<div class="my-class" data-num="myValue"></div>

Whether the attribute exists or not $.attr will overwrite.

Lua - Current time in milliseconds

Get current time in milliseconds.

os.time()

os.time()
return sec // only

posix.clock_gettime(clk)

https://luaposix.github.io/luaposix/modules/posix.time.html#clock_gettime

require'posix'.clock_gettime(0)
return sec, nsec

linux/time.h // man clock_gettime

/*
 * The IDs of the various system clocks (for POSIX.1b interval timers):
 */
#define CLOCK_REALTIME                  0
#define CLOCK_MONOTONIC                 1
#define CLOCK_PROCESS_CPUTIME_ID        2
#define CLOCK_THREAD_CPUTIME_ID         3
#define CLOCK_MONOTONIC_RAW             4
#define CLOCK_REALTIME_COARSE           5
#define CLOCK_MONOTONIC_COARSE          6

socket.gettime()

http://w3.impa.br/~diego/software/luasocket/socket.html#gettime

require'socket'.gettime()
return sec.xxx

as waqas says


compare & test

get_millisecond.lua

local posix=require'posix'
local socket=require'socket'

for i=1,3 do
    print( os.time() )
    print( posix.clock_gettime(0) )
    print( socket.gettime() )
    print''
    posix.nanosleep(0, 1) -- sec, nsec
end

output

lua get_millisecond.lua
1490186718
1490186718      268570540
1490186718.2686

1490186718
1490186718      268662191
1490186718.2687

1490186718
1490186718      268782765
1490186718.2688

How to deal with certificates using Selenium?

Javascript:

const capabilities = webdriver.Capabilities.phantomjs();
capabilities.set(webdriver.Capability.ACCEPT_SSL_CERTS, true);
capabilities.set(webdriver.Capability.SECURE_SSL, false);
capabilities.set('phantomjs.cli.args', ['--web-security=no', '--ssl-protocol=any', '--ignore-ssl-errors=yes']);
const driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome(), capabilities).build();

How to replace a substring of a string

In javascript:

var str = "abcdaaaaaabcdaabbccddabcd";
document.write(str.replace(/(abcd)/g,"----"));
//example output: ----aaaaa----aabbccdd----

In other languages, it would be something similar. Remember to enable global matches.

How to do Select All(*) in linq to sql

Assuming TableA as an entity of table TableA, and TableADBEntities as DB Entity class,

  1. LINQ Method
IQueryable<TableA> result;
using (var context = new TableADBEntities())
{
   result = context.TableA.Select(s => s);
}
  1. LINQ-to-SQL Query
IQueryable<TableA> result;
using (var context = new TableADBEntities())
{
   var qry = from s in context.TableA
               select s;
   result = qry.Select(s => s);
}

Native SQL can also be used as:

  1. Native SQL
IList<TableA> resultList;
using (var context = new TableADBEntities())
{
   resultList = context.TableA.SqlQuery("Select * from dbo.TableA").ToList();
}

Note: dbo is a default schema owner in SQL Server. One can construct a SQL SELECT query as per the database in the context.

Creating Dynamic button with click event in JavaScript

Firstly, you need to change this line:

element.setAttribute("onclick", alert("blabla"));

To something like this:

element.setAttribute("onclick", function() { alert("blabla"); });

Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.

css display table cell requires percentage width

You just need to add 'table-layout: fixed;'

.table {
   display: table;
   height: 100px;
   width: 100%;
   table-layout: fixed;
}

http://www.w3schools.com/cssref/pr_tab_table-layout.asp

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

You should initialize yours recordings. You are passing to adapter null

ArrayList<String> recordings = null; //You are passing this null

MySQL: Large VARCHAR vs. TEXT?

The preceding answers don't insist enough on the main problem: even in very simple queries like

(SELECT t2.* FROM t1, t2 WHERE t2.id = t1.id ORDER BY t1.id) 

a temporary table can be required, and if a VARCHAR field is involved, it is converted to a CHAR field in the temporary table. So if you have in your table say 500 000 lines with a VARCHAR(65000) field, this column alone will use 6.5*5*10^9 byte. Such temp tables can't be handled in memory and are written to disk. The impact can be expected to be catastrophic.

Source (with metrics): https://nicj.net/mysql-text-vs-varchar-performance/ (This refers to the handling of TEXT vs VARCHAR in "standard"(?) MyISAM storage engine. It may be different in others, e.g., InnoDB.)

Resize HTML5 canvas to fit window

(function() {

    // get viewport size
    getViewportSize = function() {
        return {
            height: window.innerHeight,
            width:  window.innerWidth
        };
    };

    // update canvas size
    updateSizes = function() {
        var viewportSize = getViewportSize();
        $('#myCanvas').width(viewportSize.width).height(viewportSize.height);
        $('#myCanvas').attr('width', viewportSize.width).attr('height', viewportSize.height);
    };

    // run on load
    updateSizes();

    // handle window resizing
    $(window).on('resize', function() {
        updateSizes();
    });

}());

Aliases in Windows command prompt

Naturally, I would not rest until I have the most convenient solution of all. Combining the very many answers and topics on the vast internet, here is what you can have.

  • Loads automatically with every instance of cmd
  • Doesn't require keyword DOSKEY for aliases
    example: ls=ls --color=auto $*

Note that this is largely based on Argyll's answer and comments, definitely read it to understand the concepts.

How to make it work?

  1. Create a mac macro file with the aliases
    you can even use a bat/cmd file to also run other stuff (similar to .bashrc in linux)
  2. Register it in Registry to run on each instance of cmd
      or run it via shortcut only if you want

Example steps:

%userprofile%/cmd/aliases.mac
;==============================================================================
;= This file is registered via registry to auto load with each instance of cmd.
;================================ general info ================================
;= https://stackoverflow.com/a/59978163/985454  -  how to set it up?
;= https://gist.github.com/postcog/5c8c13f7f66330b493b8  -  example doskey macrofile
;========================= loading with cmd shortcut ==========================
;= create a shortcut with the following target :
;= %comspec% /k "(doskey /macrofile=%userprofile%\cmd\aliases.mac)"

alias=subl %USERPROFILE%\cmd\aliases.mac
hosts=runas /noprofile /savecred /user:QWERTY-XPS9370\administrator "subl C:\Windows\System32\drivers\etc\hosts" > NUL

p=@echo "~~ powercfg -devicequery wake_armed ~~" && powercfg -devicequery wake_armed && @echo "~~ powercfg -requests ~~ " && powercfg -requests && @echo "~~ powercfg -waketimers ~~"p && powercfg -waketimers

ls=ls --color=auto $*
ll=ls -l --color=auto $*
la=ls -la --color=auto $*
grep=grep --color $*

~=cd %USERPROFILE%
cdr=cd C:\repos
cde=cd C:\repos\esquire
cdd=cd C:\repos\dixons
cds=cd C:\repos\stekkie
cdu=cd C:\repos\uplus
cduo=cd C:\repos\uplus\oxbridge-fe
cdus=cd C:\repos\uplus\stratus

npx=npx --no-install $*
npxi=npx $*
npr=npm run $*

now=vercel $*


;=only in bash
;=alias whereget='_whereget() { A=$1; B=$2; shift 2; eval \"$(where $B | head -$A | tail -1)\" $@; }; _whereget'

history=doskey /history
;= h [SHOW | SAVE | TSAVE ]
h=IF ".$*." == ".." (echo "usage: h [ SHOW | SAVE | TSAVE ]" && doskey/history) ELSE (IF /I "$1" == "SAVE" (doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved) ELSE (IF /I "$1" == "TSAVE" (echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved) ELSE (IF /I "$1" == "SHOW" (type %USERPROFILE%\cmd\history.log) ELSE (doskey/history))))
loghistory=doskey /history >> %USERPROFILE%\cmd\history.log

;=exit=echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & ECHO Command history saved, exiting & timeout 1 & exit $*
exit=echo **** %date% %time% **** >> %USERPROFILE%\cmd\history.log & doskey/history $g$g %USERPROFILE%\cmd\history.log & exit $*

;============================= :end ============================
;= rem ******************************************************************
;= rem * EOF - Don't remove the following line.  It clears out the ';'
;= rem * macro. We're using it because there is no support for comments
;= rem * in a DOSKEY macro file.
;= rem ******************************************************************
;=

Now you have three options:

  • a) load manually with shortcut

    create a shortcut to cmd.exe with the following target :
    %comspec% /k "(doskey /macrofile=%userprofile%\cmd\aliases.mac)"

  • b) register just the aliases.mac macrofile

  • c) register a regular cmd/bat file to also run arbitrary commands
    see example cmdrc.cmd file at the bottom

note: Below, Autorun_ is just a placeholder key which will not do anything. Pick one and rename the other.

Manually edit registry at this path:

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
  Autorun    REG_SZ    doskey /macrofile=%userprofile%\cmd\aliases.mac
  Autorun_    REG_SZ    %USERPROFILE%\cmd\cmdrc.cmd

Or import reg file:

%userprofile%/cmd/cmd-aliases.reg
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"Autorun"="doskey /macrofile=%userprofile%\\cmd\\aliases.mac"
"Autorun_"="%USERPROFILE%\\cmd\\cmdrc.cmd"
%userprofile%/cmd/cmdrc.cmd you don't need this file if you decided for b) above
:: This file is registered via registry to auto load with each instance of cmd.
:: https://stackoverflow.com/a/59978163/985454

@echo off
doskey /macrofile=%userprofile%\cmd\aliases.mac

:: put other commands here

How to make a custom LinkedIn share button

This works for me:

https://www.linkedin.com/shareArticle?mini=true&url=articleUrl&title=YourarticleTitle&summary=YourarticleSummary&source=YourarticleSource

You can use this link by replacing it with your content. It works 100%.

Change UITextField and UITextView Cursor / Caret Color

This worked for me in swift:

UITextField.tintColor = UIColor.blackColor()

You can also set this in storyboard: https://stackoverflow.com/a/18759577/3075340

Check if a value is an object in JavaScript

Oh My God! I think this could be more shorter than ever, let see this:

Short and Final code

_x000D_
_x000D_
function isObject(obj)_x000D_
{_x000D_
    return obj != null && obj.constructor.name === "Object"_x000D_
}_x000D_
_x000D_
console.log(isObject({})) // returns true_x000D_
console.log(isObject([])) // returns false_x000D_
console.log(isObject(null)) // returns false
_x000D_
_x000D_
_x000D_

Explained

Return Types

typeof JavaScript objects (including null) returns "object"

_x000D_
_x000D_
console.log(typeof null, typeof [], typeof {})
_x000D_
_x000D_
_x000D_

Checking on Their constructors

Checking on their constructor property returns function with their names.

_x000D_
_x000D_
console.log(({}).constructor) // returns a function with name "Object"_x000D_
console.log(([]).constructor) // returns a function with name "Array"_x000D_
console.log((null).constructor) //throws an error because null does not actually have a property
_x000D_
_x000D_
_x000D_

Introducing Function.name

Function.name returns a readonly name of a function or "anonymous" for closures.

_x000D_
_x000D_
console.log(({}).constructor.name) // returns "Object"_x000D_
console.log(([]).constructor.name) // returns "Array"_x000D_
console.log((null).constructor.name) //throws an error because null does not actually have a property
_x000D_
_x000D_
_x000D_

Note: As of 2018, Function.name might not work in IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility

Timestamp to human readable format

Hours, minutes and seconds depend on the time zone of your operating system. In GMT (UST) it's 22:00:00 but in different timezones it can be anything. So add the timezone offset to the time to create the GMT date:

var d = new Date();
date = new Date(timestamp*1000 + d.getTimezoneOffset() * 60000)

Read text file into string. C++ ifstream

getline(fin, buffer, '\n')
where fin is opened file(ifstream object) and buffer is of string/char type where you want to copy line.

Get the content of a sharepoint folder with Excel VBA

In addition to:

myFilePath = replace(myFilePath, "/", "\")
myFilePath = replace(myFilePath, "http:", "")

also replace space:

myFilePath = replace(myFilePath, " ", "%20")

Combining a class selector and an attribute selector with jQuery

I think you just need to remove the space. i.e.

$(".myclass[reference=12345]").css('border', '#000 solid 1px');

There is a fiddle here http://jsfiddle.net/xXEHY/

How to check if a list is empty in Python?

Empty lists evaluate to False in boolean contexts (such as if some_list:).

AngularJS - $http.post send data as json

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):

$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
        .then(function (response) {
            return response;
        });

How do I copy the contents of one ArrayList into another?

Supopose you want to copy oldList into a new ArrayList object called newList

ArrayList<Object> newList = new ArrayList<>() ;

for (int i = 0 ; i<oldList.size();i++){
    newList.add(oldList.get(i)) ;
}

These two lists are indepedant, changes to one are not reflected to the other one.

NPM global install "cannot find module"

For anyone else running into this, I had this problem due to my npm installing into a location that's not on my NODE_PATH.

[root@uberneek ~]# which npm
/opt/bin/npm
[root@uberneek ~]# which node
/opt/bin/node
[root@uberneek ~]# echo $NODE_PATH

My NODE_PATH was empty, and running npm install --global --verbose promised-io showed that it was installing into /opt/lib/node_modules/promised-io:

[root@uberneek ~]# npm install --global --verbose promised-io
npm info it worked if it ends with ok
npm verb cli [ '/opt/bin/node',
npm verb cli   '/opt/bin/npm',
npm verb cli   'install',
npm verb cli   '--global',
npm verb cli   '--verbose',
npm verb cli   'promised-io' ]
npm info using [email protected]
npm info using [email protected]
[cut]
npm info build /opt/lib/node_modules/promised-io
npm verb from cache /opt/lib/node_modules/promised-io/package.json
npm verb linkStuff [ true, '/opt/lib/node_modules', true, '/opt/lib/node_modules' ]
[cut]

My script fails on require('promised-io/promise'):

[neek@uberneek project]$ node buildscripts/stringsmerge.js 

module.js:340
    throw err;
          ^
Error: Cannot find module 'promised-io/promise'
    at Function.Module._resolveFilename (module.js:338:15)

I probably installed node and npm from source using configure --prefix=/opt. I've no idea why this has made them incapable of finding installed modules. The fix for now is to point NODE_PATH at the right directory:

export NODE_PATH=/opt/lib/node_modules

My require('promised-io/promise') now succeeds.

How to use boolean 'and' in Python

You can also test them as a couple.

if (i,ii)==(5,10):
    print "i is 5 and ii is 10"