Programs & Examples On #Scratchbox

Scratchbox is a cross-compilation toolkit designed to make embedded Linux application development easier. It also provides a full set of tools to integrate and cross-compile an entire Linux distribution.

Install sbt on ubuntu

As an alternative approach, you can save the SBT Extras script to a file called sbt.sh and set the permission to executable. Then add this file to your path, or just put it under your ~/bin directory.

The bonus here, is that it will download and use the correct version of SBT depending on your project properties. This is a nice convenience if you tend to compile open source projects that you pull from GitHub and other.

How to get the exact local time of client?

In JavaScript? Just instantiate a new Date object

var now = new Date();

That will create a new Date object with the client's local time.

How to handle ETIMEDOUT error?

This is caused when your request response is not received in given time(by timeout request module option).

Basically to catch that error first, you need to register a handler on error, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ }). Some more explanation here.

In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }.

If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.

If you want to wait longer, you can set timeout option of request yourself. You can set it to 0 for no timeout.

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

How do I get a python program to do nothing?

The pass command is what you are looking for. Use pass for any construct that you want to "ignore". Your example uses a conditional expression but you can do the same for almost anything.

For your specific use case, perhaps you'd want to test the opposite condition and only perform an action if the condition is false:

if num2 != num5:
    make_some_changes()

This will be the same as this:

if num2 == num5:
    pass
else:
    make_some_changes()

That way you won't even have to use pass and you'll also be closer to adhering to the "Flatter is better than nested" convention in PEP20.


You can read more about the pass statement in the documentation:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

if condition:
    pass
try:
    make_some_changes()
except Exception:
    pass # do nothing
class Foo():
    pass # an empty class definition
def bar():
    pass # an empty function definition

Convert object to JSON in Android

As of Android 3.0 (API Level 11) Android has a more recent and improved JSON Parser.

http://developer.android.com/reference/android/util/JsonReader.html

Reads a JSON (RFC 4627) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.

How to set a JavaScript breakpoint from code in Chrome?

You can also use debug(function), to break when function is called.

Command Line API Reference: debug

Java :Add scroll into text area

Try adding these two lines to your code. I hope it will work. It worked for me :)

display.setLineWrap(true);
display.setWrapStyleWord(true);

Picture of output is shown below

enter image description here

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

Jquery function return value

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

function getMachine(color, qty) {
    var returnValue = null;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            returnValue = thisArray[3];
            return false; // this breaks out of the each
        }
    });
    return returnValue;
}

var retval = getMachine(color, qty);

How to enable Logger.debug() in Log4j

I like to use a rolling file appender to write the logging info to a file. My log4j properties file typically looks something like this. I prefer this way since I like to make package specific logging in case I need varying degrees of logging for different packages. Only one package is mentioned in the example.

log4j.appender.RCS=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RCS.File.DateFormat='.'yyyy-ww
#define output location
log4j.appender.RCS.File=C:temp/logs/MyService.log
#define the file layout
log4j.appender.RCS.layout=org.apache.log4j.PatternLayout
log4j.appender.RCS.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm a} %5 %c{1}: Line#%L - %m%n
log4j.rootLogger=warn
#Define package specific logging
log4j.logger.MyService=debug, RCS

Calculating the distance between 2 points

If you are using System.Windows.Point data type to represent a point, you can use

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distance = Point.Subtract(p2, p1).Length;

Update 2017-01-08:

  • Add reference to Microsoft documentation
  • Result of Point.Subtract is System.Windows.Vector and it has also property LengthSquared to save one sqrt calculation if you just need to compare distance.
  • Adding reference to WindowsBase assembly may be needed in your project
  • You can also use operators

Example with LengthSquared and operators

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distanceSquared = (p2 - p1).LengthSquared;

How to permanently add a private key with ssh-add on Ubuntu?

For those that use Fish shell you can use the following function then call it in ~/.config/fish/config.fish or in a separate configuration file in ~/.config/fish/conf.d/loadsshkeys.fish. It will load all keys that start with id_rsa into the ssh-agent.

# Load all ssh keys that start with "id_rsa"
function loadsshkeys
  set added_keys (ssh-add -l)
   for key in (find ~/.ssh/ -not -name "*.pub" -a -iname "id_rsa*")
    if test ! (echo $added_keys | grep -o -e $key)
      ssh-add "$key"
    end
  end
end

# Call the function to run it.
loadsshkeys

If you want to have the ssh-agent auto started when you open a terminal you can use tuvistavie/fish-ssh-agent to do this.

Check to see if cURL is installed locally?

To extend the answer above and if the case is you are using XAMPP. In the current version of the xampp you cannot locate the curl_exec in the php.ini, just try using

<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>

and save to your htdocs. Next go to your browser and paste

http://localhost/[your_filename].php

if the result looks like this

array(9) {
  ["version_number"]=>
  int(469760)
  ["age"]=>
  int(3)
  ["features"]=>
  int(266141)
  ["ssl_version_number"]=>
  int(0)
  ["version"]=>
  string(6) "7.43.0"
  ["host"]=>
  string(13) "i386-pc-win32"
  ["ssl_version"]=>
  string(14) "OpenSSL/1.0.2e"
  ["libz_version"]=>
  string(5) "1.2.8"
  ["protocols"]=>
  array(19) {
    [0]=>
    string(4) "dict"
    [1]=>
    string(4) "file"
    [2]=>
    string(3) "ftp"
    [3]=>
    string(4) "ftps"
    [4]=>
    string(6) "gopher"
    [5]=>
    string(4) "http"
    [6]=>
    string(5) "https"
    [7]=>
    string(4) "imap"
    [8]=>
    string(5) "imaps"
    [9]=>
    string(4) "ldap"
    [10]=>
    string(4) "pop3"
    [11]=>
    string(5) "pop3s"
    [12]=>
    string(4) "rtsp"
    [13]=>
    string(3) "scp"
    [14]=>
    string(4) "sftp"
    [15]=>
    string(4) "smtp"
    [16]=>
    string(5) "smtps"
    [17]=>
    string(6) "telnet"
    [18]=>
    string(4) "tftp"
  }
}

curl is enable

javascript remove "disabled" attribute from html input

Set the element's disabled property to false:

document.getElementById('my-input-id').disabled = false;

If you're using jQuery, the equivalent would be:

$('#my-input-id').prop('disabled', false);

For several input fields, you may access them by class instead:

var inputs = document.getElementsByClassName('my-input-class');
for(var i = 0; i < inputs.length; i++) {
    inputs[i].disabled = false;
}

Where document could be replaced with a form, for instance, to find only the elements inside that form. You could also use getElementsByTagName('input') to get all input elements. In your for iteration, you'd then have to check that inputs[i].type == 'text'.

Lombok added but getters and setters not recognized in Intellij IDEA

Actually the lombok is working (if you run the project even with the IDE red alerts, you will see the project will run without error), but the IDE is not recognizing all the resources generated by the lombok annotations. So you have to install the lombok plugin, that's all!

How to pass a type as a method parameter in Java

You can pass an instance of java.lang.Class that represents the type, i.e.

private void foo(Class cls)

Assign output to variable in Bash

In shell, you don't put a $ in front of a variable you're assigning. You only use $IP when you're referring to the variable.

#!/bin/bash

IP=$(curl automation.whatismyip.com/n09230945.asp)

echo "$IP"

sed "s/IP/$IP/" nsupdate.txt | nsupdate

Warning: Cannot modify header information - headers already sent by ERROR

The long-term answer is that all output from your PHP scripts should be buffered in variables. This includes headers and body output. Then at the end of your scripts do any output you need.

The very quick fix for your problem will be to add

ob_start();

as the very first thing in your script, if you only need it in this one script. If you need it in all your scripts add it as the very first thing in your header.php file.

This turns on PHP's output buffering feature. In PHP when you output something (do an echo or print) it has to send the HTTP headers at that time. If you turn on output buffering you can output in the script but PHP doesn't have to send the headers until the buffer is flushed. If you turn it on and don't turn it off PHP will automatically flush everything in the buffer after the script finishes running. There really is no harm in just turning it on in almost all cases and could give you a small performance increase under some configurations.

If you have access to change your php.ini configuration file you can find and change or add the following

output_buffering = On

This will turn output buffering out without the need to call ob_start().

To find out more about output buffering check out http://php.net/manual/en/book.outcontrol.php

Posting raw image data as multipart/form-data in curl

In case anyone had the same problem: check this as @PravinS suggested. I used the exact same code as shown there and it worked for me perfectly.

This is the relevant part of the server code that helped:

if (isset($_POST['btnUpload']))
{
$url = "URL_PATH of upload.php"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
    $headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
    $postfields = array("filedata" => "@$filedata", "filename" => $filename);
    $ch = curl_init();
    $options = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => true,
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $postfields,
        CURLOPT_INFILESIZE => $filesize,
        CURLOPT_RETURNTRANSFER => true
    ); // cURL options
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    if(!curl_errno($ch))
    {
        $info = curl_getinfo($ch);
        if ($info['http_code'] == 200)
            $errmsg = "File uploaded successfully";
    }
    else
    {
        $errmsg = curl_error($ch);
    }
    curl_close($ch);
}
else
{
    $errmsg = "Please select the file";
}
}

html form should look something like:

<form action="uploadpost.php" method="post" name="frmUpload" enctype="multipart/form-data">
<tr>
  <td>Upload</td>
  <td align="center">:</td>
  <td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td align="center">&nbsp;</td>
  <td><input name="btnUpload" type="submit" value="Upload" /></td>
</tr>

Select default option value from typescript angular 6

For reactive form, I managed to make it work by using the following example (47 can be replaced with other value or variable):

<div [formGroup]="form">
  <select formControlName="fieldName">
    <option
        *ngFor="let option of options; index as i"
        [selected]="option === 47"
    >
        {{ option }}
    </option>
  </select>
</div>

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

As @Agam said,

You need this statement in your driver file: from AthleteList import AtheleteList

CSS body background image fixed to full screen even when zooming in/out

there is another technique

use

background-size:cover

That is it full set of css is

body { 
    background: url('images/body-bg.jpg') no-repeat center center fixed;
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
} 

Latest browsers support the default property.

How do I make CMake output into a 'bin' dir?

To add on to this:

If you're using CMAKE to generate a Visual Studio solution, and you want Visual Studio to output compiled files into /bin, Peter's answer needs to be modified a bit:

# set output directories for all builds (Debug, Release, etc.)
foreach( OUTPUTCONFIG ${CMAKE_CONFIGURATION_TYPES} )
    string( TOUPPER ${OUTPUTCONFIG} OUTPUTCONFIG )
    set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_SOURCE_DIR}/lib )
    set( CMAKE_LIBRARY_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_SOURCE_DIR}/lib )
    set( CMAKE_RUNTIME_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_SOURCE_DIR}/bin )
endforeach( OUTPUTCONFIG CMAKE_CONFIGURATION_TYPES )

Stored procedure or function expects parameter which is not supplied

in my case, I was passing all the parameters but one of the parameter my code was passing a null value for string.

Eg: cmd.Parameters.AddWithValue("@userName", userName);

in the above case, if the data type of userName is string, I was passing userName as null.

Interface vs Base class

Interfaces should be small. Really small. If you're really breaking down your objects, then your interfaces will probably only contain a few very specific methods and properties.

Abstract classes are shortcuts. Are there things that all derivatives of PetBase share that you can code once and be done with? If yes, then it's time for an abstract class.

Abstract classes are also limiting. While they give you a great shortcut to producing child objects, any given object can only implement one abstract class. Many times, I find this a limitation of Abstract classes, and this is why I use lots of interfaces.

Abstract classes may contain several interfaces. Your PetBase abstract class may implement IPet (pets have owners) and IDigestion (pets eat, or at least they should). However, PetBase will probably not implement IMammal, since not all pets are mammals and not all mammals are pets. You may add a MammalPetBase that extends PetBase and add IMammal. FishBase could have PetBase and add IFish. IFish would have ISwim and IUnderwaterBreather as interfaces.

Yes, my example is extensively over-complicated for the simple example, but that's part of the great thing about how interfaces and abstract classes work together.

Perl: function to trim string leading and trailing whitespace

This is available in String::Util with the trim method:

Editor's note: String::Util is not a core module, but you can install it from CPAN with [sudo] cpan String::Util.

use String::Util 'trim';
my $str = "  hello  ";
$str = trim($str);
print "string is now: '$str'\n";

prints:

string is now 'hello'

However it is easy enough to do yourself:

$str =~ s/^\s+//;
$str =~ s/\s+$//;

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.

GetRandomBits()

is not a static method. Either you have to create an instance of Program

Program p = new Program();
p.GetRandomBits();

or make

GetRandomBits() static.

Using other keys for the waitKey() function of opencv

The keycodes returned by waitKey seem platform dependent. However, it may be very educative, to see what the keys return (and by the way, on my platform, Esc does not return 27...)

The integers thay Abid's answer lists are mosty useless to the human mind (unless you're a prodigy savant...). However, if you examine them in hex, or take a look at the Least Significant Byte, you may notice patterns...

My script for examining the return values from waitKey is below:

#!/usr/bin/env python

import cv2
import sys

cv2.imshow(sys.argv[1], cv2.imread(sys.argv[1]))
res = cv2.waitKey(0)
print('You pressed %d (0x%x), LSB: %d (%s)' % (res, res, res % 256,
    repr(chr(res%256)) if res%256 < 128 else '?'))

