Programs & Examples On #Tar

An archiving program for storing and retrieving files as a collection with support for data compression.

Create a .tar.bz2 file Linux

You are not indicating what to include in the archive.

Go one level outside your folder and try:

sudo tar -cvjSf folder.tar.bz2 folder

Or from the same folder try

sudo tar -cvjSf folder.tar.bz2 *

Cheers!

what does -zxvf mean in tar -zxvf <filename>?

  • z means (un)z_ip.
  • x means ex_tract files from the archive.
  • v means print the filenames v_erbosely.
  • f means the following argument is a f_ilename.

For more details, see tar's man page.

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

Another easy way to circumvent google's check is to use another compression algorithm with tar, like bz2:

tar -cvjf my.tar.bz2 dir/

Note that 'j' (for bz2 compression) is used above instead of 'z' (gzip compression).

tar: add all files and directories in current directory INCLUDING .svn and so on

Actually the problem is with the compression options. The trick is the pipe the tar result to a compressor instead of using the built-in options. Incidentally that can also give you better compression, since you can set extra compresion options.

Minimal tar:

tar --exclude=*.tar* -cf workspace.tar .

Pipe to a compressor of your choice. This example is verbose and uses xz with maximum compression:

tar --exclude=*.tar* -cv . | xz -9v >workspace.tar.xz

Solution was tested on Ubuntu 14.04 and Cygwin on Windows 7. It's a community wiki answer, so feel free to edit if you spot a mistake.

Find files and tar them (with spaces)

Another solution as seen here:

find var/log/ -iname "anaconda.*" -exec tar -cvzf file.tar.gz {} +

How do I tar a directory of files and folders without including the directory itself?

cd my_directory && tar -czvf ../my_directory.tar.gz $(ls -A) && cd ..

This one worked for me and it's include all hidden files without putting all files in a root directory named "." like in tomoe's answer :

Tar a directory, but don't store full absolute paths in the archive

Using the "point" leads to the creation of a folder named "point" (on Ubuntu 16).

tar -tf site1.bz2 -C /var/www/site1/ .

I dealt with this in more detail and prepared an example. Multi-line recording, plus an exception.

tar -tf site1.bz2\
    -C /var/www/site1/ style.css\
    -C /var/www/site1/ index.html\
    -C /var/www/site1/ page2.html\
    -C /var/www/site1/ page3.html\
    --exclude=images/*.zip\
    -C /var/www/site1/ images/
    -C /var/www/site1/ subdir/
/

Excluding directory when creating a .tar.gz file

This worked for me:

tar -zcvf target.tar.gz target/ --exclude="target/backups" --exclude="target/cache"

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

cd /Whatever/Directory/Path/The/File/Is/In

chmod +x xampp-linux-x64-7.0.6-0-installer.run

sudo ./xampp-linux-x64-7.0.6-0-installer.run

It works

For more information refer https://forums.linuxmint.com/viewtopic.php?t=223639

How to extract filename.tar.gz file

I have the same error the result of command :

file hadoop-2.7.2.tar.gz

is hadoop-2.7.2.tar.gz: HTML document, ASCII text

the reason that the file is not gzip format due to problem in download or other.

Shell command to tar directory excluding certain files/folders

Success Case: 1) if giving full path to take backup, in exclude also should be used full path.

tar -zcvf /opt/ABC/BKP_27032020/backup_27032020.tar.gz --exclude='/opt/ABC/csv/' --exclude='/opt/ABC/log/' /opt/ABC

2) if giving current path to take backup, in exclude also should be used current path only.

tar -zcvf backup_27032020.tar.gz --exclude='ABC/csv/' --exclude='ABC/log/' ABC

Failure Case:

  1. if giving currentpath directory to take backup and full path to ignore,then wont work

    tar -zcvf /opt/ABC/BKP_27032020/backup_27032020.tar.gz --exclude='/opt/ABC/csv/' --exclude='/opt/ABC/log/' ABC

Note: mentioning exclude before/after backup directory is fine.

How to uncompress a tar.gz in another directory

Extracts myArchive.tar to /destinationDirectory

Commands:

cd /destinationDirectory
pax -rv -f myArchive.tar -s ',^/,,'

Utilizing multi core for tar+gzip/bzip compression/decompression

If you want to have more flexibility with filenames and compression options, you can use:

find /my/path/ -type f -name "*.sql" -o -name "*.log" -exec \
tar -P --transform='s@/my/path/@@g' -cf - {} + | \
pigz -9 -p 4 > myarchive.tar.gz

Step 1: find

find /my/path/ -type f -name "*.sql" -o -name "*.log" -exec

This command will look for the files you want to archive, in this case /my/path/*.sql and /my/path/*.log. Add as many -o -name "pattern" as you want.

-exec will execute the next command using the results of find: tar

Step 2: tar

tar -P --transform='s@/my/path/@@g' -cf - {} +

--transform is a simple string replacement parameter. It will strip the path of the files from the archive so the tarball's root becomes the current directory when extracting. Note that you can't use -C option to change directory as you'll lose benefits of find: all files of the directory would be included.

-P tells tar to use absolute paths, so it doesn't trigger the warning "Removing leading `/' from member names". Leading '/' with be removed by --transform anyway.

-cf - tells tar to use the tarball name we'll specify later

{} + uses everyfiles that find found previously

Step 3: pigz

pigz -9 -p 4

Use as many parameters as you want. In this case -9 is the compression level and -p 4 is the number of cores dedicated to compression. If you run this on a heavy loaded webserver, you probably don't want to use all available cores.

Step 4: archive name

> myarchive.tar.gz

Finally.

Create a tar.xz in one command

Use the -J compression option for xz. And remember to man tar :)

tar cfJ <archive.tar.xz> <files>

Edit 2015-08-10:

If you're passing the arguments to tar with dashes (ex: tar -cf as opposed to tar cf), then the -f option must come last, since it specifies the filename (thanks to @A-B-B for pointing that out!). In that case, the command looks like:

tar -cJf <archive.tar.xz> <files>

tar: file changed as we read it

I also encounter the tar messages "changed as we read it". For me these message occurred when I was making tar file of Linux file system in bitbake build environment. This error was sporadic.

For me this was not due to creating tar file from the same directory. I am assuming there is actually some file overwritten or changed during tar file creation.

The message is a warning and it still creates the tar file. We can still suppress these warning message by setting option

--warning=no-file-changed

(http://www.gnu.org/software/tar/manual/html_section/warnings.html )

Still the exit code return by the tar is "1" in warning message case: http://www.gnu.org/software/tar/manual/html_section/Synopsis.html

So if we are calling the tar file from some function in scripts, we can handle the exit code something like this:

set +e 
tar -czf sample.tar.gz dir1 dir2
exitcode=$?

if [ "$exitcode" != "1" ] && [ "$exitcode" != "0" ]; then
    exit $exitcode
fi
set -e

How to check if a Unix .tar.gz file is a valid file without uncompressing?

A nice option is to use tar -tvvf <filePath> which adds a line that reports the kind of file.

Example in a valid .tar file:

> tar -tvvf filename.tar 
drwxr-xr-x  0 diegoreymendez staff       0 Jul 31 12:46 ./testfolder2/
-rw-r--r--  0 diegoreymendez staff      82 Jul 31 12:46 ./testfolder2/._.DS_Store
-rw-r--r--  0 diegoreymendez staff    6148 Jul 31 12:46 ./testfolder2/.DS_Store
drwxr-xr-x  0 diegoreymendez staff       0 Jul 31 12:42 ./testfolder2/testfolder/
-rw-r--r--  0 diegoreymendez staff      82 Jul 31 12:42 ./testfolder2/testfolder/._.DS_Store
-rw-r--r--  0 diegoreymendez staff    6148 Jul 31 12:42 ./testfolder2/testfolder/.DS_Store
-rw-r--r--  0 diegoreymendez staff  325377 Jul  5 09:50 ./testfolder2/testfolder/Scala.pages
Archive Format: POSIX ustar format,  Compression: none

Corrupted .tar file:

> tar -tvvf corrupted.tar 
tar: Unrecognized archive format
Archive Format: (null),  Compression: none
tar: Error exit delayed from previous errors.

tar: Error is not recoverable: exiting now

I would try to unzip and untar separately and see what happens:

mv Doctrine-1.2.0.tgz Doctrine-1.2.0.tar.gz
gunzip Doctrine-1.2.0.tar.gz
tar xf Doctrine-1.2.0.tar

Tar archiving that takes input from a list of files

Some versions of tar, for example, the default versions on HP-UX (I tested 11.11 and 11.31), do not include a command line option to specify a file list, so a decent work-around is to do this:

tar cvf allfiles.tar $(cat mylist.txt)

How to tar certain file types in all subdirectories?

find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -I 'pigz -9' -cf target.tgz

for multicore or just for one core:

find ./ -type f -name "*.php" -o -name "*.html" -printf '%P\n' |xargs tar -czf target.tgz

How do I set up HttpContent for my HttpClient PostAsync second parameter?

To add to Preston's answer, here's the complete list of the HttpContent derived classes available in the standard library:

Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

There's also a supposed ObjectContent but I was unable to find it in ASP.NET Core.

Of course, you could skip the whole HttpContent thing all together with Microsoft.AspNet.WebApi.Client extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:

var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
    Title = "New Article Title",
    Body = "New Article Body"
});

Create Elasticsearch curl query for not null and not empty("")

Wrap a Missing Filter in the Must-Not section of a Bool Filter. It will only return documents where the field exists, and if you set the "null_value" property to true, values that are explicitly not null.

{
  "query":{
     "filtered":{
        "query":{
           "match_all":{}
        },
        "filter":{
            "bool":{
              "must":{},
              "should":{},
              "must_not":{
                 "missing":{
                    "field":"field1",
                    "existence":true,
                    "null_value":true
                 }
              }
           }
        }
     }
  }
}

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

binary tree :

No need to consider values, we need to look at the structrue.

Given by (2 power n) - n

Eg: for three nodes it is (2 power 3) -3 = 8-3 = 5 different structrues

binary search tree:

We need to consider even the node values. We call it as Catalan Number

Given by 2n C n / n+1

How to use regex in file find

Start with:

find . -name '*.log.*.zip' -a -mtime +1

You may not need a regex, try:

 find . -name '*.log.*-*-*.zip' -a -mtime +1

You will want the +1 in order to match 1, 2, 3 ...

How do I make jQuery wait for an Ajax call to finish before it returns?

The underlying XMLHttpRequest object (used by jQuery to make the request) supports the asynchronous property. Set it to false. Like

async: false

Convert hex string (char []) to int?

Have you tried strtol()?

strtol - convert string to a long integer

Example:

const char *hexstring = "abcdef0";
int number = (int)strtol(hexstring, NULL, 16);

In case the string representation of the number begins with a 0x prefix, one must should use 0 as base:

const char *hexstring = "0xabcdef0";
int number = (int)strtol(hexstring, NULL, 0);

(It's as well possible to specify an explicit base such as 16, but I wouldn't recommend introducing redundancy.)

Database Structure for Tree Data Structure

You mention the most commonly implemented, which is Adjacency List: https://blogs.msdn.microsoft.com/mvpawardprogram/2012/06/25/hierarchies-convert-adjacency-list-to-nested-sets

There are other models as well, including materialized path and nested sets: http://communities.bmc.com/communities/docs/DOC-9902

Joe Celko has written a book on this subject, which is a good reference from a general SQL perspective (it is mentioned in the nested set article link above).

Also, Itzik Ben-Gann has a good overview of the most common options in his book "Inside Microsoft SQL Server 2005: T-SQL Querying".

The main things to consider when choosing a model are:

1) Frequency of structure change - how frequently does the actual structure of the tree change. Some models provide better structure update characteristics. It is important to separate structure changes from other data changes however. For example, you may want to model a company's organizational chart. Some people will model this as an adjacency list, using the employee ID to link an employee to their supervisor. This is usually a sub-optimal approach. An approach that often works better is to model the org structure separate from employees themselves, and maintain the employee as an attribute of the structure. This way, when an employee leaves the company, the organizational structure itself does not need to be changes, just the association with the employee that left.

2) Is the tree write-heavy or read-heavy - some structures work very well when reading the structure, but incur additional overhead when writing to the structure.

3) What types of information do you need to obtain from the structure - some structures excel at providing certain kinds of information about the structure. Examples include finding a node and all its children, finding a node and all its parents, finding the count of child nodes meeting certain conditions, etc. You need to know what information will be needed from the structure to determine the structure that will best fit your needs.

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

I had this error message. The problem was that I declared a virtual destructor in the header file, but the virtual functions' body was actually not implemented.

How to get autocomplete in jupyter notebook without using tab?

There is an extension called Hinterland for jupyter, which automatically displays the drop down menu when typing. There are also some other useful extensions.

In order to install extensions, you can follow the guide on this github repo. To easily activate extensions, you may want to use the extensions configurator.

How can I right-align text in a DataGridView column?

this.dataGridView1.Columns["CustomerName"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; 

Calculating frames per second in a game

How i do it!

boolean run = false;

int ticks = 0;

long tickstart;

int fps;

public void loop()
{
if(this.ticks==0)
{
this.tickstart = System.currentTimeMillis();
}
this.ticks++;
this.fps = (int)this.ticks / (System.currentTimeMillis()-this.tickstart);
}

In words, a tick clock tracks ticks. If it is the first time, it takes the current time and puts it in 'tickstart'. After the first tick, it makes the variable 'fps' equal how many ticks of the tick clock divided by the time minus the time of the first tick.

Fps is an integer, hence "(int)".

How can I count the occurrences of a list item?

It was suggested to use numpy's bincount, however it works only for 1d arrays with non-negative integers. Also, the resulting array might be confusing (it contains the occurrences of the integers from min to max of the original list, and sets to 0 the missing integers).

A better way to do it with numpy is to use the unique function with the attribute return_counts set to True. It returns a tuple with an array of the unique values and an array of the occurrences of each unique value.

# a = [1, 1, 0, 2, 1, 0, 3, 3]
a_uniq, counts = np.unique(a, return_counts=True)  # array([0, 1, 2, 3]), array([2, 3, 1, 2]

and then we can pair them as

dict(zip(a_uniq, counts))  # {0: 2, 1: 3, 2: 1, 3: 2}

It also works with other data types and "2d lists", e.g.

>>> a = [['a', 'b', 'b', 'b'], ['a', 'c', 'c', 'a']]
>>> dict(zip(*np.unique(a, return_counts=True)))
{'a': 3, 'b': 3, 'c': 2}

How can I check for an empty/undefined/null string in JavaScript?

You can easily add it to native String object in JavaScript and reuse it over and over...
Something simple like below code can do the job for you if you want to check '' empty strings:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
  return !(!!this.length);
}

Otherwise if you'd like to check both '' empty string and ' ' with space, you can do that by just adding trim(), something like the code below:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
   return !(!!this.trim().length);
}

and you can call it this way:

''.isEmpty(); //return true
'alireza'.isEmpty(); //return false

Display text on MouseOver for image in html

You can use CSS hover in combination with an image background.

CSS

   .image
{
    background:url(images/back.png);
    height:100px;
    width:100px;
    display: block;
    float:left;
}

.image  a {
    display: none;
}

.image  a:hover {
    display: block;
}

HTML

<div class="image"><a href="#">Text you want on mouseover</a></div>

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Solution 1 - you need to change your backend to accept your incoming requests

Solution 2 - using Angular proxy see here

Please note this is only for ng serve, you can't use proxy in ng build

Note: the reason it's working via postman is postman doesn't send preflight requests while your browser does.

How do I convert an integer to string as part of a PostgreSQL query?

You could do this:

SELECT * FROM table WHERE cast(YOUR_INTEGER_VALUE as varchar) = 'string of numbers'

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

Personally, I have create a file.sh (right 755) in the root directory, file who do this job, on order of the crontab.

Crontab code:

10 2 * * * root /root/backupautomatique.sh

File.sh code:

rm -f /home/mordb-148-251-89-66.sql.gz #(To erase the old one)

mysqldump mor | gzip > /home/mordb-148-251-89-66.sql.gz (what you have done)

scp -P2222 /home/mordb-148-251-89-66.sql.gz root@otherip:/home/mordbexternes/mordb-148-251-89-66.sql.gz

(to send a copy somewhere else if the sending server crashes, because too old, like me ;-))

How do I create a new branch?

Right click and open SVN Repo-browser:

Enter image description here

Right click on Trunk (working copy) and choose Copy to...:

Enter image description here

Input the respective branch's name/path:

Enter image description here

Click OK, type the respective log message, and click OK.

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

JavaScript isset() equivalent

if (var) {
  // This is the most concise equivalent of Php's isset().
} 

Create a string with n characters

RandomStringUtils has a provision to create a string from given input size. Cant comment on the speed, but its a one liner.

RandomStringUtils.random(5,"\t");

creates an output

\t\t\t\t\t

preferable if you dont want to see \0 in your code.

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

This is all you need to:

  1. Add the id column
  2. Populate it with a sequence from 1 to count(*).
  3. Set it as primary key / not null.

Credit is given to @resnyanskiy who gave this answer in a comment.

user authentication libraries for node.js?

Here is some code for basic authentication from one of my projects. I use it against CouchDB with and additional auth data cache, but I stripped that code.

Wrap an authentication method around you request handling, and provide a second callback for unsuccessfull authentication. The success callback will get the username as an additional parameter. Don't forget to correctly handle requests with wrong or missing credentials in the failure callback:

/**
 * Authenticate a request against this authentication instance.
 * 
 * @param request
 * @param failureCallback
 * @param successCallback
 * @return
 */
Auth.prototype.authenticate = function(request, failureCallback, successCallback)
{
    var requestUsername = "";
    var requestPassword = "";
    if (!request.headers['authorization'])
    {
        failureCallback();
    }
    else
    {
        var auth = this._decodeBase64(request.headers['authorization']);
        if (auth)
        {
            requestUsername = auth.username;
            requestPassword = auth.password;
        }
        else
        {
            failureCallback();
        }
    }


    //TODO: Query your database (don't forget to do so async)


    db.query( function(result)
    {
        if (result.username == requestUsername && result.password == requestPassword)
        {
            successCallback(requestUsername);
        }
        else
        {
            failureCallback();
        }
    });

};


/**
 * Internal method for extracting username and password out of a Basic
 * Authentication header field.
 * 
 * @param headerValue
 * @return
 */
Auth.prototype._decodeBase64 = function(headerValue)
{
    var value;
    if (value = headerValue.match("^Basic\\s([A-Za-z0-9+/=]+)$"))
    {
        var auth = (new Buffer(value[1] || "", "base64")).toString("ascii");
        return {
            username : auth.slice(0, auth.indexOf(':')),
            password : auth.slice(auth.indexOf(':') + 1, auth.length)
        };
    }
    else
    {
        return null;
    }

};

ImportError: No module named dateutil.parser

If you are using Pipenv, you may need to add this to your Pipfile:

[packages]
python-dateutil = "*"

Best way to combine two or more byte arrays in C#

If you simply need a new byte array, then use the following:

byte[] Combine(byte[] a1, byte[] a2, byte[] a3)
{
    byte[] ret = new byte[a1.Length + a2.Length + a3.Length];
    Array.Copy(a1, 0, ret, 0, a1.Length);
    Array.Copy(a2, 0, ret, a1.Length, a2.Length);
    Array.Copy(a3, 0, ret, a1.Length + a2.Length, a3.Length);
    return ret;
}

Alternatively, if you just need a single IEnumerable, consider using the C# 2.0 yield operator:

IEnumerable<byte> Combine(byte[] a1, byte[] a2, byte[] a3)
{
    foreach (byte b in a1)
        yield return b;
    foreach (byte b in a2)
        yield return b;
    foreach (byte b in a3)
        yield return b;
}

SQL Developer is returning only the date, not the time. How do I fix this?

Well I found this way :

Oracle SQL Developer (Left top icon) > Preferences > Database > NLS and set the Date Format as MM/DD/YYYY HH24:MI:SS

enter image description here

Run all SQL files in a directory

For executing every SQLfile on the same directory use the following command:

ls | awk '{print "@"$0}' > all.sql

This command will create a single SQL file with the names of every SQL file in the directory appended by "@".

After the all.sql is created simply execute all.sql with SQLPlus, this will execute every sql file in the all.sql.

Eclipse - java.lang.ClassNotFoundException

Furthermore, DOUBLE-CHECK the eclipse "Web Deployment Assembly" dialog.

This can be found: Project Properties->Deployment Assembly.

Recently I had an eclipse plugin modify one of my web projects, and it added ~mysteriously~ added the maven test directories /src/test/java, /src/test/resources to the Deployment Assembly. UGGGG!!!

Which is why my project worked fine when I built & deployed just straight maven to tomcat, no ClassNotFoundExceptions... However, when I did the deploy through Eclipse, Whammo!! I start getting ClassNotFoundExceptions because the TestCode is getting deployed.

Eric

100% Min Height CSS layout

I agree with Levik as the parent container is set to 100% if you have sidebars and want them to fill the space to meet up with the footer you cannot set them to 100% because they will be 100 percent of the parent height as well which means that the footer ends up getting pushed down when using the clear function.

Think of it this way if your header is say 50px height and your footer is 50px height and the content is just autofitted to the remaining space say 100px for example and the page container is 100% of this value its height will be 200px. Then when you set the sidebar height to 100% it is then 200px even though it is supposed to fit snug in between the header and footer. Instead it ends up being 50px + 200px + 50px so the page is now 300px because the sidebars are set to the same height as the page container. There will be a big white space in the contents of the page.

I am using internet Explorer 9 and this is what I am getting as the effect when using this 100% method. I havent tried it in other browsers and I assume that it may work in some of the other options. but it will not be universal.

JavaScript loop through json array?

your data snippet need to be expanded a little, and it has to be this way to be proper json. notice I just include the array name attribute "item"

{"item":[
{
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "[email protected]"
}, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "[email protected]"
}]}

your java script is simply

var objCount = json.item.length;
for ( var x=0; x < objCount ; xx++ ) {
    var curitem = json.item[x];
}

linux find regex

Regular expressions with character classes (e.g. [[:digit:]]) are not supported in the default regular expression syntax used by find. You need to specify a different regex type such as posix-extended in order to use them.

Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.

Twitter Bootstrap and ASP.NET GridView

Just for the record, I got borders in the table and to get rid of it I needed to set following properties in the GridView:

GridLines="None"
CellSpacing="-1"

jQuery: select all elements of a given class, except for a particular Id

Using the .not() method with selecting an entire element is also an option.

This way could be usefull if you want to do another action with that element directly.

$(".thisClass").not($("#thisId")[0].doAnotherAction()).doAction();

Opening a remote machine's Windows C drive

By default, Windows makes the root of each drive available (provided you've got Administrator privileges) as (e.g.) \\server\c$. These are known as Administrative Shares.

PHP Date Time Current Time Add Minutes

The question is a little old, but I come back to it often ;p

Another way, which is also a one liner:

<?= date_create('2111-11-11 00:00:00')->modify("+30 minutes")->format('Y-m-d h:i:s') ?>

Or from timestamp, returns Y-m-d h:i:s:

<?= date_create('@'.time())->modify("+30 minutes")->format('Y-m-d h:i:s') ?>

Or from timestamp, returns timestamp:

<?= date_create('@'.time())->modify("+30 minutes")->format('U') ?>

Create html documentation for C# code

Doxygen or Sandcastle help file builder are the primary tools that will extract XML documentation into HTML (and other forms) of external documentation.

Note that you can combine these documentation exporters with documentation generators - as you've discovered, Resharper has some rudimentary helpers, but there are also much more advanced tools to do this specific task, such as GhostDoc (for C#/VB code with XML documentation) or my addin Atomineer Pro Documentation (for C#, C++/CLI, C++, C, VB, Java, JavaScript, TypeScript, JScript, PHP, Unrealscript code containing XML, Doxygen, JavaDoc or Qt documentation).

Oracle date to string conversion

Try this. Oracle has this feature to distinguish the millennium years..

As you mentioned, if your column is a varchar, then the below query will yield you 1989..

select to_date(column_name,'dd/mm/rr') from table1;

When the format rr is used in year, the following would be done by oracle.

if rr->00 to 49 ---> result will be 2000 - 2049, if rr->50 to 99 ---> result will be 1950 - 1999

Ansible date variable

I tried the lookup('pipe,'date') method and got trouble when I push the playbook to the tower. The tower is somehow using UTC timezone. All play executed as early as the + hours of my TZ will give me one day later of the actual date.

For example: if my TZ is Asia/Manila I supposed to have UTC+8. If I execute the playbook earlier than 8:00am in Ansible Tower, the date will follow to what was in UTC+0. It took me a while until I found this case. It let me use the date option '-d \"+8 hours\" +%F'. Now it gives me the exact date that I wanted.

Below is the variable I set in my playbook:

  vars:
    cur_target_wd: "{{ lookup('pipe','date -d \"+8 hours\" +%Y/%m-%b/%d-%a') }}"

That will give me the value of "cur_target_wd = 2020/05-May/28-Thu" even I run it earlier than 8:00am now.

How to get a json string from url?

Use the WebClient class in System.Net:

var json = new WebClient().DownloadString("url");

Keep in mind that WebClient is IDisposable, so you would probably add a using statement to this in production code. This would look like:

using (WebClient wc = new WebClient())
{
   var json = wc.DownloadString("url");
}

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

line breaks in a textarea

You can use following code:

$course_description = nl2br($_POST["course_description"]);
$course_description = trim($course_description);

How to present popover properly in iOS 8

Swift 2.0

Well I worked out. Have a look. Made a ViewController in StoryBoard. Associated with PopOverViewController class.

import UIKit

class PopOverViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()    
        self.preferredContentSize = CGSizeMake(200, 200)    
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss:")    
    }    
    func dismiss(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}      

See ViewController:

//  ViewController.swift

import UIKit

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate
{
    func showPopover(base: UIView)
    {
        if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("popover") as? PopOverViewController {    

            let navController = UINavigationController(rootViewController: viewController)
            navController.modalPresentationStyle = .Popover

            if let pctrl = navController.popoverPresentationController {
                pctrl.delegate = self

                pctrl.sourceView = base
                pctrl.sourceRect = base.bounds

                self.presentViewController(navController, animated: true, completion: nil)
            }
        }
    }    
    override func viewDidLoad(){
        super.viewDidLoad()
    }    
    @IBAction func onShow(sender: UIButton)
    {
        self.showPopover(sender)
    }    
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return .None
    }
}  