You can use it as a minimal, command-line image viewer.

Some results, which I got:

  • q letter:

    You pressed 1048689 (0x100071), LSB: 113 ('q')

  • Escape key (traditionally, ASCII 27):

    You pressed 1048603 (0x10001b), LSB: 27 ('\x1b')

  • Space:

    You pressed 1048608 (0x100020), LSB: 32 (' ')

This list could go on, however you see the way to go, when you get 'strange' results.

BTW, if you want to put it in a loop, you can just waitKey(0) (wait forever), instead of ignoring the -1 return value.

EDIT: There's more to these high bits than meets the eye - please see Andrew C's answer (hint: it has to do with keyboard modifiers like all the "Locks" e.g. NumLock).

My recent experience shows however, that there is a platform dependence - e.g. OpenCV 4.1.0 from Anaconda on Python 3.6 on Windows doesn't produce these bits, and for some (important) keys is returns 0 from waitKey() (arrows, Home, End, PageDn, PageUp, even Del and Ins). At least Backspace returns 8 (but... why not Del?).

So, for a cross platform UI you're probably restricted to W, A, S, D, letters, digits, Esc, Space and Backspace ;)

Unexpected 'else' in "else" error

You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)       
} 

To put it more simply, if you have:

if(condition == TRUE) x <- TRUE
else x <- FALSE

Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:

if(condition == TRUE) {x <- TRUE
 } else {x <- FALSE}

how to define ssh private key for servers fetched by dynamic inventory in files

I had a similar issue and solved it with a patch to ec2.py and adding some configuration parameters to ec2.ini. The patch takes the value of ec2_key_name, prefixes it with the ssh_key_path, and adds the ssh_key_suffix to the end, and writes out ansible_ssh_private_key_file as this value.

The following variables have to be added to ec2.ini in a new 'ssh' section (this is optional if the defaults match your environment):

[ssh]
# Set the path and suffix for the ssh keys
ssh_key_path = ~/.ssh
ssh_key_suffix = .pem

Here is the patch for ec2.py:

204a205,206
>     'ssh_key_path': '~/.ssh',
>     'ssh_key_suffix': '.pem',
422a425,428
>         # SSH key setup
>         self.ssh_key_path = os.path.expanduser(config.get('ssh', 'ssh_key_path'))
>         self.ssh_key_suffix = config.get('ssh', 'ssh_key_suffix')
> 
1490a1497
>         instance_vars["ansible_ssh_private_key_file"] = os.path.join(self.ssh_key_path, instance_vars["ec2_key_name"] + self.ssh_key_suffix)

How to run the sftp command with a password from Bash script?

Bash program to wait for sftp to ask for a password then send it along:

#!/bin/bash
expect -c "
spawn sftp username@your_host
expect \"Password\"
send \"your_password_here\r\"
interact "

You may need to install expect, change the wording of 'Password' to lowercase 'p' to match what your prompt receives. The problems here is that it exposes your password in plain text in the file as well as in the command history. Which nearly defeats the purpose of having a password in the first place.

enable or disable checkbox in html

If you specify the disabled attribute then the value you give it must be disabled. (In HTML 5 you may leave off everything except the attribute value. In HTML 4 you may leave off everything except the attribute name.)

If you do not want the control to be disabled then do not specify the attribute at all.

Disabled:

<input type="checkbox" disabled>
<input type="checkbox" disabled="disabled">

Enabled:

<input type="checkbox">

Invalid (but usually error recovered to be treated as disabled):

<input type="checkbox" disabled="1">
<input type="checkbox" disabled="true">
<input type="checkbox" disabled="false">

So, without knowing your template language, I guess you are looking for:

<td><input type="checkbox" name="repriseCheckBox" {checkStat == 1 ? disabled : }/></td>

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

No, there's no way to use browser JavaScript to improve password security. I highly recommend you read this article. In your case, the biggest problem is the chicken-egg problem:

What's the "chicken-egg problem" with delivering Javascript cryptography?

If you don't trust the network to deliver a password, or, worse, don't trust the server not to keep user secrets, you can't trust them to deliver security code. The same attacker who was sniffing passwords or reading diaries before you introduce crypto is simply hijacking crypto code after you do.

[...]

Why can't I use TLS/SSL to deliver the Javascript crypto code?

You can. It's harder than it sounds, but you safely transmit Javascript crypto to a browser using SSL. The problem is, having established a secure channel with SSL, you no longer need Javascript cryptography; you have "real" cryptography.

Which leads to this:

The problem with running crypto code in Javascript is that practically any function that the crypto depends on could be overridden silently by any piece of content used to build the hosting page. Crypto security could be undone early in the process (by generating bogus random numbers, or by tampering with constants and parameters used by algorithms), or later (by spiriting key material back to an attacker), or --- in the most likely scenario --- by bypassing the crypto entirely.

There is no reliable way for any piece of Javascript code to verify its execution environment. Javascript crypto code can't ask, "am I really dealing with a random number generator, or with some facsimile of one provided by an attacker?" And it certainly can't assert "nobody is allowed to do anything with this crypto secret except in ways that I, the author, approve of". These are two properties that often are provided in other environments that use crypto, and they're impossible in Javascript.

Basically the problem is this:

  • Your clients don't trust your servers, so they want to add extra security code.
  • That security code is delivered by your servers (the ones they don't trust).

Or alternatively,

  • Your clients don't trust SSL, so they want you use extra security code.
  • That security code is delivered via SSL.

Note: Also, SHA-256 isn't suitable for this, since it's so easy to brute force unsalted non-iterated passwords. If you decide to do this anyway, look for an implementation of bcrypt, scrypt or PBKDF2.

How to stop/shut down an elasticsearch node?

Considering you have 3 nodes.

Prepare your cluster

export ES_HOST=localhost:9200

# Disable shard allocation
curl -X PUT "$ES_HOST/_cluster/settings" -H 'Content-Type: application/json' -d'
{
  "persistent": {
    "cluster.routing.allocation.enable": "none"
  }
}
'

# Stop non-essential indexing and perform a synced flush
curl -X POST "$ES_HOST/_flush/synced"

Stop elasticsearch service in each node

# check nodes
export ES_HOST=localhost:9200
curl -X GET "$ES_HOST/_cat/nodes"

# node 1
systemctl stop elasticsearch.service

# node 2
systemctl stop elasticsearch.service

# node 3
systemctl stop elasticsearch.service

Restarting cluster again

# start
systemctl start elasticsearch.service

# Reenable shard allocation once the node has joined the cluster
curl -X PUT "$ES_HOST/_cluster/settings" -H 'Content-Type: application/json' -d'
{
  "persistent": {
    "cluster.routing.allocation.enable": null
  }
}
'

Tested on Elasticseach 6.5

Source:

  1. https://www.elastic.co/guide/en/elasticsearch/reference/6.5/stopping-elasticsearch.html
  2. https://www.elastic.co/guide/en/elasticsearch/reference/6.5/rolling-upgrades.html

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

You can review the differences with a:

git log HEAD..origin/master

before pulling it (fetch + merge) (see also "How do you get git to always pull from a specific branch?")


When you have a message like:

"Your branch and 'origin/master' have diverged, # and have 1 and 1 different commit(s) each, respectively."

, check if you need to update origin. If origin is up-to-date, then some commits have been pushed to origin from another repo while you made your own commits locally.

... o ---- o ---- A ---- B  origin/master (upstream work)
                   \
                    C  master (your work)

You based commit C on commit A because that was the latest work you had fetched from upstream at the time.

However, before you tried to push back to origin, someone else pushed commit B.
Development history has diverged into separate paths.

You can then merge or rebase. See Pro Git: Git Branching - Rebasing for details.

Merge

Use the git merge command:

$ git merge origin/master

This tells Git to integrate the changes from origin/master into your work and create a merge commit.
The graph of history now looks like this:

... o ---- o ---- A ---- B  origin/master (upstream work)
                   \      \
                    C ---- M  master (your work)

The new merge, commit M, has two parents, each representing one path of development that led to the content stored in that commit.

Note that the history behind M is now non-linear.

Rebase

Use the git rebase command:

$ git rebase origin/master

This tells Git to replay commit C (your work) as if you had based it on commit B instead of A.
CVS and Subversion users routinely rebase their local changes on top of upstream work when they update before commit.
Git just adds explicit separation between the commit and rebase steps.

The graph of history now looks like this:

... o ---- o ---- A ---- B  origin/master (upstream work)
                          \
                           C'  master (your work)

Commit C' is a new commit created by the git rebase command.
It is different from C in two ways:

  1. It has a different history: B instead of A.
  2. Its content accounts for changes in both B and C; it is the same as M from the merge example.

Note that the history behind C' is still linear.
We have chosen (for now) to allow only linear history in cmake.org/cmake.git.
This approach preserves the CVS-based workflow used previously and may ease the transition.
An attempt to push C' into our repository will work (assuming you have permissions and no one has pushed while you were rebasing).

The git pull command provides a shorthand way to fetch from origin and rebase local work on it:

$ git pull --rebase

This combines the above fetch and rebase steps into one command.

JQuery show/hide when hover

This code also works.

_x000D_
_x000D_
$(".circle").hover(function() {$(this).hide(200).show(200);});
_x000D_
.circle{_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    border-radius:50px;_x000D_
    font-size:20px;_x000D_
    color:black;_x000D_
    line-height:100px;_x000D_
    text-align:center;_x000D_
    background:yellow_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>_x000D_
<div class="circle">hover me</div>
_x000D_
_x000D_
_x000D_

This declaration has no storage class or type specifier in C++

Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.

Find the line number where a specific word appears with "grep"

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX

How to initialize a static array?

Nope, no difference. It's just syntactic sugar. Arrays.asList(..) creates an additional list.

Case-insensitive search

There are two ways for case insensitive comparison:

  1. Convert strings to upper case and then compare them using the strict operator (===). How strict operator treats operands read stuff at: http://www.thesstech.com/javascript/relational-logical-operators

  2. Pattern matching using string methods:

    Use the "search" string method for case insensitive search. Read about search and other string methods at: http://www.thesstech.com/pattern-matching-using-string-methods

    <!doctype html>
      <html>
        <head>
          <script>
    
            // 1st way
    
            var a = "apple";
            var b = "APPLE";  
            if (a.toUpperCase() === b.toUpperCase()) {
              alert("equal");
            }
    
            //2nd way
    
            var a = " Null and void";
            document.write(a.search(/null/i)); 
    
          </script>
        </head>
    </html>
    

How to Convert date into MM/DD/YY format in C#

DateTime.Today.ToString("MM/dd/yy")

Look at the docs for custom date and time format strings for more info.

(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)

Others cultures really are a problem. For example, that code in portugues returns someting like 01-01-01 instead of 01/01/01. I also don't undestand why...

To resolve that problem i do someting like this:

        IFormatProvider yyyymmddFormat = new System.Globalization.CultureInfo(String.Empty, false);
        return date.ToString("MM/dd/yy", yyyymmddFormat);

HTML5 Video // Completely Hide Controls

There are two ways to hide video tag controls

  1. Remove the controls attribute from the video tag.

  2. Add the css to the video tag

    video::-webkit-media-controls-panel {
    display: none !important;
    opacity: 1 !important;}
    

Ajax Upload image

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

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

Here is the sample jQuery ajax image upload script

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


    },

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

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

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

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

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):

Android and iOS devices respect the following <meta> tag:

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this <meta> tag be included within the page's <head> element.

Android toolbar center title and custom font

I found another way to add custom toolbar without any adicional Java/Kotlin code.

  • First: create a XML with your custom toolbar layout with AppBarLayout as the parent:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.AppBarLayout                     
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">
    
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay">
    
        <ImageView
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginEnd="@dimen/magin_default"
            android:src="@drawable/logo" />
    
    </android.support.v7.widget.Toolbar>
    

  • Second: Include the toolbar in your layout:

    <?xml version="1.0" encoding="utf-8"?>                
    <android.support.constraint.ConstraintLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/blue"
        tools:context=".app.MainAcitivity"
        tools:layout_editor_absoluteY="81dp">
    
        <include
            layout="@layout/toolbar_inicio"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <!-- Put your layout here -->
    
    </android.support.constraint.ConstraintLayout>
    

Why is 2 * (i * i) faster than 2 * i * i in Java?

More of an addendum. I did repro the experiment using the latest Java 8 JVM from IBM:

java version "1.8.0_191"
Java(TM) 2 Runtime Environment, Standard Edition (IBM build 1.8.0_191-b12 26_Oct_2018_18_45 Mac OS X x64(SR5 FP25))
Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)

And this shows very similar results:

0.374653912 s
n = 119860736
0.447778698 s
n = 119860736

(second results using 2 * i * i).

Interestingly enough, when running on the same machine, but using Oracle Java:

Java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

results are on average a bit slower:

0.414331815 s
n = 119860736
0.491430656 s
n = 119860736

Long story short: even the minor version number of HotSpot matter here, as subtle differences within the JIT implementation can have notable effects.

Extract year from date

This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.

As pointed out, the lubridate package has nice extraction functions.

For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.

Is SQL syntax case sensitive?

The SQL92 specification states that identifiers might be quoted, or unquoted. If both sides are unquoted then they are always case-insensitive, e.g. table_name == TAble_nAmE.

However quoted identifiers are case-sensitive, e.g. "table_name" != "TAble_naME". Also based on the spec if you wish to compare unqouted identifiers with quoted ones, then unquoted and quoted identifiers can be considered the same, if the unquoted characters are uppercased, e.g. TABLE_NAME == "TABLE_NAME", but TABLE_NAME != "table_name" or TABLE_NAME != "TAble_NaMe".

Here is the relevant part of the spec (section 5.2.13):

     13)A <regular identifier> and a <delimited identifier> are equiva-
        lent if the <identifier body> of the <regular identifier> (with
        every letter that is a lower-case letter replaced by the equiva-
        lent upper-case letter or letters) and the <delimited identifier
        body> of the <delimited identifier> (with all occurrences of
        <quote> replaced by <quote symbol> and all occurrences of <dou-
        blequote symbol> replaced by <double quote>), considered as
        the repetition of a <character string literal> that specifies a
        <character set specification> of SQL_TEXT and an implementation-
        defined collation that is sensitive to case, compare equally
        according to the comparison rules in Subclause 8.2, "<comparison
        predicate>".

Note, that just like with other parts of the SQL standard, not all databases follow this section fully. PostgreSQL for example stores all unquoted identifiers lowercased instead of uppercased, so table_name == "table_name" (which is exactly the opposite of the standard). Also some databases are case-insensitive all the time, or case-sensitiveness depend on some setting in the DB or are dependent on some of the properties of the system, usually whether the filesystem is case-sensitive or not.

Note that some database tools might send identifiers quoted all the time, so in instances where you mix queries generated by some tool (like a CREATE TABLE query generated by Liquibase or other DB migration tool), with hand made queries (like a simple JDBC select in your application) you have to make sure that the cases are consistent, especially on databases where quoted and unquoted identifiers are different (DB2, PostgreSQL, etc.)

when I run mockito test occurs WrongTypeOfReturnValue Exception

For me this meant I was running this:

a = Mockito.mock(SomeClass.class);
b = new RealClass();
when(b.method1(a)).thenReturn(c); 
// within this method1, it calls param1.method2() -- note, b is not a spy or mock

So what was happening is that mockito was detecting that a.method2() was being called, and telling me I couldn't return c from a.method2() which is wrong.

Fix: use the doReturn(c).when(b).method1(a) style syntax (instead of when(b.method1(a)).thenReturn(c);), which will help you discover the hidden bug more concisely and quickly.

Or in this particular case, after doing that it started showing the more accurate "NotAMockException", and I changed it to not longer try to set a return value from a non-mock object.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

How to draw a graph in PHP?

pChart is another great PHP graphing library.

Can I call an overloaded constructor from another constructor of the same class in C#?

In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().

When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

How to set a time zone (or a Kind) of a DateTime value?

You can try this as well, it is easy to implement

TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);

Change the text to which standard time you want to change.

Use TimeZone feature of C# to implement.

In Javascript, how do I check if an array has duplicate values?

Well I did a bit of searching around the internet for you and I found this handy link.

Easiest way to find duplicate values in a JavaScript array

You can adapt the sample code that is provided in the above link, courtesy of "swilliams" to your solution.

Onclick CSS button effect

This is a press down button example I've made:

<div>
    <form id="forminput" action="action" method="POST">
       ...
    </form>
    <div style="right: 0px;bottom: 0px;position: fixed;" class="thumbnail">
        <div class="image">
            <a onclick="document.getElementById('forminput').submit();">
                <img src="images/button.png" alt="Some awesome text">
            </a>
        </div>
    </div>
</div>

the CSS file:

.thumbnail {
    width: 128px;
    height: 128px;
}

.image {
    width: 100%;
    height: 100%;    
}

.image img {
    -webkit-transition: all .25s ease; /* Safari and Chrome */
    -moz-transition: all .25s ease; /* Firefox */
    -ms-transition: all .25s ease; /* IE 9 */
    -o-transition: all .25s ease; /* Opera */
    transition: all .25s ease;
    max-width: 100%;
    max-height: 100%;
}

.image:hover img {
    -webkit-transform:scale(1.05); /* Safari and Chrome */
    -moz-transform:scale(1.05); /* Firefox */
    -ms-transform:scale(1.05); /* IE 9 */
    -o-transform:scale(1.05); /* Opera */
     transform:scale(1.05);
}

.image:active img {
    -webkit-transform:scale(.95); /* Safari and Chrome */
    -moz-transform:scale(.95); /* Firefox */
    -ms-transform:scale(.95); /* IE 9 */
    -o-transform:scale(.95); /* Opera */
     transform:scale(.95);
}

Enjoy it!

Image is not showing in browser?

I find out the way how to set the image path just remove the "/" before the destination folder as "images/66.jpg" not "/images/66.jpg" And its working fine for me.

Combining two expressions (Expression<Func<T, bool>>)

If you provider does not support Invoke and you need to combine two expression, you can use an ExpressionVisitor to replace the parameter in the second expression by the parameter in the first expression.

class ParameterUpdateVisitor : ExpressionVisitor
{
    private ParameterExpression _oldParameter;
    private ParameterExpression _newParameter;

    public ParameterUpdateVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
    {
        _oldParameter = oldParameter;
        _newParameter = newParameter;
    }

    protected override Expression VisitParameter(ParameterExpression node)
    {
        if (object.ReferenceEquals(node, _oldParameter))
            return _newParameter;

        return base.VisitParameter(node);
    }
}

static Expression<Func<T, bool>> UpdateParameter<T>(
    Expression<Func<T, bool>> expr,
    ParameterExpression newParameter)
{
    var visitor = new ParameterUpdateVisitor(expr.Parameters[0], newParameter);
    var body = visitor.Visit(expr.Body);

    return Expression.Lambda<Func<T, bool>>(body, newParameter);
}

[TestMethod]
public void ExpressionText()
{
    string text = "test";

    Expression<Func<Coco, bool>> expr1 = p => p.Item1.Contains(text);
    Expression<Func<Coco, bool>> expr2 = q => q.Item2.Contains(text);
    Expression<Func<Coco, bool>> expr3 = UpdateParameter(expr2, expr1.Parameters[0]);

    var expr4 = Expression.Lambda<Func<Recording, bool>>(
        Expression.OrElse(expr1.Body, expr3.Body), expr1.Parameters[0]);

    var func = expr4.Compile();

    Assert.IsTrue(func(new Coco { Item1 = "caca", Item2 = "test pipi" }));
}

What Are Some Good .NET Profilers?

The current release of SharpDevelop (3.1.1) has a nice integrated profiler. It's quite fast, and integrates very well into the SharpDevelop IDE and its NUnit runner. Results are displayed in a flexible Tree/List style (use LINQ to create your own selection). Doubleclicking the displayed method jumps directly into the source code.

Add onclick event to newly added element in JavaScript

You can also set attribute:

elem.setAttribute("onclick","alert('blah');");

How can I create a simple index.html file which lists all files/directories?

There's a free php script made by Celeron Dude that can do this called Celeron Dude Indexer 2. It doesn't require .htaccess The source code is easy to understand and provides a good starting point.

Here's a download link: https://gitlab.com/desbest/celeron-dude-indexer/

celeron dude indexer

How can you search Google Programmatically Java API

To search google using API you should use Google Custom Search, scraping web page is not allowed

In java you can use CustomSearch API Client Library for Java

The maven dependency is:

<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-customsearch</artifactId>
    <version>v1-rev57-1.23.0</version>
</dependency> 

Example code searching using Google CustomSearch API Client Library

public static void main(String[] args) throws GeneralSecurityException, IOException {

    String searchQuery = "test"; //The query to search
    String cx = "002845322276752338984:vxqzfa86nqc"; //Your search engine

    //Instance Customsearch
    Customsearch cs = new Customsearch.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), null) 
                   .setApplicationName("MyApplication") 
                   .setGoogleClientRequestInitializer(new CustomsearchRequestInitializer("your api key")) 
                   .build();

    //Set search parameter
    Customsearch.Cse.List list = cs.cse().list(searchQuery).setCx(cx); 

    //Execute search
    Search result = list.execute();
    if (result.getItems()!=null){
        for (Result ri : result.getItems()) {
            //Get title, link, body etc. from search
            System.out.println(ri.getTitle() + ", " + ri.getLink());
        }
    }

}

As you can see you will need to request an api key and setup an own search engine id, cx.

Note that you can search the whole web by selecting "Search entire web" on basic tab settings during setup of cx, but results will not be exactly the same as a normal browser google search.

Currently (date of answer) you get 100 api calls per day for free, then google like to share your profit.

Conda command not found

For Conda > 4.4 follow this:

$ echo ". /home/ubuntu/miniconda2/etc/profile.d/conda.sh" >> ~/.bashrc

then you need to reload user bash so you need to log out:

exit

and then log again.

Laravel: Get base url

You can use facades or helper function as per following.

echo URL::to('/');
echo url();

Laravel using Symfony Component for Request, Laravel internal logic as per following.

namespace Symfony\Component\HttpFoundation;
/**
* {@inheritdoc}
*/
protected function prepareBaseUrl()
{
    $baseUrl = $this->server->get('SCRIPT_NAME');

    if (false === strpos($this->server->get('REQUEST_URI'), $baseUrl)) {
        // assume mod_rewrite
        return rtrim(dirname($baseUrl), '/\\');
    }

    return $baseUrl;
}

What is the ellipsis (...) for in this method signature?

Those are Java varargs. They let you pass any number of objects of a specific type (in this case they are of type JID).

In your example, the following function calls would be valid:

MessageBuilder msgBuilder; //There should probably be a call to a constructor here ;)
MessageBuilder msgBuilder2;
msgBuilder.withRecipientJids(jid1, jid2);
msgBuilder2.withRecipientJids(jid1, jid2, jid78_a, someOtherJid);

See more here: http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html

Git error: src refspec master does not match any

You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

 git add a_text_file.txt 

... do:

 git commit -m "Initial commit."

... and those errors should go away.

Using Mockito, how do I verify a method was a called with a certain argument?

This is the better solution:

verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));

How can I suppress the newline after a print statement?

print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:

print "Foo %10s bar" % baz,

How to convert a 3D point into 2D perspective projection?

You might want to debug your system with spheres to determine whether or not you have a good field of view. If you have it too wide, the spheres with deform at the edges of the screen into more oval forms pointed toward the center of the frame. The solution to this problem is to zoom in on the frame, by multiplying the x and y coordinates for the 3 dimensional point by a scalar and then shrinking your object or world down by a similar factor. Then you get the nice even round sphere across the entire frame.

I'm almost embarrassed that it took me all day to figure this one out and I was almost convinced that there was some spooky mysterious geometric phenomenon going on here that demanded a different approach.

Yet, the importance of calibrating the zoom-frame-of-view coefficient by rendering spheres cannot be overstated. If you do not know where the "habitable zone" of your universe is, you will end up walking on the sun and scrapping the project. You want to be able to render a sphere anywhere in your frame of view an have it appear round. In my project, the unit sphere is massive compared to the region that I'm describing.

Also, the obligatory wikipedia entry: Spherical Coordinate System

How do I get and set Environment variables in C#?

This will work for an environment variable that is machine setting. For Users, just change to User instead.

String EnvironmentPath = System.Environment
                .GetEnvironmentVariable("Variable_Name", EnvironmentVariableTarget.Machine);

Getting Data from Android Play Store

Disclaimer: I am from 42matters, who provides this data already on https://42matters.com/api , feel free to check it out or drop us a line.

As lenik mentioned there are open-source libraries that already help with obtaining some data from GPlay. If you want to build one yourself you can try to parse the Google Play App page, but you should pay attention to the following:

  • Make sure the URL you are trying to parse is not blocked in robots.txt - e.g. https://play.google.com/robots.txt
  • Make sure that you are not doing it too often, Google will throttle and potentially blacklist you if you are doing it too much.
  • Send a correct User-Agent header to actually show you are a bot
  • The page of an app is big - make sure you accept gzip and request the mobile version
  • GPlay website is not an API, it doesn't care that you parse it so it will change over time. Make sure you handle changes - e.g. by having test to make sure you get what you expected.

So that in mind getting one page metadata is a matter of fetching the page html and parsing it properly. With JSoup you can try:

      HttpClient httpClient = HttpClientBuilder.create().build();
      HttpGet request = new HttpGet(crawlUrl);
      HttpResponse rsp = httpClient.execute(request);

      int statusCode = rsp.getStatusLine().getStatusCode();

      if (statusCode == 200) {
           String content = EntityUtils.toString(rsp.getEntity());    
           Document doc = Jsoup.parse(content);
           //parse content, whatever you need
           Element price = doc.select("[itemprop=price]").first();
      }      

For that very simple use case that should get you started. However, the moment you want to do more interesting stuff, things get complicated:

  • Search is forbidden in robots.
  • Keeping app metadata up-to-date is hard to do. There are more than 2.2m apps, if you want to refresh their metadata daily there are 2.2 requests/day, which will 1) get blocked immediately, 2) costs a lot of money - pessimistic 220gb data transfer per day if one app is 100k
  • How do you discover new apps
  • How do you get pricing in each country, translations of each language

The list goes on. If you don't want to do all this by yourself, you can consider 42matters API, which supports lookup and search, top google charts, advanced queries and filters. And this for 35 languages and more than 50 countries.

[2]:

Communicating between a fragment and an activity - best practices

It is implemented by a Callback interface:

First of all, we have to make an interface:

public interface UpdateFrag {
     void updatefrag();
}

In the Activity do the following code:

UpdateFrag updatfrag ;

public void updateApi(UpdateFrag listener) {
        updatfrag = listener;
}

from the event from where the callback has to fire in the Activity:

updatfrag.updatefrag();

In the Fragment implement the interface in CreateView do the following code:

 ((Home)getActivity()).updateApi(new UpdateFrag() {
        @Override
        public void updatefrag() {
              .....your stuff......
        }
 });

How to represent a fix number of repeats in regular expression?

The finite repetition syntax uses {m,n} in place of star/plus/question mark.

From java.util.regex.Pattern:

X{n}      X, exactly n times
X{n,}     X, at least n times
X{n,m}    X, at least n but not more than m times

All repetition metacharacter have the same precedence, so just like you may need grouping for *, +, and ?, you may also for {n,m}.

  • ha* matches e.g. "haaaaaaaa"
  • ha{3} matches only "haaa"
  • (ha)* matches e.g. "hahahahaha"
  • (ha){3} matches only "hahaha"

Also, just like *, +, and ?, you can add the ? and + reluctant and possessive repetition modifiers respectively.

    System.out.println(
        "xxxxx".replaceAll("x{2,3}", "[x]")
    ); "[x][x]"

    System.out.println(
        "xxxxx".replaceAll("x{2,3}?", "[x]")
    ); "[x][x]x"

Essentially anywhere a * is a repetition metacharacter for "zero-or-more", you can use {...} repetition construct. Note that it's not true the other way around: you can use finite repetition in a lookbehind, but you can't use * because Java doesn't officially support infinite-length lookbehind.

References

Related questions

Differences between Lodash and Underscore.js

I just found one difference that ended up being important for me. The non-Underscore.js-compatible version of Lodash's _.extend() does not copy over class-level-defined properties or methods.

I've created a Jasmine test in CoffeeScript that demonstrates this:

https://gist.github.com/softcraft-development/1c3964402b099893bd61

Fortunately, lodash.underscore.js preserves Underscore.js's behaviour of copying everything, which for my situation was the desired behaviour.

Replace one substring for another string in shell script

This can be done entirely with bash string manipulation:

first="I love Suzy and Mary"
second="Sara"
first=${first/Suzy/$second}

That will replace only the first occurrence; to replace them all, double the first slash:

first="Suzy, Suzy, Suzy"
second="Sara"
first=${first//Suzy/$second}
# first is now "Sara, Sara, Sara"

How to enable native resolution for apps on iPhone 6 and 6 Plus?

An error was encountered while running (Domain = LaunchServicesError, Code = 0)

Usually this indicates that installd returned an error during the install process (bad resources or similar).

Unfortunately, Xcode does not display the actual underlying error (feel free to file dupes of this known bug).

You should check ~/Library/Logs/CoreSimulator/CoreSimulator.log which will log the underlying error for you.

Return Index of an Element in an Array Excel VBA

'To return the position of an element within any-dimension array  
'Returns 0 if the element is not in the array, and -1 if there is an error  
Public Function posInArray(ByVal itemSearched As Variant, ByVal aArray As Variant) As Long  
Dim pos As Long, item As Variant  

posInArray = -1  
If IsArray(aArray) Then  
    If not IsEmpty(aArray) Then  
        pos = 1  
        For Each item In aArray  
            If itemSearched = item Then  
                posInArray = pos  
                Exit Function  
            End If  
            pos = pos + 1  
        Next item  
        posInArray = 0  
    End If  
End If

End Function

href overrides ng-click in Angular.js

//for dynamic elements - if you want it in ng-repeat do below code

angular.forEach($scope.data, function(value, key) {
     //add new value to object
    value.new_url  = "your url";
});

 <div ng-repeat="row in data"><a ng-href="{{ row.url_content }}"></a></div>

"Fatal error: Cannot redeclare <function>"

Since the code you've provided does not explicitly include anything, either it is being incldued twice, or (if the script is the entry point for the code) there must be a auto-prepend set up in the webserver config / php.ini or alternatively you've got a really obscure extension loaded which defines the function.

Squash my last X commits together using Git

2020 Simple solution without rebase :

git reset --soft HEAD~2

git commit -m "new commit message"

git push -f

2 means the last two commits will be squashed. You can replace it by any number

Need to install urllib2 for Python 3.5.1

In Python 3, urllib2 was replaced by two in-built modules named urllib.request and urllib.error

Adapted from source


So replace this:

import urllib2

With this:

import urllib.request as urllib2

Can Mockito capture arguments of a method called multiple times?

I think it should be

verify(mockBar, times(2)).doSomething(...)

Sample from mockito javadoc:

ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
verify(mock, times(2)).doSomething(peopleCaptor.capture());

List<Person> capturedPeople = peopleCaptor.getAllValues();
assertEquals("John", capturedPeople.get(0).getName());
assertEquals("Jane", capturedPeople.get(1).getName());

How can I get the name of an html page in Javascript?

Current page: It's possible to do even shorter. This single line sound more elegant to find the current page's file name:

var fileName = location.href.split("/").slice(-1); 

or...

var fileName = location.pathname.split("/").slice(-1)

This is cool to customize nav box's link, so the link toward the current is enlighten by a CSS class.

JS:

$('.menu a').each(function() {
    if ($(this).attr('href') == location.href.split("/").slice(-1)){ $(this).addClass('curent_page'); }
});

CSS:

a.current_page { font-size: 2em; color: red; }

How do I split a string, breaking at a particular character?

You don't need jQuery.

var s = 'john smith~123 Street~Apt 4~New York~NY~12345';
var fields = s.split(/~/);
var name = fields[0];
var street = fields[1];

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

This is a slight modification to Edens answer - which for me in chrome didn't catch the error. Although you'll still get an error in the console: "Refused to display 'https://www.google.ca/' in a frame because it set 'X-Frame-Options' to 'sameorigin'." At least this will catch the error message and then you can deal with it.

 <iframe id="myframe" src="https://google.ca"></iframe>

 <script>
 myframe.onload = function(){
 var that = document.getElementById('myframe');

 try{
    (that.contentWindow||that.contentDocument).location.href;
 }
 catch(err){
    //err:SecurityError: Blocked a frame with origin "http://*********" from accessing a cross-origin frame.
    console.log('err:'+err);
}
}
</script>

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Ruby on Rails form_for select field with class

Try this way:

<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>

select helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options.

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

White spaces are required between publicId and systemId

If you're working from some network that requires you to use a proxy in your browser to connect to the internet (likely an office building), that might be it. I had the same issue and adding the proxy configs to the network settings solved it.

  • Go to your preferences (Eclipse -> Preferences on a Mac, or Window -> Preferences on a Windows)
  • Then -> General -> expand to view the list underneath -> Select Network Connections (don't expand)
  • At the top of the page that appears there is a drop down, select "Manual."
  • Then select "HTTP" in the list directly below the drop down (which now should have all it's options checked) and then click the "Edit" button to the right of the list.
  • Enter in the proxy url and port you need to connect to the internet in your web browser normally.
  • Repeat for "HTTPS."

If you don't know the proxy url and port, talk to your network admin.

get all keys set in memcached

The easiest way is to use python-memcached-stats package, https://github.com/abstatic/python-memcached-stats

The keys() method should get you going.

Example -

from memcached_stats import MemcachedStats
mem = MemcachedStats()

mem.keys()
['key-1',
 'key-2',
 'key-3',
 ... ]

Access to the path is denied

I had a lot of trouble with this, specifically related to my code running locally but when I needed to run it on IIS it was throwing this error. I found that adding a check to my code and letting the application create the folder on the first run fixed the issue without having to mess with the folders authorizations.

something like this before you call your method that uses the folder

bool exists = System.IO.Directory.Exists("mypath");

        if (!exists)
            System.IO.Directory.CreateDirectory("mypath");

How to monitor Java memory usage?

If you use java 1.5, you can look at ManagementFactory.getMemoryMXBean() which give you numbers on all kinds of memory. heap and non-heap, perm-gen.

A good example can be found there http://www.freshblurbs.com/explaining-java-lang-outofmemoryerror-permgen-space

$(document).on("click"... not working?

This works:

<div id="start-element">Click Me</div>

$(document).on("click","#test-element",function() {
    alert("click");
});

$(document).on("click","#start-element",function() {
    $(this).attr("id", "test-element");
});

Here is the Fiddle

Invalid use side-effecting operator Insert within a function

You can't use a function to insert data into a base table. Functions return data. This is listed as the very first limitation in the documentation:

User-defined functions cannot be used to perform actions that modify the database state.

"Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way).

You should be using a stored procedure, not a function.

How do I perform HTML decoding/encoding using Python/Django?

I found this in the Cheetah source code (here)

htmlCodes = [
    ['&', '&amp;'],
    ['<', '&lt;'],
    ['>', '&gt;'],
    ['"', '&quot;'],
]
htmlCodesReversed = htmlCodes[:]
htmlCodesReversed.reverse()
def htmlDecode(s, codes=htmlCodesReversed):
    """ Returns the ASCII decoded version of the given HTML string. This does
        NOT remove normal HTML tags like <p>. It is the inverse of htmlEncode()."""
    for code in codes:
        s = s.replace(code[1], code[0])
    return s

not sure why they reverse the list, I think it has to do with the way they encode, so with you it may not need to be reversed. Also if I were you I would change htmlCodes to be a list of tuples rather than a list of lists... this is going in my library though :)

i noticed your title asked for encode too, so here is Cheetah's encode function.

def htmlEncode(s, codes=htmlCodes):
    """ Returns the HTML encoded version of the given string. This is useful to
        display a plain ASCII text string on a web page."""
    for code in codes:
        s = s.replace(code[0], code[1])
    return s

How to get Selected Text from select2 when using <input>

This one is working fine using V 4.0.3

var vv = $('.mySelect2');     
var label = $(vv).children("option[value='"+$(vv).select2("val")+"']").first().html();
console.log(label); 

How to access route, post, get etc. parameters in Zend Framework 2

require_once 'lib/Zend/Loader/StandardAutoloader.php';
$loader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));

$loader->registerNamespace('Http\PhpEnvironment', 'lib/Zend/Http'); 

// Register with spl_autoload:
$loader->register();

$a = new Zend\Http\PhpEnvironment\Request();
print_r($a->getQuery()->get()); exit;

Powershell send-mailmessage - email to multiple recipients

$recipients = "Marcel <[email protected]>, Marcelt <[email protected]>"

is type of string you need pass to send-mailmessage a string[] type (an array):

[string[]]$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"

I think that not casting to string[] do the job for the coercing rules of powershell:

$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"

is object[] type but can do the same job.

How to set 00:00:00 using moment.js

Moment.js stores dates it utc and can apply different timezones to it. By default it applies your local timezone. If you want to set time on utc date time you need to specify utc timezone.

Try the following code:

var m = moment().utcOffset(0);
m.set({hour:0,minute:0,second:0,millisecond:0})
m.toISOString()
m.format()

jQuery hide and show toggle div with plus and minus icon

I would say the most elegant way is this:

<div class="toggle"></div>
<div class="content">...</div>

then css:

.toggle{
 display:inline-block;
height:48px;
width:48px;  background:url("http://icons.iconarchive.com/icons/pixelmixer/basic/48/plus-icon.png");
}
.toggle.expanded{
  background:url("http://cdn2.iconfinder.com/data/icons/onebit/PNG/onebit_32.png");
}

and js:

$(document).ready(function(){
  var $content = $(".content").hide();
  $(".toggle").on("click", function(e){
    $(this).toggleClass("expanded");
    $content.slideToggle();
  });
});

FIDDLE

How do I replicate a \t tab space in HTML?

&nbsp;&nbsp;&nbsp;&nbsp; would be a work around if you're only after the spacing.

Converting milliseconds to minutes and seconds with Javascript

There is probably a better way to do this, but it gets the job done:

var ms = 298999;
var min = ms / 1000 / 60;
var r = min % 1;
var sec = Math.floor(r * 60);
if (sec < 10) {
    sec = '0'+sec;
}
min = Math.floor(min);
console.log(min+':'+sec);

Not sure why you have the << operator in your minutes line, I don't think it's needed just floor the minutes before you display.

Getting the remainder of the minutes with % gives you the percentage of seconds elapsed in that minute, so multiplying it by 60 gives you the amount of seconds and flooring it makes it more fit for display although you could also get sub-second precision if you want.

If seconds are less than 10 you want to display them with a leading zero.

Passing data between controllers in Angular JS?

Make a factory in your module and add a reference of the factory in controller and use its variables in the controller and now get the value of data in another controller by adding reference where ever you want

How to set background color in jquery

How about this:

$(this).css('background-color', '#FFFFFF');

Related post: Add background color and border to table row on hover using jquery

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I have had the same issue, but in a class that was not a part of the service layer. In my case, the transaction manager was simply obtained from the context by the getBean() method, and the class belonged to the view layer - my project utilizes OpenSessionInView technique.

The sessionFactory.getCurrentSession() method, has been causing the same exception as the author's. The solution for me was rather simple.

Session session;

try {
    session = sessionFactory.getCurrentSession();
} catch (HibernateException e) {
    session = sessionFactory.openSession();
}

If the getCurrentSession() method fails, the openSession() should do the trick.

Reportviewer tool missing in visual studio 2017 RC

If you're like me and tried a few of these methods and are stuck at the point that you have the control in the toolbox and can draw it on the form but it disappears from the form and puts it down in the components, then simply edit the designer and add the following in the appropriate area of InitializeComponent() to make it visible:

this.Controls.Add(this.reportViewer1);

or

[ContainerControl].Controls.Add(this.reportViewer1);

You'll also need to make adjustments to the location and size manually after you've added the control.

Not a great answer for sure, but if you're stuck and just need to get work done for now until you have more time to figure it out, it should help.

Oracle - How to create a readonly user

A user in an Oracle database only has the privileges you grant. So you can create a read-only user by simply not granting any other privileges.

When you create a user

CREATE USER ro_user
 IDENTIFIED BY ro_user
 DEFAULT TABLESPACE users
 TEMPORARY TABLESPACE temp;

the user doesn't even have permission to log in to the database. You can grant that

GRANT CREATE SESSION to ro_user

and then you can go about granting whatever read privileges you want. For example, if you want RO_USER to be able to query SCHEMA_NAME.TABLE_NAME, you would do something like

GRANT SELECT ON schema_name.table_name TO ro_user

Generally, you're better off creating a role, however, and granting the object privileges to the role so that you can then grant the role to different users. Something like

Create the role

CREATE ROLE ro_role;

Grant the role SELECT access on every table in a particular schema

BEGIN
  FOR x IN (SELECT * FROM dba_tables WHERE owner='SCHEMA_NAME')
  LOOP
    EXECUTE IMMEDIATE 'GRANT SELECT ON schema_name.' || x.table_name || 
                                  ' TO ro_role';
  END LOOP;
END;

And then grant the role to the user

GRANT ro_role TO ro_user;

MySQL remove all whitespaces from the entire column

Working Query:

SELECT replace(col_name , ' ','') FROM table_name;

While this doesn't :

SELECT trim(col_name) FROM table_name;

Is there a date format to display the day of the week in java?

This should display 'Tue':

new SimpleDateFormat("EEE").format(new Date());

This should display 'Tuesday':

new SimpleDateFormat("EEEE").format(new Date());

This should display 'T':

new SimpleDateFormat("EEEEE").format(new Date());

So your specific example would be:

new SimpleDateFormat("yyyy-MM-EEE").format(new Date());

How to get the size of a string in Python?

Do you want to find the length of the string in python language ? If you want to find the length of the word, you can use the len function.

string = input("Enter the string : ")

print("The string length is : ",len(string))

OUTPUT : -

Enter the string : viral

The string length is : 5

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

How to remove space from string?

The tools sed or tr will do this for you by swapping the whitespace for nothing

sed 's/ //g'

tr -d ' '

Example:

$ echo "   3918912k " | sed 's/ //g'
3918912k

How to set background image of a view?

You can set multiple background image in every view using custom method as below.

make plist for every theam with background image name and other color

#import <Foundation/Foundation.h>
@interface ThemeManager : NSObject
@property (nonatomic,strong) NSDictionary*styles;
+ (ThemeManager *)sharedManager;
-(void)selectTheme;
 @end

             #import "ThemeManager.h"

            @implementation ThemeManager
            @synthesize styles;
            + (ThemeManager *)sharedManager
            {
                static ThemeManager *sharedManager = nil;
                if (sharedManager == nil)
                {
                    sharedManager = [[ThemeManager alloc] init];
                }
                [sharedManager selectTheme];
                return sharedManager;
            }
            - (id)init
            {
                if ((self = [super init]))
                {

                }
                return self;
            }
            -(void)selectTheme{
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                NSString *themeName = [defaults objectForKey:@"AppTheme"] ?: @"DefaultTheam";

                NSString *path = [[NSBundle mainBundle] pathForResource:themeName ofType:@"plist"];
                self.styles = [NSDictionary dictionaryWithContentsOfFile:path];
            }
            @end

Can use this via

 NSDictionary *styles = [ThemeManager sharedManager].styles;
 NSString *imageName = [styles objectForKey:@"backgroundImage"];
[imgViewBackGround setImage:[UIImage imageNamed:imageName]];

How to have image and text side by side

You're already doing it correctly, it just that the <h4>Facebook</h4> tag is taking too much vertical margin. You can remove it by using the style margin:0px on the <h4> tag.

For your future convenience, you can put border (border:1px solid black) on your elements to see which part you actually get it wrong.

How do I store and retrieve a blob from sqlite?

Here's how you can do it in C#:

class Program
{
    static void Main(string[] args)
    {
        if (File.Exists("test.db3"))
        {
            File.Delete("test.db3");
        }
        using (var connection = new SQLiteConnection("Data Source=test.db3;Version=3"))
        using (var command = new SQLiteCommand("CREATE TABLE PHOTOS(ID INTEGER PRIMARY KEY AUTOINCREMENT, PHOTO BLOB)", connection))
        {
            connection.Open();
            command.ExecuteNonQuery();

            byte[] photo = new byte[] { 1, 2, 3, 4, 5 };

            command.CommandText = "INSERT INTO PHOTOS (PHOTO) VALUES (@photo)";
            command.Parameters.Add("@photo", DbType.Binary, 20).Value = photo;
            command.ExecuteNonQuery();

            command.CommandText = "SELECT PHOTO FROM PHOTOS WHERE ID = 1";
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    byte[] buffer = GetBytes(reader);
                }
            }

        }
    }

    static byte[] GetBytes(SQLiteDataReader reader)
    {
        const int CHUNK_SIZE = 2 * 1024;
        byte[] buffer = new byte[CHUNK_SIZE];
        long bytesRead;
        long fieldOffset = 0;
        using (MemoryStream stream = new MemoryStream())
        {
            while ((bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length)) > 0)
            {
                stream.Write(buffer, 0, (int)bytesRead);
                fieldOffset += bytesRead;
            }
            return stream.ToArray();
        }
    }
}