Note: The func showPopover(base: UIView) method should be placed before ViewDidLoad. Hope it helps !

Bootstrap 3 Gutter Size

I tried several of the options here. For all that I tried, the spacing was uneven, or was even but when I shrank the window width enough for the subviews to stack, there was no space between stacked views.

Here is what worked for me.

.col-sm-12 { 
  margin-bottom: 2em;
}
<div class="container">
    <div class="row">
        <div class="col-sm-6">
            <div class="col-sm-12">

            </div>
        </div>
        <div class="col-sm-6">
            <div class="col-sm-12">

            </div>
        </div>
    </div>
</div>

Should import statements always be at the top of a module?

This is like many other optimizations - you sacrifice some readability for speed. As John mentioned, if you've done your profiling homework and found this to be a significantly useful enough change and you need the extra speed, then go for it. It'd probably be good to put a note up with all the other imports:

from foo import bar
from baz import qux
# Note: datetime is imported in SomeClass below

How to add chmod permissions to file in Git?

Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644 or 755 (spelled (100644 and 100755; the 100 part means "regular file"):

diff --git a/path b/path
new file mode 100644

The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask setting, which would normally be 022 to remove write permission from "group" and "other", or 002 to remove write permission only from "other". It might also be 077 if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".


1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664 in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.

The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.

PHPMyAdmin Default login password

This is asking for your MySQL username and password.

You should enter these details, which will default to "root" and "" (i.e.: nothing) if you've not specified a password.

BitBucket - download source as ZIP

Now Its Updated and very easy to download!

Select your repository from Dashboard or Repository tab.

And then just click on Download tab having icon of download. It will Let you download whole repository in zip format.

enter image description here

Postgres: clear entire database before re-creating / re-populating from bash script

To dump:

pg_dump -Fc mydb > db.dump

To restore:

pg_restore --verbose --clean --no-acl --no-owner -h localhost -U myuser -d my_db db/latest.dump

What is the iPhone 4 user-agent?

iOS 4.3.2's User Agent, which came out this week, is:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5

Batch / Find And Edit Lines in TXT file

On a native Windows install, you can either use batch(cmd.exe) or vbscript without the need to get external tools. Here's an example in vbscript:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    If InStr(strLine,"ex3")> 0 Then
        strLine = Replace(strLine,"ex3","ex5")
    End If 
    WScript.Echo strLine
Loop    

Save as myreplace.vbs and on the command line:

c:\test> cscript /nologo myreplace.vbs  > newfile
c:\test> ren newfile file.txt

fail to change placeholder color with Bootstrap 3

With LESS the actual mixin is in vendor-prefixes.less

.placeholder(@color: @input-color-placeholder) {
...
}

This mixin is called in forms.less on line 133:

.placeholder();

Your solution in LESS is:

.placeholder(#fff);

Imho the best way to go. Just use Winless or a composer compiler like Gulp/Grunt works, too and even better/faster.

How can I determine whether a specific file is open in Windows?

Use Process Explorer from the Sysinternals Suite, the Find Handle or DLL function will let you search for the process with that file open.

How to check if activity is in foreground or in visible background?

I have to say your workflow is not in a standard Android way. In Android, you don't need to finish() your activity if you want to open another activity from Intent. As for user's convenience, Android allows user to use 'back' key to go back from the activity that you opened to your app.

So just let the system stop you activity and save anything need to when you activity is called back.

Tomcat 8 is not able to handle get request with '|' in query parameters?

Escape it. The pipe symbol is one that has been handled differently over time and between browsers. For instance, Chrome and Firefox convert a URL with pipe differently when copy/paste them. However, the most compatible, and necessary with Tomcat 8.5 it seems, is to escape it:

http://localhost:8080/app/handleResponse?msg=name%7Cid%7C

HTTP POST using JSON in Java

Here is what you need to do:

  1. Get the Apache HttpClient, this would enable you to make the required request
  2. Create an HttpPost request with it and add the header application/x-www-form-urlencoded
  3. Create a StringEntity that you will pass JSON to it
  4. Execute the call

The code roughly looks like (you will still need to debug it and make it work):

// @Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params = new StringEntity("details={\"name\":\"xyz\",\"age\":\"20\"} ");
    request.addHeader("content-type", "application/x-www-form-urlencoded");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
    // @Deprecated httpClient.getConnectionManager().shutdown(); 
}

Using local makefile for CLion instead of CMake

Update: If you are using CLion 2020.2, then it already supports Makefiles. If you are using an older version, read on.


Even though currently only CMake is supported, you can instruct CMake to call make with your custom Makefile. Edit your CMakeLists.txt adding one of these two commands:

When you tell CLion to run your program, it will try to find an executable with the same name of the target in the directory pointed by PROJECT_BINARY_DIR. So as long as your make generates the file where CLion expects, there will be no problem.

Here is a working example:

Tell CLion to pass its $(PROJECT_BINARY_DIR) to make

This is the sample CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.4)
project(mytest)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

add_custom_target(mytest COMMAND make -C ${mytest_SOURCE_DIR}
                         CLION_EXE_DIR=${PROJECT_BINARY_DIR})

Tell make to generate the executable in CLion's directory

This is the sample Makefile:

all:
    echo Compiling $(CLION_EXE_DIR)/$@ ...
    g++ mytest.cpp -o $(CLION_EXE_DIR)/mytest

That is all, you may also want to change your program's working directory so it executes as it is when you run make from inside your directory. For this edit: Run -> Edit Configurations ... -> mytest -> Working directory

How to prevent a background process from being stopped after closing SSH client in Linux

There's also the daemon command of the open-source libslack package.

daemon is quite configurable and does care about all the tedious daemon stuff such as automatic restart, logging or pidfile handling.

Split comma-separated values

.NET 2.0 does not support LINQ - SO thread;
But you can create a 3.5 project in VS2005 - MSDN thread

Without lambda support, you'll need to do something like this:

string s = "a,b, b, c";
string[] values = s.Split(',');
for(int i = 0; i < values.Length; i++)
{
   values[i] = values[i].Trim();
}

Cannot run the macro... the macro may not be available in this workbook

Go into task manager and see if you have any Microsoft Excel Processes running in the background. I closed my excel background processes and my code worked again.

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

How to get random value out of an array?

Another approach through flipping array to get direct value.

Snippet

$array = [ 'Name1' => 'John', 'Name2' => 'Jane', 'Name3' => 'Jonny' ];
$val = array_rand(array_flip($array));

array_rand return key not value. So, we're flipping value as key.

Note: PHP key alway be an unique key, so when array is flipped, duplicate value as a key will be overwritten.

PHP 5 disable strict standards error

WordPress

If you work in the wordpress environment, Wordpress sets the error level in file wp-includes/load.php in function wp_debug_mode(). So you have to change the level AFTER this function has been called ( in a file not checked into git so that's development only ), or either modify directly the error_reporting() call

Removing a non empty directory programmatically in C or C++

You want to write a function (a recursive function is easiest, but can easily run out of stack space on deep directories) that will enumerate the children of a directory. If you find a child that is a directory, you recurse on that. Otherwise, you delete the files inside. When you are done, the directory is empty and you can remove it via the syscall.

To enumerate directories on Unix, you can use opendir(), readdir(), and closedir(). To remove you use rmdir() on an empty directory (i.e. at the end of your function, after deleting the children) and unlink() on a file. Note that on many systems the d_type member in struct dirent is not supported; on these platforms, you will have to use stat() and S_ISDIR(stat.st_mode) to determine if a given path is a directory.

On Windows, you will use FindFirstFile()/FindNextFile() to enumerate, RemoveDirectory() on empty directories, and DeleteFile() to remove files.

Here's an example that might work on Unix (completely untested):

int remove_directory(const char *path) {
   DIR *d = opendir(path);
   size_t path_len = strlen(path);
   int r = -1;

   if (d) {
      struct dirent *p;

      r = 0;
      while (!r && (p=readdir(d))) {
          int r2 = -1;
          char *buf;
          size_t len;

          /* Skip the names "." and ".." as we don't want to recurse on them. */
          if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
             continue;

          len = path_len + strlen(p->d_name) + 2; 
          buf = malloc(len);

          if (buf) {
             struct stat statbuf;

             snprintf(buf, len, "%s/%s", path, p->d_name);
             if (!stat(buf, &statbuf)) {
                if (S_ISDIR(statbuf.st_mode))
                   r2 = remove_directory(buf);
                else
                   r2 = unlink(buf);
             }
             free(buf);
          }
          r = r2;
      }
      closedir(d);
   }

   if (!r)
      r = rmdir(path);

   return r;
}

In Android, how do I set margins in dp programmatically?

As today, the best is probably to use Paris, a library provided by AirBnB.

Styles can then be applied like this:

Paris.style(myView).apply(R.style.MyStyle);

it also support custom view (if you extend a view) using annotations:

@Styleable and @Style

How can I load storyboard programmatically from class?

For swift 3 and 4, you can do this. Good practice is set name of Storyboard equal to StoryboardID.

enum StoryBoardName{
   case second = "SecondViewController"
}
extension UIStoryBoard{
   class func load(_ storyboard: StoryBoardName) -> UIViewController{
      return UIStoryboard(name: storyboard.rawValue, bundle: nil).instantiateViewController(withIdentifier: storyboard.rawValue)
   }
}

and then you can load your Storyboard in your ViewController like this:

class MyViewController: UIViewController{
     override func viewDidLoad() {
        super.viewDidLoad()
        guard let vc = UIStoryboard.load(.second) as? SecondViewController else {return}
        self.present(vc, animated: true, completion: nil)
     }

}

When you create a new Storyboard just set the same name on StoryboardID and add Storyboard name in your enum "StoryBoardName"

Applying an ellipsis to multiline text

I took a look at how YouTube solves it on their homepage and simplified it:

.multine-ellipsis {
  -webkit-box-orient: vertical;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}

This will allow 2 lines of code and then append an ellipsis.

Gist: https://gist.github.com/eddybrando/386d3350c0b794ea87a2082bf4ab014b

Right to Left support for Twitter Bootstrap 3

you can use my project i create bootstrap 3 rtl with sass and gulp so you can easely customize it https://github.com/z-avanes/bootstrap3-rtl

How to display the current time and date in C#

For time:

label1.Text = DateTime.Now.ToString("HH:mm:ss"); //result 22:11:45

or

label1.Text = DateTime.Now.ToString("hh:mm:ss tt"); //result 11:11:45 PM

For date:

label1.Text = DateTime.Now.ToShortDateString(); //30.5.2012

Add days Oracle SQL

In a more general way you can use "INTERVAL". Here some examples:

1) add a day

select sysdate + INTERVAL '1' DAY from dual;

2) add 20 days

select sysdate + INTERVAL '20' DAY from dual;

2) add some minutes

select sysdate + INTERVAL '15' MINUTE from dual;

Disabled UIButton not faded or grey

To make the button is faded when disable, you can set alpha for it. There are two options for you:

First way: If you want to apply for all your buttons in your app, so you can write extension for UIButton like this:

extension UIButton {

    open override var isEnabled: Bool{
        didSet {
            alpha = isEnabled ? 1.0 : 0.5
        }
    }

}

Second way: If you just want to apply for some buttons in your app, so you can write a custom class from UIButton like below and use this class for which you want to apply:

class MyButton: UIButton {
    override var isEnabled: Bool {
        didSet {
            alpha = isEnabled ? 1.0 : 0.5
        }
    }
}

How to pass multiple arguments in processStartInfo?

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

use /c as a cmd argument to close cmd.exe once its finish processing your commands

How to remove "onclick" with JQuery?

Try this if you unbind the onclick event by ID Then use:

$('#youLinkID').attr('onclick','').unbind('click');

Try this if you unbind the onclick event by Class Then use:

$('.className').attr('onclick','').unbind('click');

Use tab to indent in textarea

$("textarea").keydown(function(event) {
    if(event.which===9){
        var cIndex=this.selectionStart;
        this.value=[this.value.slice(0,cIndex),//Slice at cursor index
            "\t",                              //Add Tab
            this.value.slice(cIndex)].join('');//Join with the end
        event.stopPropagation();
        event.preventDefault();                //Don't quit the area
        this.selectionStart=cIndex+1;
        this.selectionEnd=cIndex+1;            //Keep the cursor in the right index
    }
});

Check if key exists and iterate the JSON array using Python

jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        print("to_id:", dest.get('id', 'null'))

Try it:

>>> getTargetIds(jsonData)
to_id: 1543
to_id: null

Or, if you just want to skip over values missing ids instead of printing 'null':

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        if 'id' in to_id:
            print("to_id:", dest['id'])

So:

>>> getTargetIds(jsonData)
to_id: 1543

Of course in real life, you probably don't want to print each id, but to store them and do something with them, but that's another issue.

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

date.ToString("o") // The Round-trip ("O", "o") Format Specifier
date.ToString("s") // The Sortable ("s") Format Specifier, conforming to ISO86801

MSDN Standard Date and Time Format Strings