TypeError: module.__init__() takes at most 2 arguments (3 given)

Even after @Mickey Perlstein's answer and his 3 hours of detective work, it still took me a few more minutes to apply this to my own mess. In case anyone else is like me and needs a little more help, here's what was going on in my situation.

  • responses is a module
  • Response is a base class within the responses module
  • GeoJsonResponse is a new class derived from Response

Initial GeoJsonResponse class:

from pyexample.responses import Response

class GeoJsonResponse(Response):

    def __init__(self, geo_json_data):

Looks fine. No problems until you try to debug the thing, which is when you get a bunch of seemingly vague error messages like this:

from pyexample.responses import GeoJsonResponse ..\pyexample\responses\GeoJsonResponse.py:12: in (module) class GeoJsonResponse(Response):

E TypeError: module() takes at most 2 arguments (3 given)

=================================== ERRORS ====================================

___________________ ERROR collecting tests/test_geojson.py ____________________

test_geojson.py:2: in (module) from pyexample.responses import GeoJsonResponse ..\pyexample\responses \GeoJsonResponse.py:12: in (module)

class GeoJsonResponse(Response): E TypeError: module() takes at most 2 arguments (3 given)

ERROR: not found: \PyExample\tests\test_geojson.py::TestGeoJson::test_api_response

C:\Python37\lib\site-packages\aenum__init__.py:163

(no name 'PyExample\ tests\test_geojson.py::TestGeoJson::test_api_response' in any of [])

The errors were doing their best to point me in the right direction, and @Mickey Perlstein's answer was dead on, it just took me a minute to put it all together in my own context:

I was importing the module:

from pyexample.responses import Response

when I should have been importing the class:

from pyexample.responses.Response import Response

Hope this helps someone. (In my defense, it's still pretty early.)

Difference between string and text in rails?

The difference relies in how the symbol is converted into its respective column type in query language.

with MySQL :string is mapped to VARCHAR(255)

:string |                   VARCHAR                | :limit => 1 to 255 (default = 255)  
:text   | TINYTEXT, TEXT, MEDIUMTEXT, or LONGTEXT2 | :limit => 1 to 4294967296 (default = 65536)

Reference:

https://hub.packtpub.com/working-rails-activerecord-migrations-models-scaffolding-and-database-completion/

When should each be used?

As a general rule of thumb, use :string for short text input (username, email, password, titles, etc.) and use :text for longer expected input such as descriptions, comment content, etc.

CSS strikethrough different color from text?

Assigning the desired line-through color to a parent element works for the deleted text element (<del>) as well - making the assumption the client renders <del> as a line-through.

http://jsfiddle.net/kpowz/vn9RC/

How to add image to canvas

In my case, I was mistaken the function parameters, which are:

context.drawImage(image, left, top);
context.drawImage(image, left, top, width, height);

If you expect them to be

context.drawImage(image, width, height);

you will place the image just outside the canvas with the same effects as described in the question.

What's the difference between interface and @interface in java?

interface:

In general, an interface exposes a contract without exposing the underlying implementation details. In Object Oriented Programming, interfaces define abstract types that expose behavior, but contain no logic. Implementation is defined by the class or type that implements the interface.

@interface : (Annotation type)

Take the below example, which has a lot of comments:

public class Generation3List extends Generation2List {

   // Author: John Doe
   // Date: 3/17/2002
   // Current revision: 6
   // Last modified: 4/12/2004
   // By: Jane Doe
   // Reviewers: Alice, Bill, Cindy

   // class code goes here

}

Instead of this, you can declare an annotation type

 @interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}

which can then annotate a class as follows:

@ClassPreamble (
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {

// class code goes here

}

PS: Many annotations replace comments in code.

Reference: http://docs.oracle.com/javase/tutorial/java/annotations/declaring.html

Getting the .Text value from a TextBox

Did you try using t.Text?

Which is more efficient, a for-each loop, or an iterator?

foreach uses iterators under the hood anyway. It really is just syntactic sugar.

Consider the following program:

import java.util.List;
import java.util.ArrayList;

public class Whatever {
    private final List<Integer> list = new ArrayList<>();
    public void main() {
        for(Integer i : list) {
        }
    }
}

Let's compile it with javac Whatever.java,
And read the disassembled bytecode of main(), using javap -c Whatever:

public void main();
  Code:
     0: aload_0
     1: getfield      #4                  // Field list:Ljava/util/List;
     4: invokeinterface #5,  1            // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator;
     9: astore_1
    10: aload_1
    11: invokeinterface #6,  1            // InterfaceMethod java/util/Iterator.hasNext:()Z
    16: ifeq          32
    19: aload_1
    20: invokeinterface #7,  1            // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object;
    25: checkcast     #8                  // class java/lang/Integer
    28: astore_2
    29: goto          10
    32: return

We can see that foreach compiles down to a program which:

  • Creates iterator using List.iterator()
  • If Iterator.hasNext(): invokes Iterator.next() and continues loop

As for "why doesn't this useless loop get optimized out of the compiled code? we can see that it doesn't do anything with the list item": well, it's possible for you to code your iterable such that .iterator() has side-effects, or so that .hasNext() has side-effects or meaningful consequences.

You could easily imagine that an iterable representing a scrollable query from a database might do something dramatic on .hasNext() (like contacting the database, or closing a cursor because you've reached the end of the result set).

So, even though we can prove that nothing happens in the loop body… it is more expensive (intractable?) to prove that nothing meaningful/consequential happens when we iterate. The compiler has to leave this empty loop body in the program.

The best we could hope for would be a compiler warning. It's interesting that javac -Xlint:all Whatever.java does not warn us about this empty loop body. IntelliJ IDEA does though. Admittedly I have configured IntelliJ to use Eclipse Compiler, but that may not be the reason why.

enter image description here

How do I find the PublicKeyToken for a particular dll?

Answer is very simple use the .NET Framework tools sn.exe. So open the Visual Studio 2008 Command Prompt and then point to the dll’s folder you want to get the public key,

Use the following command,

sn –T myDLL.dll

This will give you the public key token. Remember one thing this only works if the assembly has to be strongly signed.

Example

C:\WINNT\Microsoft.NET\Framework\v3.5>sn -T EdmGen.exe

Microsoft (R) .NET Framework Strong Name Utility  Version 3.5.21022.8
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key token is b77a5c561934e089

scrollable div inside container

Instead of overflow:auto, try overflow-y:auto. Should work like a charm!

how to get the last part of a string before a certain character?

Difference between split and partition is split returns the list without delimiter and will split where ever it gets delimiter in string i.e.

x = 'http://test.com/lalala-134-431'

a,b,c = x.split(-)
print(a)
"http://test.com/lalala"
print(b)
"134"
print(c)
"431"

and partition will divide the string with only first delimiter and will only return 3 values in list

x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala"
print(b)
"-"
print(c)
"134-431"

so as you want last value you can use rpartition it works in same way but it will find delimiter from end of string

x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"

C++ Singleton design pattern

C++11 Thread safe implementation:

 #include <iostream>
 #include <thread>


 class Singleton
 {
     private:
         static Singleton * _instance;
         static std::mutex mutex_;

     protected:
         Singleton(const std::string value): value_(value)
         {
         }
         ~Singleton() {}
         std::string value_;

     public:
         /**
          * Singletons should not be cloneable.
          */
         Singleton(Singleton &other) = delete;
         /**
          * Singletons should not be assignable.
          */
         void operator=(const Singleton &) = delete;

         //static Singleton *GetInstance(const std::string& value);
         static Singleton *GetInstance(const std::string& value)
         {
             if (_instance == nullptr)
             {
                 std::lock_guard<std::mutex> lock(mutex_);
                 if (_instance == nullptr)
                 {
                     _instance = new Singleton(value);
                 }
             }
             return _instance;
         }

         std::string value() const{
             return value_;
         }
 };

 /**
  * Static methods should be defined outside the class.
  */
 Singleton* Singleton::_instance = nullptr;
 std::mutex Singleton::mutex_;


 void ThreadFoo(){
     std::this_thread::sleep_for(std::chrono::milliseconds(10));
     Singleton* singleton = Singleton::GetInstance("FOO");
     std::cout << singleton->value() << "\n";
 }

 void ThreadBar(){
     std::this_thread::sleep_for(std::chrono::milliseconds(1000));
     Singleton* singleton = Singleton::GetInstance("BAR");
     std::cout << singleton->value() << "\n";
 }

 int main()
 {
     std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<
                 "If you see different values, then 2 singletons were created (booo!!)\n\n" <<
                 "RESULT:\n";
     std::thread t1(ThreadFoo);
     std::thread t2(ThreadBar);
     t1.join();
     t2.join();
     std::cout << "Complete!" << std::endl;

     return 0;
 }

JNZ & CMP Assembly Instructions

JNZ     Jump if Not Zero    ZF=0

Indeed, this is confusing right.

To make it easier to understand, replace Not Zero with Not Set. (Please take note this is for your own understanding)

Hence,

JNZ     Jump if Not Set     ZF=0

Not Set means flag Z = 0. So Jump (Jump if Not Set)

Set means flag Z = 1. So, do NOT Jump

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

Extract values in Pandas value_counts()

Try this:

dataframe[column].value_counts().index.tolist()
['apple', 'sausage', 'banana', 'cheese']

Convert a PHP script into a stand-alone windows executable

ExeOutput is also can Turn PHP Websites into Windows Applications and Software

Turn PHP Websites into Windows Applications and Software

Applications made with ExeOutput for PHP run PHP scripts, PHP applications, and PHP websites natively, and do not require a web server, a web browser, or PHP distribution. They are stand-alone and work on any computer with recent Windows versions.

ExeOutput for PHP is a powerful website compiler that works with all of the elements found on modern sites: PHP scripts, JavaScript, HTML, CSS, XML, PDF files, Flash, Flash videos, Silverlight videos, databases, and images. Combining these elements with PHP Runtime and PHP Extensions, ExeOutput for PHP builds an EXE file that contains your complete application.

http://www.exeoutput.com/

How do I remove all .pyc files from a project?

First run:

find . -type f -name "*.py[c|o]" -exec rm -f {} +

Then add:

export PYTHONDONTWRITEBYTECODE=1

To ~/.profile

Daemon Threads Explanation

A simpler way to think about it, perhaps: when main returns, your process will not exit if there are non-daemon threads still running.

A bit of advice: Clean shutdown is easy to get wrong when threads and synchronization are involved - if you can avoid it, do so. Use daemon threads whenever possible.

How to merge a Series and DataFrame

If df is a pandas.DataFrame then df['new_col']= Series list_object of length len(df) will add the or Series list_object as a column named 'new_col'. df['new_col']= scalar (such as 5 or 6 in your case) also works and is equivalent to df['new_col']= [scalar]*len(df)

So a two-line code serves the purpose:

df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]})
s = pd.Series({'s1':5, 's2':6})
for x in s.index:    
    df[x] = s[x]

Output: 
   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

Reversing a String with Recursion in Java

Best Solution what I found.

public class Manager
{
    public static void main(String[] args)
    {
        System.out.println("Sameer after reverse : " 
                         + Manager.reverse("Sameer"));
        System.out.println("Single Character a after reverse : " 
                         + Manager.reverse("a"));
        System.out.println("Null Value after reverse : "
                         + Manager.reverse(null));
        System.out.println("Rahul after reverse : "
                         + Manager.reverse("Rahul"));
    }

    public static String reverse(String args)
    {
        if(args == null || args.length() < 1 
                                || args.length() == 1)
        {
            return args;
        }
        else
        {
                return "" + 
                               args.charAt(args.length()-1) + 
                               reverse(args.substring(0, args.length()-1));                                  
        }
    }
}

Output:C:\Users\admin\Desktop>java Manager Sameer after reverse : reemaS Single Character a after reverse : a Null Value after reverse : null Rahul after reverse : luhaR

Change marker size in Google maps V3

The size arguments are in pixels. So, to double your example's marker size the fifth argument to the MarkerImage constructor would be:

new google.maps.Size(42,68)

I find it easiest to let the map API figure out the other arguments, unless I need something other than the bottom/center of the image as the anchor. In your case you could do:

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);

How to make a class JSON serializable

class DObject(json.JSONEncoder):
    def delete_not_related_keys(self, _dict):
        for key in ["skipkeys", "ensure_ascii", "check_circular", "allow_nan", "sort_keys", "indent"]:
            try:
                del _dict[key]
            except:
                continue

    def default(self, o):
        if hasattr(o, '__dict__'):
            my_dict = o.__dict__.copy()
            self.delete_not_related_keys(my_dict)
            return my_dict
        else:
            return o

a = DObject()
a.name = 'abdul wahid'
b = DObject()
b.name = a

print(json.dumps(b, cls=DObject))

Creating a recursive method for Palindrome

public static boolean isPalindrome(String p)
    {
        if(p.length() == 0 || p.length() == 1)
            // if length =0 OR 1 then it is
            return true; 

         if(p.substring(0,1).equalsIgnoreCase(p.substring(p.length()-1))) 
            return isPalindrome(p.substring(1, p.length()-1));


        return false;
    }

This solution is not case sensitive. Hence, for example, if you have the following word : "adinida", then you will get true if you do "Adninida" or "adninida" or "adinidA", which is what we want.

I like @JigarJoshi answer, but the only problem with his approach is that it will give you false for words which contains caps.

Align text to the bottom of a div

Flex Solution

It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

_x000D_
_x000D_
.wrap {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border: 1px solid #aaa;_x000D_
  margin: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
  align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <span>Align me to the bottom</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.


Old Solution (Valid if you are not willing to use flex)

If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

_x000D_
_x000D_
div {_x000D_
  display: table-cell;_x000D_
  vertical-align: bottom;_x000D_
  border: 1px solid #f00;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
_x000D_
_x000D_

(Or JSFiddle)

One line ftp server in python

I dont know about a one-line FTP server, but if you do

python -m SimpleHTTPServer

It'll run an HTTP server on 0.0.0.0:8000, serving files out of the current directory. If you're looking for a way to quickly get files off a linux box with a web browser, you cant beat it.

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

Quick Fix: I have the same problem to start the MongoDB and it was easily fixed by running the file mongod.exe (C:\Program Files\MongoDB\Server\3.2\bin) then run the file mongo.exe (C:\Program Files\MongoDB\Server\3.2\bin)..Problem fixed

Mixing C# & VB In The Same Project

Well, actually I inherited a project some years ago from a colleague who had decided to mix VB and C# webforms within the same project. That worked but is far from fun to maintain.

I decided that new code should be C# classes and to get them to work I had to add a subnode to the compilation part of web.config

        <codeSubDirectories>
            <add directoryName="VB"/>
            <add directoryName="CS"/>
        </codeSubDirectories>

The all VB code goes into a subfolder in the App_Code called VB and the C# code into the CS subfolder. This will produce two .dll files. It works, but code is compiled in the same order as listed in "codeSubDirectories" and therefore i.e Interfaces should be in the VB folder if used in both C# and VB.

I have both a reference to a VB and a C# compiler in

<system.codedom>
    <compilers>

The project is currently updated to framework 3.5 and it still works (but still no fun to maintain..)

Redirect output of mongo query to a csv file

Extending other answers:

I found @GEverding's answer most flexible. It also works with aggregation:

test_db.js

print("name,email");

db.users.aggregate([
    { $match: {} }
]).forEach(function(user) {
        print(user.name+","+user.email);
    }
});

Execute the following command to export results:

mongo test_db < ./test_db.js >> ./test_db.csv

Unfortunately, it adds additional text to the CSV file which requires processing the file before we can use it:

MongoDB shell version: 3.2.10 
connecting to: test_db

But we can make mongo shell stop spitting out those comments and only print what we have asked for by passing the --quiet flag

mongo --quiet test_db < ./test_db.js >> ./test_db.csv

Concatenate a NumPy array to another NumPy array

You may use numpy.append()...

import numpy

B = numpy.array([3])
A = numpy.array([1, 2, 2])
B = numpy.append( B , A )

print B

> [3 1 2 2]

This will not create two separate arrays but will append two arrays into a single dimensional array.

Remove property for all objects in array

_x000D_
_x000D_
var array = [{"bad": "something", "good":"something"},{"bad":"something", "good":"something"}];_x000D_
var results = array.map(function(item){_x000D_
  return {good : item["good"]}_x000D_
});_x000D_
console.log(JSON.stringify(results));
_x000D_
_x000D_
_x000D_

How do I select the "last child" with a specific class name in CSS?

$('.class')[$(this).length - 1] 

or

$( "p" ).last().addClass( "selected" );

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL

UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";

Hope this helps someone else.

jQuery.ajax returns 400 Bad Request

I was getting the 400 Bad Request error, even after setting:

contentType: "application/json",
dataType: "json"

The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.

This was my initial code:

var data = {
    "TestId": testId,
    "PlayerId": parseInt(playerId),
    "Result": result
};

var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
    url: url,
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify(data), // issue with a property type in the data object
    dataType: "json",
    error: function (e) {
        console.log(e); // logging the error object to console
    },
    success: function () {
        console.log('Success saving test result');
    }
});

Now after making the request, I checked the console tab in the browser development tool.
It looked like this: enter image description here

responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.

Changing the data object creation like below fixed the issue for me:

var data = {
        "TestId": String(testId), //converting testId to a string
        "PlayerId": parseInt(playerId),
        "Result": result
};

I assume other possible errors could also be identified by logging and inspecting the error object.

Cannot connect to SQL Server named instance from another SQL Server

Do you have any Client Aliases defined on your Development Machine? If so, then define them the same on SQLB also. Specifically, I suspect that you have Client Aliases in InstanceName format that are defining the ports, thus bypassing the actual Instance names and the need for SQL Browser (partially). There are other possibilities with Client Aliases also though, so just make sure that they are the same.

To check for SQL Client Aliases, use the SQL Server Configuration Manager, (in the microsoft SQLServer, Program Start menu). In there, goto Client Configuration, and then "Aliases".


Other things to check:

  1. That SQLA and SQLB are either in the same domain, or that there is not a Trust issues between them.

  2. Make sure that SQLB has TCP/IP enabled as a Client Protocol (this is also in SQL configuration Manager).


By some of your responses I think that you may have missed the point of my statements about Domains and Trusts. You cannot connect to a SQL "Server\Instance" unless there is sufficient trust between the client and the server. This is because the whole Instance-Naming scheme that SQL Sevrer uses is dependent on SPNs (Service Principal Names) for discovery, location and authorization, and SPNs are stored in the AD. So unless the client is on the same box, the instance needs to be able to register its SPN and the client needs to be able to browse whatever AD forest the server instance registered it's SPN into.

If you cannot do that, then Instance names effectively do not work and you have to use the Port number (or pipe name) instead. This is what I now suspect is going on.

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

Asynchronous vs synchronous execution, what does it really mean?

As a really simple example,

SYNCHRONOUS

Imagine 3 school students instructed to run a relay race on a road.

1st student runs her given distance, stops and passes the baton to the 2nd. No one else has started to run.

1------>
        2.
                3.

When the 2nd student retrieves the baton, she starts to run her given distance.

      1.
        2------>
                3.

The 2nd student got her shoelace untied. Now she has stopped and tying up again. Because of this, 2nd's end time has got extended and the 3rd's starting time has got delayed.

      1.
        --2.--->
                3.

This pattern continues on till the 3rd retrieves the baton from 2nd and finishes the race.

ASYNCHRONOUS

Just Imagine 10 random people walking on the same road. They're not on a queue of course, just randomly walking on different places on the road in different paces.

2nd person's shoelace got untied. She stopped to get it tied up again.

But nobody is waiting for her to get it tied up. Everyone else is still walking the same way they did before, in that same pace of theirs.

10-->    9-->
   8--> 7-->   6-->
 5-->     4-->
1-->   2.    3-->

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

How to mark a build unstable in Jenkins when running shell scripts

Duplicating my answer from here because I spent some time looking for this:

This is now possible in newer versions of Jenkins, you can do something like this:

#!/usr/bin/env groovy

properties([
  parameters([string(name: 'foo', defaultValue: 'bar', description: 'Fails job if not bar (unstable if bar)')]),
])


stage('Stage 1') {
  node('parent'){
    def ret = sh(
      returnStatus: true, // This is the key bit!
      script: '''if [ "$foo" = bar ]; then exit 2; else exit 1; fi'''
    )
    // ret can be any number/range, does not have to be 2.
    if (ret == 2) {
      currentBuild.result = 'UNSTABLE'
    } else if (ret != 0) {
      currentBuild.result = 'FAILURE'
      // If you do not manually error the status will be set to "failed", but the
      // pipeline will still run the next stage.
      error("Stage 1 failed with exit code ${ret}")
    }
  }
}

The Pipeline Syntax generator shows you this in the advanced tab:

Pipeline Syntax Example

How to add an Access-Control-Allow-Origin header

Check this link.. It will definitely solve your problem.. There are plenty of solutions to make cross domain GET Ajax calls BUT POST REQUEST FOR CROSS DOMAIN IS SOLVED HERE. It took me 3 days to figure it out.