How to set the height and the width of a textfield in Java?

package myguo;
import javax.swing.*;

public class MyGuo {

    JFrame f;
    JButton bt1 , bt2 ;
    JTextField t1,t2;
    JLabel l1,l2;

    MyGuo(){

        f=new JFrame("LOG IN FORM");
        f.setLocation(500,300);
        f.setSize(600,500);
        f.setLayout(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        l1=new JLabel("NAME");
        l1.setBounds(50,70,80,30);

        l2=new JLabel("PASSWORD");
        l2.setBounds(50,100,80,30);

        t1=new JTextField();
        t1.setBounds(140, 70, 200,30);

         t2=new JTextField();
        t2.setBounds(140, 110, 200,30);

        bt1 =new JButton("LOG IN");
        bt1.setBounds(150,150,80,30);

        bt2 =new JButton("CLEAR");
        bt2.setBounds(235,150,80,30);

         f.add(l1);
        f.add(l2);
         f.add(t1);
         f.add(t2);
         f.add(bt1);
         f.add(bt2);

    f.setVisible(true);

    }
    public static void main(String[] args) {
        MyGuo myGuo = new MyGuo();
}
}

load scripts asynchronously

Thanks to HTML5, you can now declare the scripts that you want to load asynchronously by adding "async" in the tag:

<script async>...</script>

Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).

Note: There are several ways an external script can be executed:

  • If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)
  • If async is not present and defer is present: The script is executed when the page has finished parsing
  • If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page

See this: http://www.w3schools.com/tags/att_script_async.asp

Set the text in a span

This is because you have wrong selector. According to your markup, .ui-icon and .ui-icon-circle-triangle-w" should point to the same <span> element. So you should use:

$(".ui-icon.ui-icon-circle-triangle-w").html("<<");

or

$(".ui-datepicker-prev .ui-icon").html("<<");

or

$(".ui-datepicker-prev span").html("<<");

How do I get a Date without time in Java?

The most straightforward way:

long millisInDay = 60 * 60 * 24 * 1000;
long currentTime = new Date().getTime();
long dateOnly = (currentTime / millisInDay) * millisInDay;
Date clearDate = new Date(dateOnly);

must declare a named package eclipse because this compilation unit is associated to the named module

The "delete module-info.java at your Project Explorer tab" answer is the easiest and most straightforward answer, but

for those who would want a little more understanding or control of what's happening, the following alternate methods may be desirable;

  • make an ever so slightly more realistic application; com.YourCompany.etc or just com.HelloWorld (Project name: com.HelloWorld and class name: HelloWorld)

or

  • when creating the java project; when in the Create Java Project dialog, don't choose Finish but Next, and deselect Create module-info.java file

Efficiently test if a port is open on Linux?

You can use netcat for this.

nc ip port < /dev/null

connects to the server and directly closes the connection again. If netcat is not able to connect, it returns a non-zero exit code. The exit code is stored in the variable $?. As an example,

nc ip port < /dev/null; echo $?

will return 0 if and only if netcat could successfully connect to the port.

Send email with PHPMailer - embed image in body

I found the answer:

$mail->AddEmbeddedImage('img/2u_cs_mini.jpg', 'logo_2u');

and on the <img> tag put src='cid:logo_2u'

Is it not possible to stringify an Error using JSON.stringify?

You can define a Error.prototype.toJSON to retrieve a plain Object representing the Error:

if (!('toJSON' in Error.prototype))
Object.defineProperty(Error.prototype, 'toJSON', {
    value: function () {
        var alt = {};

        Object.getOwnPropertyNames(this).forEach(function (key) {
            alt[key] = this[key];
        }, this);

        return alt;
    },
    configurable: true,
    writable: true
});
var error = new Error('testing');
error.detail = 'foo bar';

console.log(JSON.stringify(error));
// {"message":"testing","detail":"foo bar"}

Using Object.defineProperty() adds toJSON without it being an enumerable property itself.


Regarding modifying Error.prototype, while toJSON() may not be defined for Errors specifically, the method is still standardized for objects in general (ref: step 3). So, the risk of collisions or conflicts is minimal.

Though, to still avoid it completely, JSON.stringify()'s replacer parameter can be used instead:

function replaceErrors(key, value) {
    if (value instanceof Error) {
        var error = {};

        Object.getOwnPropertyNames(value).forEach(function (key) {
            error[key] = value[key];
        });

        return error;
    }

    return value;
}

var error = new Error('testing');
error.detail = 'foo bar';

console.log(JSON.stringify(error, replaceErrors));

How to backup MySQL database in PHP?

Take a look here! It is a native solution written in php. You won't need to exec mysqldump, or cope with incomplete scripts. This is a full mysqldump clone, without dependencies, output compression and sane defaults.

Out of the box, mysqldump-php supports backing up table structures, the data itself, views, triggers and events.

MySQLDump-PHP is the only library that supports:

  • output binary blobs as hex.
  • resolves view dependencies (using Stand-In tables).
  • output compared against original mysqldump. Linked to travis-ci testing system (testing from php 5.3 to 7.1 & hhvm)
  • dumps stored procedures.
  • dumps events.
  • does extended-insert and/or complete-insert.
  • supports virtual columns from MySQL 5.7.

You can install it using composer, or just download the php file, and it is as easy as doing:

use Ifsnop\Mysqldump as IMysqldump;

try {
    $dump = new IMysqldump\Mysqldump('database', 'username', 'password');
    $dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
    echo 'mysqldump-php error: ' . $e->getMessage();
}

All the options are explained at the github page, but more or less are auto-explicative:

$dumpSettingsDefault = array(
    'include-tables' => array(),
    'exclude-tables' => array(),
    'compress' => Mysqldump::NONE,
    'init_commands' => array(),
    'no-data' => array(),
    'reset-auto-increment' => false,
    'add-drop-database' => false,
    'add-drop-table' => false,
    'add-drop-trigger' => true,
    'add-locks' => true,
    'complete-insert' => false,
    'databases' => false,
    'default-character-set' => Mysqldump::UTF8,
    'disable-keys' => true,
    'extended-insert' => true,
    'events' => false,
    'hex-blob' => true, /* faster than escaped content */
    'net_buffer_length' => self::MAXLINESIZE,
    'no-autocommit' => true,
    'no-create-info' => false,
    'lock-tables' => true,
    'routines' => false,
    'single-transaction' => true,
    'skip-triggers' => false,
    'skip-tz-utc' => false,
    'skip-comments' => false,
    'skip-dump-date' => false,
    'skip-definer' => false,
    'where' => '',
    /* deprecated */
    'disable-foreign-keys-check' => true
);

How to bind DataTable to Datagrid

You could use DataGrid in WPF

SqlDataAdapter da = new SqlDataAdapter("Select * from Table",con);
DataTable dt = new DataTable("Call Reciept");
da.Fill(dt);
DataGrid dg = new DataGrid();
dg.ItemsSource = dt.DefaultView;

Manually put files to Android emulator SD card

In Android Studio, open the Device Manager: Tools -> Android -> Android Device Monitor

In Eclipse open the Device Manager: enter image description here

In the device manager you can add files to the SD Card here: enter image description here

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

Typescript interface default values

It is depends on the case and the usage. Generally, in TypeScript there are no default values for interfaces.

If you don't use the default values
You can declare x as:

let x: IX | undefined; // declaration: x = undefined

Then, in your init function you can set real values:

x = {
    a: 'xyz'
    b: 123
    c: new AnotherType()
};

In this way, x can be undefined or defined - undefined represents that the object is uninitialized, without set the default values, if they are unnecessary. This is loggically better than define "garbage".

If you want to partially assign the object:
You can define the type with optional properties like:

interface IX {
    a: string,
    b?: any,
    c?: AnotherType
}

In this case you have to set only a. The other types are marked with ? which mean that they are optional and have undefined as default value.

In any case you can use undefined as a default value, it is just depends on your use case.

OrderBy descending in Lambda expression?

This only works in situations where you have a numeric field, but you can put a minus sign in front of the field name like so:

reportingNameGroups = reportingNameGroups.OrderBy(x=> - x.GroupNodeId);

However this works a little bit different than OrderByDescending when you have are running it on an int? or double? or decimal? fields.

What will happen is on OrderByDescending the nulls will be at the end, vs with this method the nulls will be at the beginning. Which is useful if you want to shuffle nulls around without splitting data into pieces and splicing it later.

ParseError: not well-formed (invalid token) using cElementTree

It seems to complain about \x08 you will need to escape that.

Edit:

Or you can have the parser ignore the errors using recover

from lxml import etree
parser = etree.XMLParser(recover=True)
etree.fromstring(xmlstring, parser=parser)

Should I use past or present tense in git commit messages?

Who are you writing the message for? And is that reader typically reading the message pre- or post- ownership the commit themselves?

I think good answers here have been given from both perspectives, I’d perhaps just fall short of suggesting there is a best answer for every project. The split vote might suggest as much.

i.e. to summarise:

  • Is the message predominantly for other people, typically reading at some point before they have assumed the change: A proposal of what taking the change will do to their existing code.

  • Is the message predominantly as a journal/record to yourself (or to your team), but typically reading from the perspective of having assumed the change and searching back to discover what happened.

Perhaps this will lead the motivation for your team/project, either way.

Windows batch script to move files

This is exactly how it worked for me. For some reason the above code failed.

This one runs a check every 3 minutes for any files in there and auto moves it to the destination folder. If you need to be prompted for conflicts then change the /y to /-y

:backup
move /y "D:\Dropbox\Dropbox\Camera Uploads\*.*" "D:\Archive\Camera Uploads\"
timeout 360
goto backup

Static array vs. dynamic array in C++

Static array :Efficiency. No dynamic allocation or deallocation is required.

Arrays declared in C, C++ in function including static modifier are static. Example: static int foo[5];

React-Router: No Not Found Route?

I just had a quick look at your example, but if i understood it the right way you're trying to add 404 routes to dynamic segments. I had the same issue a couple of days ago, found #458 and #1103 and ended up with a hand made check within the render function:

if (!place) return <NotFound />;

hope that helps!

Java Package Does Not Exist Error

Right click your maven project in bottom of the drop down list Maven >> reimport

it works for me for the missing dependancyies

Why are iframes considered dangerous and a security risk?

The IFRAME element may be a security risk if your site is embedded inside an IFRAME on hostile site. Google "clickjacking" for more details. Note that it does not matter if you use <iframe> or not. The only real protection from this attack is to add HTTP header X-Frame-Options: DENY and hope that the browser knows its job.

In addition, IFRAME element may be a security risk if any page on your site contains an XSS vulnerability which can be exploited. In that case the attacker can expand the XSS attack to any page within the same domain that can be persuaded to load within an <iframe> on the page with XSS vulnerability. This is because content from the same origin (same domain) is allowed to access the parent content DOM (practically execute JavaScript in the "host" document). The only real protection methods from this attack is to add HTTP header X-Frame-Options: DENY and/or always correctly encode all user submitted data (that is, never have an XSS vulnerability on your site - easier said than done).

That's the technical side of the issue. In addition, there's the issue of user interface. If you teach your users to trust that URL bar is supposed to not change when they click links (e.g. your site uses a big iframe with all the actual content), then the users will not notice anything in the future either in case of actual security vulnerability. For example, you could have an XSS vulnerability within your site that allows the attacker to load content from hostile source within your iframe. Nobody could tell the difference because the URL bar still looks identical to previous behavior (never changes) and the content "looks" valid even though it's from hostile domain requesting user credentials.

If somebody claims that using an <iframe> element on your site is dangerous and causes a security risk, he does not understand what <iframe> element does, or he is speaking about possibility of <iframe> related vulnerabilities in browsers. Security of <iframe src="..."> tag is equal to <img src="..." or <a href="..."> as long there are no vulnerabilities in the browser. And if there's a suitable vulnerability, it might be possible to trigger it even without using <iframe>, <img> or <a> element, so it's not worth considering for this issue.

However, be warned that content from <iframe> can initiate top level navigation by default. That is, content within the <iframe> is allowed to automatically open a link over current page location (the new location will be visible in the address bar). The only way to avoid that is to add sandbox attribute without value allow-top-navigation. For example, <iframe sandbox="allow-forms allow-scripts" ...>. Unfortunately, sandbox also disables all plugins, always. For example, Youtube content cannot be sandboxed because Flash player is still required to view all Youtube content. No browser supports using plugins and disallowing top level navigation at the same time.

Note that X-Frame-Options: DENY also protects from rendering performance side-channel attack that can read content cross-origin (also known as "Pixel perfect Timing Attacks").

Can I disable a CSS :hover effect via JavaScript?

You can manipulate the stylesheets and stylesheet rules themselves with javascript

var sheetCount = document.styleSheets.length;
var lastSheet = document.styleSheets[sheetCount-1];
var ruleCount;
if (lastSheet.cssRules) { // Firefox uses 'cssRules'
    ruleCount = lastSheet.cssRules.length;
}
else if (lastSheet.rules) { / /IE uses 'rules'
    ruleCount = lastSheet.rules.length;
}
var newRule = "a:hover { text-decoration: none !important; color: #000 !important; }";
// insert as the last rule in the last sheet so it
// overrides (not overwrites) previous definitions
lastSheet.insertRule(newRule, ruleCount);