http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx

What is the canonical way to trim a string in Ruby without creating a new string?

There's no need to both strip and chomp as strip will also remove trailing carriage returns - unless you've changed the default record separator and that's what you're chomping.

Olly's answer already has the canonical way of doing this in Ruby, though if you find yourself doing this a lot you could always define a method for it:

def strip_or_self!(str)
  str.strip! || str
end

Giving:

@title = strip_or_self!(tokens[Title]) if tokens[Title]

Also keep in mind that the if statement will prevent @title from being assigned if the token is nil, which will result in it keeping its previous value. If you want or don't mind @title always being assigned you can move the check into the method and further reduce duplication:

def strip_or_self!(str)
  str.strip! || str if str
end

As an alternative, if you're feeling adventurous you can define a method on String itself:

class String
  def strip_or_self!
    strip! || self
  end
end

Giving one of:

@title = tokens[Title].strip_or_self! if tokens[Title]

@title = tokens[Title] && tokens[Title].strip_or_self!

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Node Version Manager (NVM) on Windows

1.downlad nvm 
2.install chocolaty
3.change C:\Program Files\node   to C:\Program Files\nodejsx

emphasized textThe first thing that we need to do is install NVM. website : https://docs.microsoft.com/en-us/windows/nodejs/setup-on-windows

What does $@ mean in a shell script?

$@ is all of the parameters passed to the script.

For instance, if you call ./someScript.sh foo bar then $@ will be equal to foo bar.

If you do:

./someScript.sh foo bar

and then inside someScript.sh reference:

umbrella_corp_options "$@"

this will be passed to umbrella_corp_options with each individual parameter enclosed in double quotes, allowing to take parameters with blank space from the caller and pass them on.

SQL Update to the SUM of its joined values

Use a sub query similar to the below.

UPDATE P
SET extrasPrice = sub.TotalPrice from
BookingPitches p
inner join 
(Select PitchID, Sum(Price) TotalPrice
    from  dbo.BookingPitchExtras
    Where [Required] = 1
    Group by Pitchid
) as Sub
on p.Id = e.PitchId 
where p.BookingId = 1

Can't connect to local MySQL server through socket '/tmp/mysql.sock

Make sure your /etc/hosts has 127.0.0.1 localhost in it and it should work fine

Getting the current Fragment instance in the viewpager

I tried the following:

 int index = mViewPager.getCurrentItem();
 List<Fragment> fragments = getSupportFragmentManager().getFragments();
 View rootView = fragments.get(index).getView();

Unable to merge dex

If this error appeared for you after including kotlin support, and none of the other solutions work, try changing the kotlin dependency of app module's build.gradle to:

implementation ("org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version") {
    exclude group: 'org.jetbrains', module: 'annotations'
}

This works for me on Android Studio 3.0 Beta 6. See this answer for further explanation.

What is a NullPointerException, and how do I fix it?

Question: What causes a NullPointerException (NPE)?

As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying "no object".

A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:

public class Test {
    public static void main(String[] args) {
        String foo = null;
        int length = foo.length();   // HERE
    }
}

the statement labeled "HERE" is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException.

There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:

  • assign it to a reference variable or read it from a reference variable,
  • assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
  • pass it as a parameter or return it as a result, or
  • test it using the == or != operators, or instanceof.

Question: How do I read the NPE stacktrace?

Suppose that I compile and run the program above:

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:4)
$

First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac compiler doesn't.)

Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code if you take the time to read it carefully.

So let's look at what it says:

Exception in thread "main" java.lang.NullPointerException

The first line of the stack trace tells you a number of things:

  • It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...
  • It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException.
  • If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message.

The second line is the most important one in diagnosing an NPE.

at Test.main(Test.java:4)

This tells us a number of things:

  • "at Test.main" says that we were in the main method of the Test class.
  • "Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.

If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.

Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.

In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE.

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

1 - Not quite true. There are things called nested exceptions...

Question: How do I track down the cause of the NPE exception in my code?

This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation.

Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:

int length = foo.length(); // HERE

How can that throw an NPE?

In fact, there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and... BANG!

But (I hear you say) what if the NPE was thrown inside the length() method call?

Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String class and line 4 of Test.java would be the second "at" line.

So where did that null come from? In this case, it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.)

OK, so let's try a slightly more tricky example. This will require some logical deduction.

public class Test {

    private static String[] foo = new String[2];

    private static int test(String[] bar, int pos) {
        return bar[pos].length();
    }

    public static void main(String[] args) {
        int length = test(foo, 1);
    }
}

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.test(Test.java:6)
    at Test.main(Test.java:10)
$ 

So now we have two "at" lines. The first one is for this line:

return args[pos].length();

and the second one is for this line:

int length = test(foo, 1);
    

Looking at the first line, how could that throw an NPE? There are two ways:

  • If the value of bar is null then bar[pos] will throw an NPE.
  • If the value of bar[pos] is null then calling length() on it will throw an NPE.

Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:

Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null ... but that is not happening here.)

So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is this possible?

Indeed it is! And that is the problem. When we initialize like this:

private static String[] foo = new String[2];

we allocate a String[] with two elements that are initialized to null. After that, we have not changed the contents of foo ... so foo[1] will still be null.

What about on Android?

On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using and the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause.

But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when getViewById unexpectedly returns a null. My advice would be to search for Q&As about the cause of the unexpected null return value.

Accessing a resource via codebehind in WPF

You should use System.Windows.Controls.UserControl's FindResource() or TryFindResource() methods.

Also, a good practice is to create a string constant which maps the name of your key in the resource dictionary (so that you can change it at only one place).

Reading a date using DataReader

 (DateTime)MyReader["ColumnName"];

OR

Convert.ToDateTime(MyReader["ColumnName"]);

Adding blank spaces to layout

The previous answers didn't work in my case. However, creating an empty item in the menu does.

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
  ...
  <item />
  ...
</menu>

How to make the window full screen with Javascript (stretching all over the screen)

Now that the full screen APIs are more widespread and appear to be maturing, why not try Screenfull.js? I used it for the first time yesterday and today our app goes truly full screen in (almost) all browsers!

Be sure to couple it with the :fullscreen pseudo-class in CSS. See https://www.sitepoint.com/use-html5-full-screen-api/ for more.

isolating a sub-string in a string before a symbol in SQL Server 2008

This can achieve using two SQL functions- SUBSTRING and CHARINDEX

You can read strings to a variable as shown in the above answers, or can add it to a SELECT statement as below:

SELECT SUBSTRING('Net Operating Loss - 2007' ,0, CHARINDEX('-','Net Operating Loss - 2007'))

How can I put a ListView into a ScrollView without it collapsing?

thanks to Vinay's code here is my code for when you can't have a listview inside a scrollview yet you need something like that

LayoutInflater li = LayoutInflater.from(this);

                RelativeLayout parent = (RelativeLayout) this.findViewById(R.id.relativeLayoutCliente);

                int recent = 0;

                for(Contatto contatto : contatti)
                {
                    View inflated_layout = li.inflate(R.layout.header_listview_contatti, layout, false);


                    inflated_layout.setId(contatto.getId());
                    ((TextView)inflated_layout.findViewById(R.id.textViewDescrizione)).setText(contatto.getDescrizione());
                    ((TextView)inflated_layout.findViewById(R.id.textViewIndirizzo)).setText(contatto.getIndirizzo());
                    ((TextView)inflated_layout.findViewById(R.id.textViewTelefono)).setText(contatto.getTelefono());
                    ((TextView)inflated_layout.findViewById(R.id.textViewMobile)).setText(contatto.getMobile());
                    ((TextView)inflated_layout.findViewById(R.id.textViewFax)).setText(contatto.getFax());
                    ((TextView)inflated_layout.findViewById(R.id.textViewEmail)).setText(contatto.getEmail());



                    RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

                    if (recent == 0)
                    {
                        relativeParams.addRule(RelativeLayout.BELOW, R.id.headerListViewContatti);
                    }
                    else
                    {
                        relativeParams.addRule(RelativeLayout.BELOW, recent);
                    }
                    recent = inflated_layout.getId();

                    inflated_layout.setLayoutParams(relativeParams);
                    //inflated_layout.setLayoutParams( new RelativeLayout.LayoutParams(source));

                    parent.addView(inflated_layout);
                }

the relativeLayout stays inside a ScrollView so it all becomes scrollable :)

What is correct media query for IPad Pro?

I tried several of the proposed answers but the problem is that the media queries conflicted with other queries and instead of displaying the mobile CSS on the iPad Pro, it was displaying the desktop CSS. So instead of using max and min for dimensions, I used the EXACT VALUES and it works because on the iPad pro you can't resize the browser.

Note that I added a query for mobile CSS that I use for devices with less than 900px width; feel free to remove it if needed.

This is the query, it combines both landscape and portrait, it works for the 12.9" and if you need to target the 10.5" you can simply add the queries for these dimensions:

@media only screen and (max-width: 900px), 
(height: 1024px) and (width: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: landscape), 
(width: 1024px) and (height: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: portrait)  {

     // insert mobile and iPad Pro 12.9" CSS here    
}

Matching special characters and letters in regex

Try this RegEx: Matching special charecters which we use in paragraphs and alphabets

   Javascript : /^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$/.test(str)

                .test(str) returns boolean value if matched true and not matched false

            c# :  ^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$

JQuery Find #ID, RemoveClass and AddClass

Try this

$('#testID').addClass('nameOfClass');

or

$('#testID').removeClass('nameOfClass');

Count number of rows per group and add result to original data frame

The base R function aggregate will obtain the counts with a one-liner, but adding those counts back to the original data.frame seems to take a bit of processing.

df <- data.frame(name=c('black','black','black','red','red'),
                 type=c('chair','chair','sofa','sofa','plate'),
                 num=c(4,5,12,4,3))
df
#    name  type num
# 1 black chair   4
# 2 black chair   5
# 3 black  sofa  12
# 4   red  sofa   4
# 5   red plate   3

rows.per.group  <- aggregate(rep(1, length(paste0(df$name, df$type))),
                             by=list(df$name, df$type), sum)
rows.per.group
#   Group.1 Group.2 x
# 1   black   chair 2
# 2     red   plate 1
# 3   black    sofa 1
# 4     red    sofa 1

my.summary <- do.call(data.frame, rows.per.group)
colnames(my.summary) <- c(colnames(df)[1:2], 'rows.per.group')
my.data <- merge(df, my.summary, by = c(colnames(df)[1:2]))
my.data
#    name  type num rows.per.group
# 1 black chair   4              2
# 2 black chair   5              2
# 3 black  sofa  12              1
# 4   red plate   3              1
# 5   red  sofa   4              1

How do I convert a String to an int in Java?

I'm have a solution, but I do not know how effective it is. But it works well, and I think you could improve it. On the other hand, I did a couple of tests with JUnit which step correctly. I attached the function and testing:

static public Integer str2Int(String str) {
    Integer result = null;
    if (null == str || 0 == str.length()) {
        return null;
    }
    try {
        result = Integer.parseInt(str);
    } 
    catch (NumberFormatException e) {
        String negativeMode = "";
        if(str.indexOf('-') != -1)
            negativeMode = "-";
        str = str.replaceAll("-", "" );
        if (str.indexOf('.') != -1) {
            str = str.substring(0, str.indexOf('.'));
            if (str.length() == 0) {
                return (Integer)0;
            }
        }
        String strNum = str.replaceAll("[^\\d]", "" );
        if (0 == strNum.length()) {
            return null;
        }
        result = Integer.parseInt(negativeMode + strNum);
    }
    return result;
}

Testing with JUnit:

@Test
public void testStr2Int() {
    assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
    assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
    assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
    assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
    assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
    assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
    assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
    assertEquals("Not
     is numeric", null, Helper.str2Int("czv.,xcvsa"));
    /**
     * Dynamic test
     */
    for(Integer num = 0; num < 1000; num++) {
        for(int spaces = 1; spaces < 6; spaces++) {
            String numStr = String.format("%0"+spaces+"d", num);
            Integer numNeg = num * -1;
            assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
            assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
        }
    }
}

Open soft keyboard programmatically

in onCreate method of activity or onActivityCreated of a fragment

....
view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            view.removeOnPreDrawListener(this);
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

            // !Pay attention to return `true`
            // Chet Haase told to 
            return true;
        }
    });

Convert generic list to dataset in C#

I found this code on Microsoft forum. This is so far one of easiest way, easy to understand and use. This has saved me hours , I have customized it as extension method without any change to actual method. Below is the code. it doesn't require much explanation.

You can use two function signature with same implementation

1) public static DataSet ToDataSetFromObject(this object dsCollection)

2) public static DataSet ToDataSetFromArrayOfObject( this object[] arrCollection) . I 'll be using this one for example.

// <summary>
// Serialize Object to XML and then read it into a DataSet:
// </summary>
// <param name="arrCollection">Array of object</param>
// <returns>dataset</returns>

public static DataSet ToDataSetFromArrayOfObject( this object[] arrCollection)
{
    DataSet ds = new DataSet();
    try {
        XmlSerializer serializer = new XmlSerializer(arrCollection.GetType);
        System.IO.StringWriter sw = new System.IO.StringWriter();
        serializer.Serialize(sw, dsCollection);
        System.IO.StringReader reader = new System.IO.StringReader(sw.ToString());
        ds.ReadXml(reader);
    } catch (Exception ex) {
        throw (new Exception("Error While Converting Array of Object to Dataset."));
    }
    return ds;
}

To use this extension in code

Country[] objArrayCountry = null;
objArrayCountry = ....;// populate your array
if ((objArrayCountry != null)) {
    dataset = objArrayCountry.ToDataSetFromArrayOfObject();
}

How to determine an object's class?

checking with isinstance() would not be enough if you want to know in run time. use:

if(someObject.getClass().equals(C.class){
    // do something
}

Is it possible to have multiple styles inside a TextView?

In fact, except the Html object, you also could use the Spannable type classes, e.g. TextAppearanceSpan or TypefaceSpan and SpannableString togather. Html class also uses these mechanisms. But with the Spannable type classes, you've more freedom.

Is there a way to split a widescreen monitor in to two or more virtual monitors?

Right now, I'm using twinsplay to organize my windows side by side.

I tried Winsplit before, but I couldn't get it to work because the default hotkeys ( Ctrl-Alt-Left, Ctrl-Alt-Right ) clashed with the graphics card hotkeys for rotating my screen and setting different hotkeys just didn't work. Twinsplay just worked for me out of the box.

Another nice thing about twinsplay is that it also allows me to save and restore windows "sessions" - so I can save my work environment ( eclipse, total commander, visual studio, msdn, outlook, firefox ) before turning off the computer at night and then quickly get back to it in the morning.

React onClick function fires on render

JSX will evaluate JavaScript expressions in curly braces

In this case, this.props.removeTaskFunction(todo) is invoked and the return value is assigned to onClick

What you have to provide for onClick is a function. To do this, you can wrap the value in an anonymous function.

export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
    const taskNodes = todoTasks.map(todo => (
                <div>
                    {todo.task}
                    <button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
                </div>
            );
    return (
        <div className="todo-task-list">
            {taskNodes}
        </div>
        );
    }
});

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

In my case.I was getting missing element error pointing to NuGet.Config file. At that time it was looking some thing like this

<?xml version="1.0" encoding="utf-8"?>
<settings>
  <repositoryPath>Packages</repositoryPath>
</settings>

then I just added configuration tag that actually wraps entire xml. Now working fine for me

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <settings>
     <repositoryPath>Packages</repositoryPath>
  </settings>
</configuration>

Generate random password string with requirements in javascript

For someone who is looking for a simplest script. No while (true), no if/else, no declaration.

Base on mwag's answer, but this one uses crypto.getRandomValues, a stronger random than Math.random.

Array(20)
  .fill('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$')
  .map(x => x[Math.floor(crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * x.length)])
  .join('');

See this for 0xffffffff.

Alternative 1

var generatePassword = (
  length = 20,
  wishlist = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$"
) => Array(length)
      .fill('')
      .map(() => wishlist[Math.floor(crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * wishlist.length)])
      .join('');

console.log(generatePassword());

Alternative 2

var generatePassword = (
  length = 20,
  wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$'
) =>
  Array.from(crypto.getRandomValues(new Uint32Array(length)))
    .map((x) => wishlist[x % wishlist.length])
    .join('')

console.log(generatePassword())

Node.js

const crypto = require('crypto')

const generatePassword = (
  length = 20,
  wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$'
) =>
  Array.from(crypto.randomFillSync(new Uint32Array(length)))
    .map((x) => wishlist[x % wishlist.length])
    .join('')

console.log(generatePassword())

The endpoint reference (EPR) for the Operation not found is

As described by Eran Chinthaka at http://wso2.com/library/176/

If Axis2 engine cannot find a service and an operation for a message, it immediately fails, sending a fault to the sender. If service not found - "Service Not found EPR is " If service found but not an operation- "Operation Not found EPR is and WSA Action = "

In your case the service is found but the operation not. The Axis2 engine uses SOAPAction in order to figure out the requested operation and, in your example, the SOAPAction is missing, therefore I would try to define the SOAPAction header

How to use if-else option in JSTL

There is no if-else, just if.

<c:if test="${user.age ge 40}">
 You are over the hill.
</c:if>

Optionally you can use choose-when:

<c:choose>
  <c:when test="${a boolean expr}">
    do something
  </c:when>
  <c:when test="${another boolean expr}">
    do something else
  </c:when>
  <c:otherwise>
    do this when nothing else is true
  </c:otherwise>
</c:choose>

Best way to check if a URL is valid

function is_url($uri){
    if(preg_match( '/^(http|https):\\/\\/[a-z0-9_]+([\\-\\.]{1}[a-z_0-9]+)*\\.[_a-z]{2,5}'.'((:[0-9]{1,5})?\\/.*)?$/i' ,$uri)){
      return $uri;
    }
    else{
        return false;
    }
}

How to hide the keyboard when I press return key in a UITextField?

In viewDidLoad declare:

[yourTextField setDelegate:self];

Then, include the override of the delegate method:

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

How do you get the magnitude of a vector in Numpy?

Fastest way I found is via inner1d. Here's how it compares to other numpy methods:

import numpy as np
from numpy.core.umath_tests import inner1d

V = np.random.random_sample((10**6,3,)) # 1 million vectors
A = np.sqrt(np.einsum('...i,...i', V, V))
B = np.linalg.norm(V,axis=1)   
C = np.sqrt((V ** 2).sum(-1))
D = np.sqrt((V*V).sum(axis=1))
E = np.sqrt(inner1d(V,V))

print [np.allclose(E,x) for x in [A,B,C,D]] # [True, True, True, True]

import cProfile
cProfile.run("np.sqrt(np.einsum('...i,...i', V, V))") # 3 function calls in 0.013 seconds
cProfile.run('np.linalg.norm(V,axis=1)')              # 9 function calls in 0.029 seconds
cProfile.run('np.sqrt((V ** 2).sum(-1))')             # 5 function calls in 0.028 seconds
cProfile.run('np.sqrt((V*V).sum(axis=1))')            # 5 function calls in 0.027 seconds
cProfile.run('np.sqrt(inner1d(V,V))')                 # 2 function calls in 0.009 seconds

inner1d is ~3x faster than linalg.norm and a hair faster than einsum

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

If it is going to be a web based application, you can also use the ServletContextListener interface.

public class SLF4JBridgeListener implements ServletContextListener {

   @Autowired 
   ThreadPoolTaskExecutor executor;

   @Autowired 
   ThreadPoolTaskScheduler scheduler;

    @Override
    public void contextInitialized(ServletContextEvent sce) {

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
         scheduler.shutdown();
         executor.shutdown();     

    }

}

(change) vs (ngModelChange) in angular

In Angular 7, the (ngModelChange)="eventHandler()" will fire before the value bound to [(ngModel)]="value" is changed while the (change)="eventHandler()" will fire after the value bound to [(ngModel)]="value" is changed.

What are the differences between WCF and ASMX web services?

Keith Elder nicely compares ASMX to WCF here. Check it out.

Another comparison of ASMX and WCF can be found here - I don't 100% agree with all the points there, but it might give you an idea.

WCF is basically "ASMX on stereoids" - it can be all that ASMX could - plus a lot more!.

ASMX is:

  • easy and simple to write and configure
  • only available in IIS
  • only callable from HTTP

WCF can be:

  • hosted in IIS, a Windows Service, a Winforms application, a console app - you have total freedom
  • used with HTTP (REST and SOAP), TCP/IP, MSMQ and many more protocols

In short: WCF is here to replace ASMX fully.

Check out the WCF Developer Center on MSDN.

Update: link seems to be dead - try this: What Is Windows Communication Foundation?

Python: How to remove empty lists from a list?

You can use filter() instead of a list comprehension:

list2 = filter(None, list1)

If None is used as first argument to filter(), it filters out every value in the given list, which is False in a boolean context. This includes empty lists.

It might be slightly faster than the list comprehension, because it only executes a single function in Python, the rest is done in C.

How to determine the content size of a UIWebView?

AFAIK you can use [webView sizeThatFits:CGSizeZero] to figure out it's content size.

Inserting a text where cursor is using Javascript/jquery

How to insert some Text to current cursor position of a TextBox through JQuery and JavaScript

Process

  1. Find the Current Cursor Position
  2. Get the Text to be Copied
  3. Set the Text Over there
  4. Update the Cursor position

Here I have 2 TextBoxes and a Button. I have to Click on a certain position on a textbox and then click on the button to paste the text from the other textbox to the the position of the previous textbox.

Main issue here is that getting the current cursor position where we will paste the text.

//Textbox on which to be pasted
<input type="text" id="txtOnWhichToBePasted" />

//Textbox from where to be pasted
<input type="text" id="txtFromWhichToBePasted" />


//Button on which click the text to be pasted
<input type="button" id="btnInsert" value="Insert"/>


<script type="text/javascript">

$(document).ready(function () {
    $('#btnInsert').bind('click', function () {
            var TextToBePasted = $('#txtFromWhichToBePasted').value;
            var ControlOnWhichToBePasted = $('#txtOnWhichToBePasted');

            //Paste the Text
            PasteTag(ControlOnWhichToBePasted, TextToBePasted);
        });
    });

//Function Pasting The Text
function PasteTag(ControlOnWhichToBePasted,TextToBePasted) {
    //Get the position where to be paste

    var CaretPos = 0;
    // IE Support
    if (document.selection) {

        ControlOnWhichToBePasted.focus();
        var Sel = document.selection.createRange();

        Sel.moveStart('character', -ctrl.value.length);

        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ControlOnWhichToBePasted.selectionStart || ControlOnWhichToBePasted.selectionStart == '0')
        CaretPos = ControlOnWhichToBePasted.selectionStart;

    //paste the text
    var WholeString = ControlOnWhichToBePasted.value;
    var txt1 = WholeString.substring(0, CaretPos);
    var txt2 = WholeString.substring(CaretPos, WholeString.length);
    WholeString = txt1 + TextToBePasted + txt2;
    var CaretPos = txt1.length + TextToBePasted.length;
    ControlOnWhichToBePasted.value = WholeString;

    //update The cursor position 
    setCaretPosition(ControlOnWhichToBePasted, CaretPos);
}

function setCaretPosition(ControlOnWhichToBePasted, pos) {

    if (ControlOnWhichToBePasted.setSelectionRange) {
        ControlOnWhichToBePasted.focus();
        ControlOnWhichToBePasted.setSelectionRange(pos, pos);
    }
    else if (ControlOnWhichToBePasted.createTextRange) {
        var range = ControlOnWhichToBePasted.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

</script>

Why is "using namespace std;" considered bad practice?

Yes, the namespace is important. Once in my project, I needed to import one var declaration into my source code, but when compiling it, it conflicted with another third-party library.

At the end, I had to work around around it by some other means and make the code less clear.

Script to get the HTTP status code of a list of urls?

Curl has a specific option, --write-out, for this:

$ curl -o /dev/null --silent --head --write-out '%{http_code}\n' <url>
200
  • -o /dev/null throws away the usual output
  • --silent throws away the progress meter
  • --head makes a HEAD HTTP request, instead of GET
  • --write-out '%{http_code}\n' prints the required status code

To wrap this up in a complete Bash script:

#!/bin/bash
while read LINE; do
  curl -o /dev/null --silent --head --write-out "%{http_code} $LINE\n" "$LINE"
done < url-list.txt

(Eagle-eyed readers will notice that this uses one curl process per URL, which imposes fork and TCP connection penalties. It would be faster if multiple URLs were combined in a single curl, but there isn't space to write out the monsterous repetition of options that curl requires to do this.)

afxwin.h file is missing in VC++ Express Edition

I see the question is about Express Edition, but this topic is easy to pop up in Google Search, and doesn't have a solution for other editions.

So. If you run into this problem with any VS Edition except Express, you can rerun installation and include MFC files.

Check if program is running with bash shell script?

PROCESS="process name shown in ps -ef"
START_OR_STOP=1        # 0 = start | 1 = stop

MAX=30
COUNT=0

until [ $COUNT -gt $MAX ] ; do
        echo -ne "."
        PROCESS_NUM=$(ps -ef | grep "$PROCESS" | grep -v `basename $0` | grep -v "grep" | wc -l)
        if [ $PROCESS_NUM -gt 0 ]; then
            #runs
            RET=1
        else
            #stopped
            RET=0
        fi

        if [ $RET -eq $START_OR_STOP ]; then
            sleep 5 #wait...
        else
            if [ $START_OR_STOP -eq 1 ]; then
                    echo -ne " stopped"
            else
                    echo -ne " started"
            fi
            echo
            exit 0
        fi
        let COUNT=COUNT+1
done

if [ $START_OR_STOP -eq 1 ]; then
    echo -ne " !!$PROCESS failed to stop!! "
else
    echo -ne " !!$PROCESS failed to start!! "
fi
echo
exit 1

Get environment variable value in Dockerfile

add -e key for passing environment variables to container. example:

$ MYSQLHOSTIP=$(sudo docker inspect -format="{{ .NetworkSettings.IPAddress }}" $MYSQL_CONRAINER_ID)
$ sudo docker run -e DBIP=$MYSQLHOSTIP -i -t myimage /bin/bash

root@87f235949a13:/# echo $DBIP
172.17.0.2

Float to String format specifier

In C#, float is an alias for System.Single (a bit like intis an alias for System.Int32).

PHP - include a php file and also send query parameters

You can use $GLOBALS to solve this issue as well.

$myvar = "Hey";

include ("test.php");


echo $GLOBALS["myvar"];