Making the attributes !important and making this the very last CSS definition should override any previous definition, unless one is more specifically targeted. You may have to insert more rules in that case.

jquery remove "selected" attribute of option?

Using jQuery 1.9 and above:

$("#mySelect :selected").prop('selected', false);

Oracle SqlPlus - saving output in a file but don't show on screen

set termout off doesn't work from the command line, so create a file e.g. termout_off.sql containing the line:

set termout off

and call this from the SQL prompt:

SQL> @termout_off

Gson: Is there an easier way to serialize a map

Only the TypeToken part is neccesary (when there are Generics involved).

Map<String, String> myMap = new HashMap<String, String>();
myMap.put("one", "hello");
myMap.put("two", "world");

Gson gson = new GsonBuilder().create();
String json = gson.toJson(myMap);

System.out.println(json);

Type typeOfHashMap = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken
System.out.println(newMap.get("one"));
System.out.println(newMap.get("two"));

Output:

{"two":"world","one":"hello"}
hello
world

Checking for an empty file in C++

char ch;
FILE *f = fopen("file.txt", "r");

if(fscanf(f,"%c",&ch)==EOF)
{
    printf("File is Empty");
}
fclose(f);

How to remove a directory from git repository?

You can use Attlasian Source Tree (Windows) (https://www.atlassian.com/software/sourcetree/overview). Just select files from tree and push button "Remove" at the top. Files will be deleted from local repository and local git database. Then Commit, then push.

laravel collection to array

you can do something like this

$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();

Reference is https://laravel.com/docs/5.1/collections#method-toarray

Originally from Laracasts website https://laracasts.com/discuss/channels/laravel/how-to-convert-this-collection-to-an-array

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />

<context:component-scan base-package="com.tridenthyundai.ains" />

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

<bean id="messageSource" 
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages" />
</bean>

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

Join two data frames, select all columns from one and some columns from the other

I believe that this would be the easiest and most intuitive way:

final = (df1.alias('df1').join(df2.alias('df2'),
                               on = df1['id'] == df2['id'],
                               how = 'inner')
                         .select('df1.*',
                                 'df2.other')
)

How to use a client certificate to authenticate and authorize in a Web API

Looking at the source code I also think there must be some issue with the private key.

What it is doing is actually to check if the certificate that is passed is of type X509Certificate2 and if it has the private key.

If it doesn't find the private key it tries to find the certificate in the CurrentUser store and then in the LocalMachine store. If it finds the certificate it checks if the private key is present.

(see source code from class SecureChannnel, method EnsurePrivateKey)

So depending on which file you imported (.cer - without private key or .pfx - with private key) and on which store it might not find the right one and Request.ClientCertificate won't be populated.

You can activate Network Tracing to try to debug this. It will give you output like this:

  • Trying to find a matching certificate in the certificate store
  • Cannot find the certificate in either the LocalMachine store or the CurrentUser store.

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

Would the use of <caption> be allowed?

<ul>
  <caption> Title of List </caption>
  <li> Item 1 </li>
  <li> Item 2 </li>
</ul>

Get Line Number of certain phrase in file Python

Here's what I've found to work:

f_rd = open(path, 'r')
file_lines = f_rd.readlines()
f_rd.close()

matches = [line for line in file_lines if "chars of Interest" in line]
index = file_lines.index(matches[0])

Easiest way to toggle 2 classes in jQuery

Here's another 'non-conventional' way.

  • It implies the use of underscore or lodash.
  • It assumes a context where you:
    • the element doesn't have an init class (that means you cannot do toggleClass('a b'))
    • you have to get the class dynamically from somewhere

An example of this scenario could be buttons that has the class to be switched on another element (say tabs in a container).

// 1: define the array of switching classes:
var types = ['web','email'];

// 2: get the active class:
var type = $(mybutton).prop('class');

// 3: switch the class with the other on (say..) the container. You can guess the other by using _.without() on the array:
$mycontainer.removeClass(_.without(types, type)[0]).addClass(type);

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

SELECT * FROM TABLE
WHERE DATE BETWEEN '09/16/2010 05:00:00' and '09/21/2010 09:00:00'

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

Could not find a declaration file for module 'busboy'. 'f:/firebase-cloud- 
functions/functions/node_modules/busboy/lib/main.js' implicitly has an ‘any’ 
type.

Try `npm install @types/busboy` if it exists or add a new declaration (.d.ts) 
the file containing `declare module 'busboy';`

In my case it's solved: All you have to do is edit your TypeScript Config file (tsconfig.json) and add a new key-value pair as:

"noImplicitAny": false

How to insert a large block of HTML in JavaScript?

Despite the imprecise nature of the question, here's my interpretive answer.

var html = [
    '<div> A line</div>',
    '<div> Add more lines</div>',
    '<div> To the array as you need.</div>'
].join('');

var div = document.createElement('div');
    div.setAttribute('class', 'post block bc2');
    div.innerHTML = html;
    document.getElementById('posts').appendChild(div);

Flatten List in LINQ

Like this?

var iList = Method().SelectMany(n => n);

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Get an OutputStream into a String

baos.toString(StandardCharsets.UTF_8);

Converts the buffer's contents into a string by decoding the bytes using the named charset.

Java 14 - https://docs.oracle.com/

select data up to a space?

If the first column is always the same size (including the spaces), then you can just take those characters (via LEFT) and clean up the spaces (with RTRIM):

SELECT RTRIM(LEFT(YourColumn, YourColumnSize))

Alternatively, you can extract the second (or third, etc.) column (using SUBSTRING):

SELECT RTRIM(SUBSTRING(YourColumn, PreviousColumnSizes, YourColumnSize))

One benefit of this approach (especially if YourColumn is the result of a computation) is that YourColumn is only specified once.

Display A Popup Only Once Per User

You can use removeItem() class of localStorage to destroy that key on browser close with:

window.onbeforeunload = function{
    localStorage.removeItem('your key');
};

SELECT INTO a table variable in T-SQL

Try something like this:

DECLARE @userData TABLE(
    name varchar(30) NOT NULL,
    oldlocation varchar(30) NOT NULL
);

INSERT INTO @userData (name, oldlocation)
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;

What is the difference between a process and a thread?

From Erlang Programming (2009): Erlang concurrency is fast and scalable. Its processes are lightweight in that the Erlang virtual machine does not create an OS thread for every created process. They are created, scheduled, and handled in the VM, independent of underlying operating system.

Erlang implements a preemptive scheduler, which allows each process to run for a set period of time without blocking a system thread for too long, which gives each process some cpu time to be executed. The number of system threads depends on the number of cores if I'm not mistaking, and processes can be removed from one thread and moved to another if the load becomes uneven, this is all handled by the Erlang scheduler.

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

Regex for not empty and not whitespace

A little late, but here's a regex I found that returns 0 matches for empty or white spaces:

/^(?!\s*$).+/

You can test this out at regex101

Create a dictionary with list comprehension

Just to throw in another example. Imagine you have the following list:

nums = [4,2,2,1,3]

and you want to turn it into a dict where the key is the index and value is the element in the list. You can do so with the following line of code:

{index:nums[index] for index in range(0,len(nums))}

git diff between two different files

I believe using --no-index is what you're looking for:

git diff [<options>] --no-index [--] <path> <path>

as mentioned in the git manual:

This form is to compare the given two paths on the filesystem. You can omit the --no-index option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Adding the Tomcat server in the server runtime will do the job:

Project properties ? Java Build Path ? Add Library ? Select "Server Runtime" from the list ? Next ? Select "Apache Tomcat" ? Finish.

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

You would have to use the JavascriptExecutor class:

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('attr', '10')");

Good Linux (Ubuntu) SVN client

If you use eclipse, subclipse is the best I've ever used. In my opinion, this should exist as stand-alone as well... Easy to use, linked with the code and the project you have in eclipse... Just perfect for a developer who uses eclipse and wants a gui.

Personally, I prefer the command-line client, both for linux and windows.

Edit: if you use XFCE and its file manager (called Thunar), there's a plugin which works quite well. If I don't want to open the terminal, I just use that one, it has all the functionality, is fast and easy to use. There's also one for git included, though...

When should I use semicolons in SQL Server?

In SQL2008 BOL they say that in next releases semicolons will be required. Therefore, always use it.

Reference:

CSS content generation before or after 'input' elements

This is not due to input tags not having any content per-se, but that their content is outside the scope of CSS.

input elements are a special type called replaced elements, these do not support :pseudo selectors like :before and :after.

In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS. Typical replaced elements are <img>, <object>, <video> or form elements like <textarea> and <input>. Some elements, like <audio> or <canvas> are replaced elements only in specific cases. Objects inserted using the CSS content properties are anonymous replaced elements.

Note that this is even referred to in the spec:

This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML).

And more explicitly:

Replaced elements do not have ::before and ::after pseudo-elements

Mongoose's find method with $or condition does not work properly

According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."

So add indexes for your other fields and it will work. I had a similar problem and this solved it.

You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/

if (boolean == false) vs. if (!boolean)

The first form, when used with an API that returns Boolean and compared against Boolean.FALSE, will never throw a NullPointerException.

The second form, when used with the java.util.Map interface, also, will never throw a NullPointerException because it returns a boolean and not a Boolean.

If you aren't concerned about consistent coding idioms, then you can pick the one you like, and in this concrete case it really doesn't matter. If you do care about consistent coding, then consider what you want to do when you check a Boolean that may be NULL.

What's onCreate(Bundle savedInstanceState)

If you save the state of the application in a bundle (typically non-persistent, dynamic data in onSaveInstanceState), it can be passed back to onCreate if the activity needs to be recreated (e.g., orientation change) so that you don't lose this prior information. If no data was supplied, savedInstanceState is null.

... you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

source

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

You can use strcmp:

break x:20 if strcmp(y, "hello") == 0

20 is line number, x can be any filename and y can be any variable.

How can I check if a Perl module is installed on my system from the command line?

If you want to quickly check if a module is installed (at least on Unix systems, with Bash as shell), add this to your .bashrc file:

alias modver="perl -e\"eval qq{use \\\$ARGV[0];\\\\\\\$v=\\\\\\\$\\\${ARGV[0]}::VERSION;};\ print\\\$@?qq{No module found\\n}:\\\$v?qq{Version \\\$v\\n}:qq{Found.\\n};\"\$1"

Then you can:

=> modver XML::Simple
No module found

=> modver DBI
Version 1.607

How to Validate Google reCaptcha on Form Submit

From a UX perspective, it can help to visibly let the user know when they can proceed to submit the form - either by enabling a disabled button, or simply making the button visible.

Here's a simple example...

<form>
    <div class="g-recaptcha" data-sitekey="YOUR_PRIVATE_KEY" data-callback="recaptchaCallback"></div>
    <button type="submit" class="btn btn-default hidden" id="btnSubmit">Submit</button>
</form>

<script>
    function recaptchaCallback() {
        var btnSubmit = document.getElementById("btnSubmit");

        if ( btnSubmit.classList.contains("hidden") ) {
            btnSubmit.classList.remove("hidden");
            btnSubmitclassList.add("show");
        }
    }
</script>

Update select2 data without rebuilding the control

select2 v3.x

If you have local array with options (received by ajax call), i think you should use data parameter as function returning results for select box:

var pills = [{id:0, text: "red"}, {id:1, text: "blue"}]; 

$('#selectpill').select2({
    placeholder: "Select a pill",
    data: function() { return {results: pills}; }
});

$('#uppercase').click(function() {
    $.each(pills, function(idx, val) {
        pills[idx].text = val.text.toUpperCase();
    });
});
$('#newresults').click(function() {
    pills = [{id:0, text: "white"}, {id:1, text: "black"}];
});

FIDDLE: http://jsfiddle.net/RVnfn/576/

In case if you customize select2 interface with buttons, just call updateResults (this method not allowed to call from outsite of select2 object but you can add it to allowedMethods array in select2 if you need to) method after updateting data array(pills in example).


select2 v4: custom data adapter

Custom data adapter with additional updateOptions (its unclear why original ArrayAdapter lacks this functionality) method can be used to dynamically update options list (all options in this example):

$.fn.select2.amd.define('select2/data/customAdapter',
    ['select2/data/array', 'select2/utils'],
    function (ArrayAdapter, Utils) {
        function CustomDataAdapter ($element, options) {
            CustomDataAdapter.__super__.constructor.call(this, $element, options);
        }
        Utils.Extend(CustomDataAdapter, ArrayAdapter);
        CustomDataAdapter.prototype.updateOptions = function (data) {
            this.$element.find('option').remove(); // remove all options
            this.addOptions(this.convertToOptions(data));
        }        
        return CustomDataAdapter;
    }
);

var customAdapter = $.fn.select2.amd.require('select2/data/customAdapter');

var sel = $('select').select2({
    dataAdapter: customAdapter,
    data: pills
});

$('#uppercase').click(function() {
    $.each(pills, function(idx, val) {
        pills[idx].text = val.text.toUpperCase();
    });
    sel.data('select2').dataAdapter.updateOptions(pills);
});

FIDDLE: https://jsfiddle.net/xu48n36c/1/


select2 v4: ajax transport function

in v4 you can define custom transport method that can work with local data array (thx @Caleb_Kiage for example, i've played with it without succes)

docs: https://select2.github.io/options.html#can-an-ajax-plugin-other-than-jqueryajax-be-used

Select2 uses the transport method defined in ajax.transport to send requests to your API. By default, this transport method is jQuery.ajax but this can be changed.

$('select').select2({
    ajax: {
        transport: function(params, success, failure) {
            var items = pills;
            // fitering if params.data.q available
            if (params.data && params.data.q) {
                items = items.filter(function(item) {
                    return new RegExp(params.data.q).test(item.text);
                });
            }
            var promise = new Promise(function(resolve, reject) {
                resolve({results: items});
            });
            promise.then(success);
            promise.catch(failure);
        }
    }
});

BUT with this method you need to change ids of options if text of option in array changes - internal select2 dom option element list did not modified. If id of option in array stay same - previous saved option will be displayed instead of updated from array! That is not problem if array modified only by adding new items to it - ok for most common cases.

FIDDLE: https://jsfiddle.net/xu48n36c/3/

How to use multiprocessing queue in Python?

Here's a dead simple usage of multiprocessing.Queue and multiprocessing.Process that allows callers to send an "event" plus arguments to a separate process that dispatches the event to a "do_" method on the process. (Python 3.4+)

import multiprocessing as mp
import collections

Msg = collections.namedtuple('Msg', ['event', 'args'])

class BaseProcess(mp.Process):
    """A process backed by an internal queue for simple one-way message passing.
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queue = mp.Queue()

    def send(self, event, *args):
        """Puts the event and args as a `Msg` on the queue
        """
       msg = Msg(event, args)
       self.queue.put(msg)

    def dispatch(self, msg):
        event, args = msg

        handler = getattr(self, "do_%s" % event, None)
        if not handler:
            raise NotImplementedError("Process has no handler for [%s]" % event)

        handler(*args)

    def run(self):
        while True:
            msg = self.queue.get()
            self.dispatch(msg)

Usage:

class MyProcess(BaseProcess):
    def do_helloworld(self, arg1, arg2):
        print(arg1, arg2)

if __name__ == "__main__":
    process = MyProcess()
    process.start()
    process.send('helloworld', 'hello', 'world')

The send happens in the parent process, the do_* happens in the child process.

I left out any exception handling that would obviously interrupt the run loop and exit the child process. You can also customize it by overriding run to control blocking or whatever else.

This is really only useful in situations where you have a single worker process, but I think it's a relevant answer to this question to demonstrate a common scenario with a little more object-orientation.

Using SUMIFS with multiple AND OR conditions

In order to get the formula to work place the cursor inside the formula and press ctr+shift+enter and then it will work!

Issue pushing new code in Github

A simpler answer is to manually upload the README.MD file from your computer to GitHub. Worked very well for me.

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

The way I do it: I store the latitude and longitude and then I have a third column which is a automatic derived geography type of the 1st two columns. The table looks like this:

CREATE TABLE [dbo].[Geopoint]
(
    [GeopointId] BIGINT NOT NULL PRIMARY KEY IDENTITY, 
    [Latitude] float NOT NULL, 
    [Longitude] float NOT NULL, 
    [ts] ROWVERSION NOT NULL, 
    [GeographyPoint]  AS ([geography]::STGeomFromText(((('POINT('+CONVERT([varchar](20),[Longitude]))+' ')+CONVERT([varchar](20),[Latitude]))+')',(4326))) 
)

This gives you the flexibility of spatial queries on the geoPoint column and you can also retrieve the latitude and longitude values as you need them for display or extracting for csv purposes.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

How to use the unsigned Integer in Java 8 and Java 9?

    // Java 8
    int vInt = Integer.parseUnsignedInt("4294967295");
    System.out.println(vInt); // -1
    String sInt = Integer.toUnsignedString(vInt);
    System.out.println(sInt); // 4294967295

    long vLong = Long.parseUnsignedLong("18446744073709551615");
    System.out.println(vLong); // -1
    String sLong = Long.toUnsignedString(vLong);
    System.out.println(sLong); // 18446744073709551615

    // Guava 18.0
    int vIntGu = UnsignedInts.parseUnsignedInt(UnsignedInteger.MAX_VALUE.toString());
    System.out.println(vIntGu); // -1
    String sIntGu = UnsignedInts.toString(vIntGu);
    System.out.println(sIntGu); // 4294967295

    long vLongGu = UnsignedLongs.parseUnsignedLong("18446744073709551615");
    System.out.println(vLongGu); // -1
    String sLongGu = UnsignedLongs.toString(vLongGu);
    System.out.println(sLongGu); // 18446744073709551615

    /**
     Integer - Max range
     Signed: From -2,147,483,648 to 2,147,483,647, from -(2^31) to 2^31 – 1
     Unsigned: From 0 to 4,294,967,295 which equals 2^32 - 1

     Long - Max range
     Signed: From -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, from -(2^63) to 2^63 - 1
     Unsigned: From 0 to 18,446,744,073,709,551,615 which equals 2^64 – 1
     */

How to embed a Facebook page's feed into my website

The Like Box/ Page plugin is basically an iframe and ugly :D

So I created my own free plugin that I call Famax plugin to display FanPage feeds. It's similar to the like box but has a better UI and is more customizable.

Also because the Like box is shown in an iframe with a fixed width and height etc, its not really responsive.

Parsing Query String in node.js

require('url').parse('/status?name=ryan', {parseQueryString: true}).query

returns

{ name: 'ryan' }

ref: https://nodejs.org/api/url.html#url_urlobject_query

Best practice for REST token-based authentication with JAX-RS and Jersey

How token-based authentication works

In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.

In a few words, an authentication scheme based on tokens follow these steps:

  1. The client sends their credentials (username and password) to the server.
  2. The server authenticates the credentials and, if they are valid, generate a token for the user.
  3. The server stores the previously generated token in some storage along with the user identifier and an expiration date.
  4. The server sends the generated token to the client.
  5. The client sends the token to the server in each request.
  6. The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
    • If the token is valid, the server accepts the request.
    • If the token is invalid, the server refuses the request.
  7. Once the authentication has been performed, the server performs authorization.
  8. The server can provide an endpoint to refresh tokens.

Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).

What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)

This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.

It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml descriptor. It's a custom authentication.

Authenticating a user with their username and password and issuing a token

Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:

@Path("/authentication")
public class AuthenticationEndpoint {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username, 
                                     @FormParam("password") String password) {

        try {

            // Authenticate the user using the credentials provided
            authenticate(username, password);

            // Issue a token for the user
            String token = issueToken(username);

            // Return the token on the response
            return Response.ok(token).build();

        } catch (Exception e) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }      
    }

    private void authenticate(String username, String password) throws Exception {
        // Authenticate against a database, LDAP, file or whatever
        // Throw an Exception if the credentials are invalid
    }

    private String issueToken(String username) {
        // Issue a token (can be a random String persisted to a database or a JWT token)
        // The issued token must be associated to a user
        // Return the issued token
    }
}

If any exceptions are thrown when validating the credentials, a response with the status 403 (Forbidden) will be returned.

If the credentials are successfully validated, a response with the status 200 (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.

When consuming application/x-www-form-urlencoded, the client must to send the credentials in the following format in the request payload:

username=admin&password=123456

Instead of form params, it's possible to wrap the username and the password into a class:

public class Credentials implements Serializable {

    private String username;
    private String password;

    // Getters and setters omitted
}

And then consume it as JSON:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {

    String username = credentials.getUsername();
    String password = credentials.getPassword();

    // Authenticate the user, issue a token and return a response
}

Using this approach, the client must to send the credentials in the following format in the payload of the request:

{
  "username": "admin",
  "password": "123456"
}

Extracting the token from the request and validating it

The client should send the token in the standard HTTP Authorization header of the request. For example:

Authorization: Bearer <token-goes-here>

The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.

JAX-RS provides @NameBinding, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured annotation as following:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }

The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext can be used to access the HTTP request headers and then extract the token:

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String REALM = "example";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the Authorization header from the request
        String authorizationHeader =
                requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validate the Authorization header
        if (!isTokenBasedAuthentication(authorizationHeader)) {
            abortWithUnauthorized(requestContext);
            return;
        }

        // Extract the token from the Authorization header
        String token = authorizationHeader
                            .substring(AUTHENTICATION_SCHEME.length()).trim();

        try {

            // Validate the token
            validateToken(token);

        } catch (Exception e) {
            abortWithUnauthorized(requestContext);
        }
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

        // Check if the Authorization header is valid
        // It must not be null and must be prefixed with "Bearer" plus a whitespace
        // The authentication scheme comparison must be case-insensitive
        return authorizationHeader != null && authorizationHeader.toLowerCase()
                    .startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {

        // Abort the filter chain with a 401 status code response
        // The WWW-Authenticate header is sent along with the response
        requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE, 
                                AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
                        .build());
    }

    private void validateToken(String token) throws Exception {
        // Check if the token was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
    }
}

If any problems happen during the token validation, a response with the status 401 (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.

Securing your REST endpoints

To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.

If some methods or classes do not need authentication, simply do not annotate them:

@Path("/example")
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myUnsecuredMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // The authentication filter won't be executed before invoking this method
        ...
    }

    @DELETE
    @Secured
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response mySecuredMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured
        // The authentication filter will be executed before invoking this method
        // The HTTP request must be performed with a valid token
        ...
    }
}

In the example shown above, the filter will be executed only for the mySecuredMethod(Long) method because it's annotated with @Secured.

Identifying the current user

It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:

Overriding the security context of the current request

Within your ContainerRequestFilter.filter(ContainerRequestContext) method, a new SecurityContext instance can be set for the current request. Then override the SecurityContext.getUserPrincipal(), returning a Principal instance:

final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> username;
        }

    @Override
    public boolean isUserInRole(String role) {
        return true;
    }

    @Override
    public boolean isSecure() {
        return currentSecurityContext.isSecure();
    }

    @Override
    public String getAuthenticationScheme() {
        return AUTHENTICATION_SCHEME;
    }
});

Use the token to look up the user identifier (username), which will be the Principal's name.

Inject the SecurityContext in any JAX-RS resource class:

@Context
SecurityContext securityContext;

The same can be done in a JAX-RS resource method:

@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id, 
                         @Context SecurityContext securityContext) {
    ...
}

And then get the Principal:

Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();

Using CDI (Context and Dependency Injection)

If, for some reason, you don't want to override the SecurityContext, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.

Create a CDI qualifier:

@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }

In your AuthenticationFilter created above, inject an Event annotated with @AuthenticatedUser:

@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;

If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):

userAuthenticatedEvent.fire(username);

It's very likely that there's a class that represents a user in your application. Let's call this class User.

Create a CDI bean to handle the authentication event, find a User instance with the correspondent username and assign it to the authenticatedUser producer field:

@RequestScoped
public class AuthenticatedUserProducer {

    @Produces
    @RequestScoped
    @AuthenticatedUser
    private User authenticatedUser;

    public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
        this.authenticatedUser = findUser(username);
    }

    private User findUser(String username) {
        // Hit the the database or a service to find a user by its username and return it
        // Return the User instance
    }
}

The authenticatedUser field produces a User instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User instance (in fact, it's a CDI proxy):

@Inject
@AuthenticatedUser
User authenticatedUser;

Note that the CDI @Produces annotation is different from the JAX-RS @Produces annotation:

Be sure you use the CDI @Produces annotation in your AuthenticatedUserProducer bean.

The key here is the bean annotated with @RequestScoped, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.

Compared to the approach that overrides the SecurityContext, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.

Supporting role-based authorization

Please refer to my other answer for details on how to support role-based authorization.

Issuing tokens

A token can be:

  • Opaque: Reveals no details other than the value itself (like a random string)
  • Self-contained: Contains details about the token itself (like JWT).

See details below:

Random string as token

A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:

Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);

JWT (JSON Web Token)

JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.

It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):

  • iss: Principal that issued the token.
  • sub: Principal that is the subject of the JWT.
  • exp: Expiration date for the token.
  • nbf: Time on which the token will start to be accepted for processing.
  • iat: Time on which the token was issued.
  • jti: Unique identifier for the token.

Be aware that you must not store sensitive data, such as passwords, in the token.

The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.

You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti claim) along with some other details such as the user you issued the token for, the expiration date, etc.

When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.

Using JWT

There are a few Java libraries to issue and validate JWT tokens such as:

To find some other great resources to work with JWT, have a look at http://jwt.io.

Handling token revocation with JWT

If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.

The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti claim against the token identifiers you have on server side.

For security purposes, revoke all the tokens for a user when they change their password.

Additional information

  • It doesn't matter which type of authentication you decide to use. Always do it on the top of a HTTPS connection to prevent the man-in-the-middle attack.
  • Take a look at this question from Information Security for more information about tokens.
  • In this article you will find some useful information about token-based authentication.

What is the color code for transparency in CSS?

There are now 8-digit hex codes in CSS4 (CSS Color Module Level 4), the last two digit (or in case of the abbreviation, the last of the 4 digits) represents alpha, 00 meaning fully transparent and ff meaning fully opaque, 7f representing an opacity of 0.5 etc.

The format is '#rrggbbaa' or the shorthand, '#rgba'.

Support is lacking for MS browsers, they might be less cooperative or just slower than the other developers, either or both of which actually sealed IE's fate: https://caniuse.com/#feat=css-rrggbbaa

How do I check if a number is positive or negative in C#?

int j = num * -1;

if (j - num  == j)
{
     // Num is equal to zero
}
else if (j < i)
{
      // Num is positive
}
else if (j > i) 
{
     // Num is negative
}

Bash scripting, multiple conditions in while loop

Try:

while [ $stats -gt 300 -o $stats -eq 0 ]

[ is a call to test. It is not just for grouping, like parentheses in other languages. Check man [ or man test for more information.

Calculate RSA key fingerprint

Reproducing content from AWS forums here, because I found it useful to my use case - I wanted to check which of my keys matched ones I had imported into AWS

openssl pkey -in ~/.ssh/ec2/primary.pem -pubout -outform DER | openssl md5 -c

Where:

  • primary.pem is the private key to check

Note that this gives a different fingerprint from the one computed by ssh-keygen.

How to view file diff in git before commit

Another technique to consider if you want to compare a file to the last commit which is more pedantic:

git diff master myfile.txt

The advantage with this technique is you can also compare to the penultimate commit with:

git diff master^ myfile.txt

and the one before that:

git diff master^^ myfile.txt

Also you can substitute '~' for the caret '^' character and 'you branch name' for 'master' if you are not on the master branch.

Matching exact string with JavaScript

Either modify the pattern beforehand so that it only matches the entire string:

var r = /^a$/

or check afterward whether the pattern matched the whole string:

function matchExact(r, str) {
   var match = str.match(r);
   return match && str === match[0];
}

How do I divide in the Linux console?

In bash, if you don't need decimals in your division, you can do:

>echo $((5+6))
11
>echo $((10/2))
5
>echo $((10/3))
3

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

Replace text in HTML page with jQuery

The html replace idea is good, but if done to the document.body, the page will blink and ads will disappear.

My solution:
$("*:contains('purrfect')").each(function() { var replaced = $(this).html().replace(/purrfect/g, "purrfect"); $(this).html(replaced); });

Delete cookie by name?

You should define the path on which the cookie exists to ensure that you are deleting the correct cookie.

function set_cookie(name, value) {
  document.cookie = name +'='+ value +'; Path=/;';
}
function delete_cookie(name) {
  document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

If you don't specify the path, the browser will set a cookie relative to the page you are currently on, so if you delete the cookie while on a different page, the other cookie continues its existence.

Edit based on @Evan Morrison's comment.
Be aware that in some cases to identify the correct cookie, the Domain parameter is required.
Usually it's defined as Domain=.yourdomain.com.
Placing a dot in front of your domain name means that this cookie may exist on any sub-domain (www also counts as sub-domain).

Also, as mentioned in @RobertT's answer, HttpOnly cookies cannot be deleted with JavaScript on the client side.

How to dynamically insert a <script> tag via jQuery after page load?

Try the following:

<script type="text/javascript">
// Use any event to append the code
$(document).ready(function() 
{
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "http://scriptlocation/das.js";
    // Use any selector
    $("head").append(s);
});

http://api.jquery.com/append

Error - Unable to access the IIS metabase

  1. Create a shortcut to the "devenv.exe"
  2. select the "Run as administrator" option for the shortcut
  3. doble click on the short cut and reopen your project

How to create a numpy array of arbitrary length strings?

You can do so by creating an array of dtype=object. If you try to assign a long string to a normal numpy array, it truncates the string:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'], 
      dtype='|S6')

But when you use dtype=object, you get an array of python object references. So you can have all the behaviors of python strings:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)

Indeed, because it's an array of objects, you can assign any kind of python object to the array:

>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)

However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:

>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop

ImportError: Cannot import name X

The problem is clear: circular dependency between names in entity and physics modules.

Regardless of importing the whole module or just a class, the names must be loaded .

Watch this example:

# a.py
import b
def foo():
  pass
b.bar()
# b.py
import a
def bar():
  pass
a.foo()

This will be compiled into:

# a.py
# import b
# b.py
# import a # ignored, already importing
def bar():
  pass
a.foo()
# name a.foo is not defined!!!
# import b done!
def foo():
  pass
b.bar()
# done!

With one slight change we can solve this:

# a.py
def foo():
  pass
import b
b.bar()
# b.py
def bar():
  pass
import a
a.foo()

This will be compiled into:

# a.py
def foo():
  pass
# import b
# b.py
def bar():
  pass
# import a # ignored, already importing
a.foo()
# import b done!
b.bar()
# done!

Keylistener in Javascript

Here's an update for modern browsers in 2019

_x000D_
_x000D_
let playerSpriteX = 0;_x000D_
_x000D_
document.addEventListener('keyup', (e) => {_x000D_
  if (e.code === "ArrowUp")        playerSpriteX += 10_x000D_
  else if (e.code === "ArrowDown") playerSpriteX -= 10_x000D_
_x000D_
  document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX;_x000D_
});
_x000D_
Click on this window to focus it, and hit keys up and down_x000D_
<br><br><br>_x000D_
<div id="test">playerSpriteX = 0</div>
_x000D_
_x000D_
_x000D_


Original answer from 2013

window.onkeyup = function(e) {
   var key = e.keyCode ? e.keyCode : e.which;

   if (key == 38) {
       playerSpriteX += 10;
   }else if (key == 40) {
       playerSpriteX -= 10;
   }
}

FIDDLE

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The formula is

minSdkVersion <= targetSdkVersion <= compileSdkVersion

minSdkVersion - is a marker that defines a minimum Android version on which application will be able to install. Also it is used by Lint to prevent calling API that doesn’t exist. Also it has impact on Build Time. So you can use build flavors to override minSdkVersion to maximum during the development. It will help to make build faster using all improvements that the Android team provides for us. For example some features Java 8 are available only from specific version of minSdkVersion.

targetSdkVersion - If AndroidOS version is >= targetSdkVersion it says Android system to turn on specific(new) behavior changes. *Please note that some of new behaviors will be turned on by default even if thought targetSdkVersion is <, you should read official doc.

For example:

  • Starting in Android 6.0 (API level 23) Runtime Permissions were introduced. If you set targetSdkVersion to 22 or lower your application does not ask a user for some permission in run time.

  • Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).

  • Starting in Android 9 (API level 28), Web-based data directories separated by process. If targetSdkVersion is 28+ and you create several WebView in different processes you will get java.lang.RuntimeException

compileSdkVersion - actually it is SDK Platform version and tells Gradle which Android SDK use to compile. When you want to use new features or debug .java files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion - level 28. compileSdkVersion is not included in your APK: it is purely used at compile time. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version

You can read more about it here. Also I would recommend you to take a look at the example of migration to Android 8.0.

[buildToolsVersion]

How to Create an excel dropdown list that displays text with a numeric hidden value

Data validation drop down

There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.

The steps in Excel 2010 are:

  • Create your list with matching values.
  • On the Data tab choose Data Validation
  • The Data validation form will be displayed
  • Set the Allow dropdown to List
  • Set the Source range to the first part of your list
  • Click on OK (User messages can be added if required)

In a cell enter a formula like this

=VLOOKUP(A2,$D$3:$E$5,2,FALSE)

which will return the matching value from the second part of your list.

Screenshot of Data validation list

Form control drop down

Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.

The steps in Excel 2010 are:

  • Create your list of data in a worksheet
  • Click on the Developer tab and dropdown on the Insert option
  • In the Form section choose Combo box or List box
  • Use the mouse to draw the box on the worksheet
  • Right click on the box and select Format control
  • The Format control form will be displayed
  • Click on the Control tab
  • Set the Input range to your list of data
  • Set the Cell link range to the cell where you want the number of the selected item to appear
  • Click on OK

Screenshot of form control

How to horizontally center an unordered list of unknown width?

It depends on if you mean the list items are below the previous or to the right of the previous, ie:

Home
About
Contact

or

Home | About | Contact

The first one you can do simply with:

#wrapper { width:600px; background: yellow; margin: 0 auto; }
#footer ul { text-align: center; list-style-type: none; }

The second could be done like this:

#wrapper { width:600px; background: yellow; margin: 0 auto; }
#footer ul { text-align: center; list-style-type: none; }
#footer li { display: inline; }
#footer a { padding: 2px 12px; background: orange; text-decoration: none; }
#footer a:hover { background: green; color: yellow; }

C# RSA encryption/decryption with transmission

public static string Encryption(string strText)
        {
            var publicKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

            var testData = Encoding.UTF8.GetBytes(strText);

            using (var rsa = new RSACryptoServiceProvider(1024))
            {
                try
                {
                    // client encrypting data with public key issued by server                    
                    rsa.FromXmlString(publicKey.ToString());

                    var encryptedData = rsa.Encrypt(testData, true);

                    var base64Encrypted = Convert.ToBase64String(encryptedData);

                    return base64Encrypted;
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }

        public static string Decryption(string strText)
        {
            var privateKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent><P>/aULPE6jd5IkwtWXmReyMUhmI/nfwfkQSyl7tsg2PKdpcxk4mpPZUdEQhHQLvE84w2DhTyYkPHCtq/mMKE3MHw==</P><Q>3WV46X9Arg2l9cxb67KVlNVXyCqc/w+LWt/tbhLJvV2xCF/0rWKPsBJ9MC6cquaqNPxWWEav8RAVbmmGrJt51Q==</Q><DP>8TuZFgBMpBoQcGUoS2goB4st6aVq1FcG0hVgHhUI0GMAfYFNPmbDV3cY2IBt8Oj/uYJYhyhlaj5YTqmGTYbATQ==</DP><DQ>FIoVbZQgrAUYIHWVEYi/187zFd7eMct/Yi7kGBImJStMATrluDAspGkStCWe4zwDDmdam1XzfKnBUzz3AYxrAQ==</DQ><InverseQ>QPU3Tmt8nznSgYZ+5jUo9E0SfjiTu435ihANiHqqjasaUNvOHKumqzuBZ8NRtkUhS6dsOEb8A2ODvy7KswUxyA==</InverseQ><D>cgoRoAUpSVfHMdYXW9nA3dfX75dIamZnwPtFHq80ttagbIe4ToYYCcyUz5NElhiNQSESgS5uCgNWqWXt5PnPu4XmCXx6utco1UVH8HGLahzbAnSy6Cj3iUIQ7Gj+9gQ7PkC434HTtHazmxVgIR5l56ZjoQ8yGNCPZnsdYEmhJWk=</D></RSAKeyValue>";

            var testData = Encoding.UTF8.GetBytes(strText);

            using (var rsa = new RSACryptoServiceProvider(1024))
            {
                try
                {                    
                    var base64Encrypted = strText;

                    // server decrypting data with private key                    
                    rsa.FromXmlString(privateKey);

                    var resultBytes = Convert.FromBase64String(base64Encrypted);
                    var decryptedBytes = rsa.Decrypt(resultBytes, true);
                    var decryptedData = Encoding.UTF8.GetString(decryptedBytes);
                    return decryptedData.ToString();
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }

Calculate days between two Dates in Java 8

Everyone is saying to use ChronoUnit.DAYS.between but that just delegates to another method you could call yourself. So you could also do firstDate.until(secondDate, ChronoUnit.DAYS).

The docs for both actually mention both approaches and say to use whichever one is more readable.

Read Numeric Data from a Text File in C++

It can depend, especially on whether your file will have the same number of items on each row or not. If it will, then you probably want a 2D matrix class of some sort, usually something like this:

class array2D { 
    std::vector<double> data;
    size_t columns;
public:
    array2D(size_t x, size_t y) : columns(x), data(x*y) {}

    double &operator(size_t x, size_t y) {
       return data[y*columns+x];
    }
};

Note that as it's written, this assumes you know the size you'll need up-front. That can be avoided, but the code gets a little larger and more complex.

In any case, to read the numbers and maintain the original structure, you'd typically read a line at a time into a string, then use a stringstream to read numbers from the line. This lets you store the data from each line into a separate row in your array.

If you don't know the size ahead of time or (especially) if different rows might not all contain the same number of numbers:

11 12 13
23 34 56 78

You might want to use a std::vector<std::vector<double> > instead. This does impose some overhead, but if different rows may have different sizes, it's an easy way to do the job.

std::vector<std::vector<double> > numbers;

std::string temp;

while (std::getline(infile, temp)) {
    std::istringstream buffer(temp);
    std::vector<double> line((std::istream_iterator<double>(buffer)),
                             std::istream_iterator<double>());

    numbers.push_back(line);
}

...or, with a modern (C++11) compiler, you can use brackets for line's initialization:

    std::vector<double> line{std::istream_iterator<double>(buffer),
                             std::istream_iterator<double>()};

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

How do I manually configure a DataSource in Java?

One thing you might want to look at is the Commons DBCP project. It provides a BasicDataSource that is configured fairly similarly to your example. To use that you need the database vendor's JDBC JAR in your classpath and you have to specify the vendor's driver class name and the database URL in the proper format.

Edit:

If you want to configure a BasicDataSource for MySQL, you would do something like this:

BasicDataSource dataSource = new BasicDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setUrl("jdbc:mysql://<host>:<port>/<database>");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");

Code that needs a DataSource can then use that.

Operator overloading ==, !=, Equals

public class BOX
{
    double height, length, breadth;

    public static bool operator == (BOX b1, BOX b2)
    {
        if (b1 is null)
            return b2 is null;

        return b1.Equals(b2);
    }

    public static bool operator != (BOX b1, BOX b2)
    {
        return !(b1 == b2);
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        return obj is BOX b2? (length == b2.length && 
                               breadth == b2.breadth && 
                               height == b2.height): false;

    }

    public override int GetHashCode()
    {
        return (height,length,breadth).GetHashCode();
    }
}

tell pip to install the dependencies of packages listed in a requirement file

simplifily, use:

pip install -r requirement.txt

it can install all listed in requirement file.

Oracle get previous day records

SELECT field,datetime_field 
FROM database
WHERE datetime_field > (CURRENT_DATE - 1)

Its been some time that I worked on Oracle. But, I think this should work.

ReactJs: What should the PropTypes be for this.props.children?

Try a custom propTypes :

 const  childrenPropTypeLogic = (props, propName, componentName) => {
          const prop = props[propName];
          return React.Children
                   .toArray(prop)
                   .find(child => child.type !== 'div') && new Error(`${componentName} only accepts "div" elements`);
 };


static propTypes = {

   children : childrenPropTypeLogic

}

Fiddle

_x000D_
_x000D_
const {Component, PropTypes} = React;_x000D_
_x000D_
 const  childrenPropTypeLogic = (props, propName, componentName) => {_x000D_
             var error;_x000D_
          var prop = props[propName];_x000D_
    _x000D_
          React.Children.forEach(prop, function (child) {_x000D_
            if (child.type !== 'div') {_x000D_
              error = new Error(_x000D_
                '`' + componentName + '` only accepts children of type `div`.'_x000D_
              );_x000D_
            }_x000D_
          });_x000D_
    _x000D_
          return error;_x000D_
    };_x000D_
    _x000D_
  _x000D_
_x000D_
class ContainerComponent extends Component {_x000D_
  static propTypes = {_x000D_
    children: childrenPropTypeLogic,_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div>_x000D_
        {this.props.children}_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
class App extends Component {_x000D_
   render(){_x000D_
    return (_x000D_
    <ContainerComponent>_x000D_
        <div>1</div>_x000D_
        <div>2</div>_x000D_
      </ContainerComponent>_x000D_
    )_x000D_
   }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App /> , document.querySelector('section'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<section />
_x000D_
_x000D_
_x000D_

Add up a column of numbers at the Unix shell

Here goes

cat files.txt | xargs ls -l | cut -c 23-30 | 
  awk '{total = total + $1}END{print total}'

Capturing multiple line output into a Bash variable

In addition to the answer given by @l0b0 I just had the situation where I needed to both keep any trailing newlines output by the script and check the script's return code. And the problem with l0b0's answer is that the 'echo x' was resetting $? back to zero... so I managed to come up with this very cunning solution:

RESULTX="$(./myscript; echo x$?)"
RETURNCODE=${RESULTX##*x}
RESULT="${RESULTX%x*}"

PHP to write Tab Characters inside a file?

Use \t and enclose the string with double-quotes:

$chunk = "abc\tdef\tghi";

When is the init() function run?

Here is another example - https://play.golang.org/p/9P-LmSkUMKY

package main

import (
    "fmt"
)

func callOut() int {
    fmt.Println("Outside is beinge executed")
    return 1
}

var test = callOut()

func init() {
    fmt.Println("Init3 is being executed")
}

func init() {
    fmt.Println("Init is being executed")
}

func init() {
    fmt.Println("Init2 is being executed")
}

func main() {
    fmt.Println("Do your thing !")
}

Output of the above program

$ go run init/init.go
Outside is being executed
Init3 is being executed
Init is being executed
Init2 is being executed
Do your thing !

Instantiating a generic type

You cannot do new T() due to type erasure. The default constructor can only be

public Navigation() {     this("", "", null); } 

​ You can create other constructors to provide default values for trigger and description. You need an concrete object of T.

Write a number with two decimal places SQL Server

Use Str() Function. It takes three arguments(the number, the number total characters to display, and the number of decimal places to display

  Select Str(12345.6789, 12, 3)

displays: ' 12345.679' ( 3 spaces, 5 digits 12345, a decimal point, and three decimal digits (679). - it rounds if it has to truncate, (unless the integer part is too large for the total size, in which case asterisks are displayed instead.)

for a Total of 12 characters, with 3 to the right of decimal point.

Find the last element of an array while using a foreach loop in PHP

to get first and last element from foreach array

foreach($array as $value) {
    if ($value === reset($array)) {
        echo 'FIRST ELEMENT!';
    }

    if ($value === end($array)) {
        echo 'LAST ITEM!';
    }
}

To draw an Underline below the TextView in Android

A simple and sustainable solution is to create a layer-list and make it as the background of your TextView:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:left="-5dp"
        android:right="-5dp"
        android:top="-5dp">
        <shape>
            <stroke
                android:width="1.5dp"
                android:color="@color/colorAccent" />
        </shape>
    </item>
</layer-list>

how to parse json using groovy

You can map JSON to specific class in Groovy using as operator:

import groovy.json.JsonSlurper

String json = '''
{
  "name": "John",  
  "age": 20
}
'''

def person = new JsonSlurper().parseText(json) as Person 

with(person) {
    assert name == 'John'
    assert age == 20
}

how to set default culture info for entire c# application

Not for entire application or particular class.

CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture at all.

Sample code to change cultures for current thread:

CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:

(3.3).ToString(new CultureInfo("fr-FR"))

java : non-static variable cannot be referenced from a static context Error

No, actually, you must declare your con2 field static:

private static java.sql.Connection con2 = null;

Edit: Correction, that won't be enough actually, you will get the same problem because your getConnection2Url method is also not static. A better solution may be to instead do the following change:

 public static void main (String[] args) { 
     new testconnect().run();
 } 

 public void run() {
     con2 = java.sql.DriverManager.getConnection(getConnectionUrl2());
 }

jQuery detect if textarea is empty

To find out if the textarea is empty we have a look at the textarea text content and if there is one sinlge character to be found it is not empty.

Try:

if ($(#textareaid).get(0).textContent.length == 0){
  // action
}
//or
if (document.getElmentById(textareaid).textContent.length == 0){
  // action
}

$(#textareaid) gets us the textarea jQuery object. $(#textareaid).get(0) gets us the dom node. We could also use document.getElmentById(textareaid) without the use of jQuery. .textContent gets us the textContent of that dom element. With .length we can see if there are any characters present. So the textarea is empty in case that there are no characters inside.

How do I enable --enable-soap in php on linux?

Getting SOAP working usually does not require compiling PHP from source. I would recommend trying that only as a last option.

For good measure, check to see what your phpinfo says, if anything, about SOAP extensions:

$ php -i | grep -i soap

to ensure that it is the PHP extension that is missing.

Assuming you do not see anything about SOAP in the phpinfo, see what PHP SOAP packages might be available to you.

In Ubuntu/Debian you can search with:

$ apt-cache search php | grep -i soap

or in RHEL/Fedora you can search with:

$ yum search php | grep -i soap

There are usually two PHP SOAP packages available to you, usually php-soap and php-nusoap. php-soap is typically what you get with configuring PHP with --enable-soap.

In Ubuntu/Debian you can install with:

$ sudo apt-get install php-soap

Or in RHEL/Fedora you can install with:

$ sudo yum install php-soap

After the installation, you might need to place an ini file and restart Apache.

How do I set the background color of my main screen in Flutter?

I think you need to use MaterialApp widget and use theme and set primarySwatch with color that you want. look like below code,

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

Background thread with QThread in PyQt

Very nice example from Matt, I fixed the typo and also pyqt4.8 is common now so I removed the dummy class as well and added an example for the dataReady signal

# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt


# very testable class (hint: you can use mock.Mock for the signals)
class Worker(QtCore.QObject):
    finished = QtCore.pyqtSignal()
    dataReady = QtCore.pyqtSignal(list, dict)

    @QtCore.pyqtSlot()
    def processA(self):
        print "Worker.processA()"
        self.finished.emit()

    @QtCore.pyqtSlot(str, list, list)
    def processB(self, foo, bar=None, baz=None):
        print "Worker.processB()"
        for thing in bar:
            # lots of processing...
            self.dataReady.emit(['dummy', 'data'], {'dummy': ['data']})
        self.finished.emit()


def onDataReady(aList, aDict):
    print 'onDataReady'
    print repr(aList)
    print repr(aDict)


app = QtGui.QApplication(sys.argv)

thread = QtCore.QThread()  # no parent!
obj = Worker()  # no parent!
obj.dataReady.connect(onDataReady)

obj.moveToThread(thread)

# if you want the thread to stop after the worker is done
# you can always call thread.start() again later
obj.finished.connect(thread.quit)

# one way to do it is to start processing as soon as the thread starts
# this is okay in some cases... but makes it harder to send data to
# the worker object from the main gui thread.  As you can see I'm calling
# processA() which takes no arguments
thread.started.connect(obj.processA)
thread.finished.connect(app.exit)

thread.start()

# another way to do it, which is a bit fancier, allows you to talk back and
# forth with the object in a thread safe way by communicating through signals
# and slots (now that the thread is running I can start calling methods on
# the worker object)
QtCore.QMetaObject.invokeMethod(obj, 'processB', Qt.QueuedConnection,
                                QtCore.Q_ARG(str, "Hello World!"),
                                QtCore.Q_ARG(list, ["args", 0, 1]),
                                QtCore.Q_ARG(list, []))

# that looks a bit scary, but its a totally ok thing to do in Qt,
# we're simply using the system that Signals and Slots are built on top of,
# the QMetaObject, to make it act like we safely emitted a signal for
# the worker thread to pick up when its event loop resumes (so if its doing
# a bunch of work you can call this method 10 times and it will just queue
# up the calls.  Note: PyQt > 4.6 will not allow you to pass in a None
# instead of an empty list, it has stricter type checking

app.exec_()

Iterating Through a Dictionary in Swift

Dictionaries in Swift (and other languages) are not ordered. When you iterate through the dictionary, there's no guarentee that the order will match the initialization order. In this example, Swift processes the "Square" key before the others. You can see this by adding a print statement to the loop. 25 is the 5th element of Square so largest would be set 5 times for the 5 elements in Square and then would stay at 25.

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    println("kind: \(kind)")
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
largest

This prints:

kind: Square
kind: Prime
kind: Fibonacci

How to create a Restful web service with input parameters?

You can. Try something like this:

@Path("/todo/{varX}/{varY}")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("varX") String varX,
    @PathParam("varY") String varY) {
        Todo todo = new Todo();
        todo.setSummary(varX);
        todo.setDescription(varY);
        return todo;
}

Then call your service with this URL;
http://localhost:8088/JerseyJAXB/rest/todo/summary/description

Change "on" color of a Switch

<androidx.appcompat.widget.SwitchCompat
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:thumbTint="@color/white"
                app:trackTint="@drawable/checker_track"/>

And inside checker_track.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/lightish_blue" android:state_checked="true"/>
    <item android:color="@color/hint" android:state_checked="false"/>
</selector>

Remove category & tag base from WordPress url - without a plugin

If you want to remove /category/ from the url, follow these two steps:

  1. Go to Settings >> Permalinks and select Custom and enter: /%category%/%postname%/
  2. Next set your Category Base to .

Save it and you’ll see your URL changed to this format: http://yourblog.com/quotes/

(Source: http://premium.wpmudev.org/blog/daily-tip-quick-trick-to-remove-category-from-wordpress-url/)

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

"[ ]{2,}"

This will match more than one space.

String mytext = " hello     there   ";
//without trim -> " hello there"
//with trim -> "hello there"
mytext = mytext.trim().replaceAll("[ ]{2,}", " ");
System.out.println(mytext);

OUTPUT:

hello there

UILabel Align Text to center

Label.textAlignment = NSTextAlignmentCenter;

Trigger insert old values- values that was updated

Here's an example update trigger:

create table Employees (id int identity, Name varchar(50), Password varchar(50))
create table Log (id int identity, EmployeeId int, LogDate datetime, 
    OldName varchar(50))
go
create trigger Employees_Trigger_Update on Employees
after update
as
insert into Log (EmployeeId, LogDate, OldName) 
select id, getdate(), name
from deleted
go
insert into Employees (Name, Password) values ('Zaphoid', '6')
insert into Employees (Name, Password) values ('Beeblebox', '7')
update Employees set Name = 'Ford' where id = 1
select * from Log

This will print:

id   EmployeeId   LogDate                   OldName
1    1            2010-07-05 20:11:54.127   Zaphoid

Java generics - why is "extends T" allowed but not "implements T"?

Probably because for both sides (B and C) only the type is relevant, not the implementation. In your example

public class A<B extends C>{}

B can be an interface as well. "extends" is used to define sub-interfaces as well as sub-classes.

interface IntfSub extends IntfSuper {}
class ClzSub extends ClzSuper {}

I usually think of 'Sub extends Super' as 'Sub is like Super, but with additional capabilities', and 'Clz implements Intf' as 'Clz is a realization of Intf'. In your example, this would match: B is like C, but with additional capabilities. The capabilities are relevant here, not the realization.