Programs & Examples On #Bioinformatics

Use this tag only for programming-related questions related to Bioinformatics. Other questions do not belong here. Please refer to the tag wiki for more information.

Remove part of string after "."

We can pretend they are filenames and remove extensions:

tools::file_path_sans_ext(a)
# [1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155"

WinError 2 The system cannot find the file specified (Python)

Popen expect a list of strings for non-shell calls and a string for shell calls.

Call subprocess.Popen with shell=True:

process = subprocess.Popen(command, stdout=tempFile, shell=True)

Hopefully this solves your issue.

This issue is listed here: https://bugs.python.org/issue17023

AngularJS passing data to $http.get request

For sending get request with parameter i use

  $http.get('urlPartOne\\'+parameter+'\\urlPartTwo')

By this you can use your own url string

jQuery using append with effects

In my case:

$("div.which-stores-content").append("<div class="content">Content</div>);
$("div.content").hide().show("fast");

you can adjust your css with visibility:hidden -> visibility:visible and adjust the transitions etc transition: visibility 1.0s;

Input button target="_blank" isn't causing the link to load in a new window/tab

<form target="_blank">
    <button class="btn btn-primary" formaction="http://www.google.com">Google</button>
</form>

JavaScript Regular Expression Email Validation

Email validation is easy to get wrong. I would therefore recommend that you use Verimail.js.

Why?

  • Syntax validation (according to RFC 822).
  • IANA TLD validation
  • Spelling suggestion for the most common TLDs and email domains
  • Deny temporary email account domains such as mailinator.com
  • jQuery plugin support

Another great thing with Verimail.js is that it has spelling suggestion for the most common email domains and registered TLDs. This can lower your bounce rate drastically for users that misspell common domain names such as gmail.com, hotmail.com, aol.com, aso..

Example:

How to use it?

The easiest way is to download and include verimail.jquery.js on your page. After that, hookup Verimail by running the following function on the input-box that needs the validation:

$("input#email-address").verimail({
    messageElement: "p#status-message"
});

The message element is an optional element that displays a message such as "Invalid email.." or "Did you mean [email protected]?". If you have a form and only want to proceed if the email is verified, you can use the function getVerimailStatus as shown below:

if($("input#email-address").getVerimailStatus() < 0){
    // Invalid email
}else{
    // Valid email
}

The getVerimailStatus-function returns an integer code according to the object Comfirm.AlphaMail.Verimail.Status. As shown above, if the status is a negative integer value, then the validation should be treated as a failure. But if the value is greater or equal to 0, then the validation should be treated as a success.

Submit HTML form, perform javascript function (alert then redirect)

<form action="javascript:completeAndRedirect();">
    <input type="text" id="Edit1" 
    style="width:280; height:50; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:22px">
</form>

Changing action to point at your function would solve the problem, in a different way.

The 'packages' element is not declared

You can also find a copy of the nuspec.xsd here as it seems to no longer be available:

https://gist.github.com/sharwell/6131243

How to send an email with Gmail as provider using Python?

You down with OOP?

#!/usr/bin/env python


import smtplib

class Gmail(object):
    def __init__(self, email, password):
        self.email = email
        self.password = password
        self.server = 'smtp.gmail.com'
        self.port = 587
        session = smtplib.SMTP(self.server, self.port)        
        session.ehlo()
        session.starttls()
        session.ehlo
        session.login(self.email, self.password)
        self.session = session

    def send_message(self, subject, body):
        ''' This must be removed '''
        headers = [
            "From: " + self.email,
            "Subject: " + subject,
            "To: " + self.email,
            "MIME-Version: 1.0",
           "Content-Type: text/html"]
        headers = "\r\n".join(headers)
        self.session.sendmail(
            self.email,
            self.email,
            headers + "\r\n\r\n" + body)


gm = Gmail('Your Email', 'Password')

gm.send_message('Subject', 'Message')

Finding the handle to a WPF window

Well, instead of passing Application.Current.MainWindow, just pass a reference to whichever window it is you want: new WindowInteropHelper(this).Handle and so on.

How to get a Docker container's IP address from the host

If you want to quickly see all Docker IP addresses, or without typing the instance name, you can hack the docker ps command adding this to your ~/.bashrc file:

function docker-ips() {
    docker ps | while read line; do
        if `echo $line | grep -q 'CONTAINER ID'`; then
            echo -e "IP ADDRESS\t$line"
        else
            CID=$(echo $line | awk '{print $1}');
            IP=$(docker inspect -f "{{ .NetworkSettings.IPAddress }}" $CID);
            printf "${IP}\t${line}\n"
        fi
    done;
}

This comes from a proposal by Andrew Johnstone at the Docker GitHub: https://github.com/docker/docker/issues/8786

What does "dereferencing" a pointer mean?

A pointer is a "reference" to a value.. much like a library call number is a reference to a book. "Dereferencing" the call number is physically going through and retrieving that book.

int a=4 ;
int *pA = &a ;
printf( "The REFERENCE/call number for the variable `a` is %p\n", pA ) ;

// The * causes pA to DEREFERENCE...  `a` via "callnumber" `pA`.
printf( "%d\n", *pA ) ; // prints 4.. 

If the book isn't there, the librarian starts shouting, shuts the library down, and a couple of people are set to investigate the cause of a person going to find a book that isn't there.

How to use if - else structure in a batch file?

Here's my code Example for if..else..if
which do the following

Prompt user for Process Name

If the process name is invalid
Then it's write to user

Error : The Processor above doesn't seem to be exist 

if the process name is services
Then it's write to user

Error : You can't kill the Processor above 

if the process name is valid and not services
Then it's write to user

the process has been killed via taskill

so i called it Process killer.bat
Here's my Code:

@echo off

:Start
Rem preparing the batch  
cls
Title Processor Killer
Color 0B
Echo Type Processor name to kill It (Without ".exe")
set /p ProcessorTokill=%=%  

:tasklist
tasklist|find /i "%ProcessorTokill%.exe">nul & if errorlevel 1 (
REM check if the process name is invalid 
Cls 
Title %ProcessorTokill% Not Found
Color 0A
echo %ProcessorTokill%
echo Error : The Processor above doesn't seem to be exist    

) else if %ProcessorTokill%==services (
REM check if the process name is services and doesn't kill it
Cls 
Color 0c
Title Permission denied 
echo "%ProcessorTokill%.exe"
echo Error : You can't kill the Processor above 

) else (
REM if the process name is valid and not services
Cls 
Title %ProcessorTokill% Found
Color 0e
echo %ProcessorTokill% Found
ping localhost -n 2 -w 1000>nul
echo Killing %ProcessorTokill% ...
taskkill /f /im %ProcessorTokill%.exe /t>nul
echo %ProcessorTokill% Killed...
)

pause>nul



REM If else if Template
REM if thing1 (
REM Command here 2 ! 
REM ) else if thing2 (
REM command here 2 !
REM ) else (
REM command here 3 !
REM )

Using PHP with Socket.io

I was looking for a really simple way to get PHP to send a socket.io message to clients.

This doesn't require any additional PHP libraries - it just uses sockets.

Instead of trying to connect to the websocket interface like so many other solutions, just connect to the node.js server and use .on('data') to receive the message.

Then, socket.io can forward it along to clients.

Detect a connection from your PHP server in Node.js like this:

//You might have something like this - just included to show object setup
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

server.on("connection", function(s) {
    //If connection is from our server (localhost)
    if(s.remoteAddress == "::ffff:127.0.0.1") {
        s.on('data', function(buf) {
            var js = JSON.parse(buf);
            io.emit(js.msg,js.data); //Send the msg to socket.io clients
        });
    }
});

Here's the incredibly simple php code - I wrapped it in a function - you may come up with something better.

Note that 8080 is the port to my Node.js server - you may want to change.

function sio_message($message, $data) {
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $result = socket_connect($socket, '127.0.0.1', 8080);
    if(!$result) {
        die('cannot connect '.socket_strerror(socket_last_error()).PHP_EOL);
    }
    $bytes = socket_write($socket, json_encode(Array("msg" => $message, "data" => $data)));
    socket_close($socket);
}

You can use it like this:

sio_message("chat message","Hello from PHP!");

You can also send arrays which are converted to json and passed along to clients.

sio_message("DataUpdate",Array("Data1" => "something", "Data2" => "something else"));

This is a useful way to "trust" that your clients are getting legitimate messages from the server.

You can also have PHP pass along database updates without having hundreds of clients query the database.

I wish I'd found this sooner - hope this helps!

What does `ValueError: cannot reindex from a duplicate axis` mean?

In my case, this error popped up not because of duplicate values, but because I attempted to join a shorter Series to a Dataframe: both had the same index, but the Series had fewer rows (missing the top few). The following worked for my purposes:

df.head()
                          SensA
date                           
2018-04-03 13:54:47.274   -0.45
2018-04-03 13:55:46.484   -0.42
2018-04-03 13:56:56.235   -0.37
2018-04-03 13:57:57.207   -0.34
2018-04-03 13:59:34.636   -0.33

series.head()
date
2018-04-03 14:09:36.577    62.2
2018-04-03 14:10:28.138    63.5
2018-04-03 14:11:27.400    63.1
2018-04-03 14:12:39.623    62.6
2018-04-03 14:13:27.310    62.5
Name: SensA_rrT, dtype: float64

df = series.to_frame().combine_first(df)

df.head(10)
                          SensA  SensA_rrT
date                           
2018-04-03 13:54:47.274   -0.45        NaN
2018-04-03 13:55:46.484   -0.42        NaN
2018-04-03 13:56:56.235   -0.37        NaN
2018-04-03 13:57:57.207   -0.34        NaN
2018-04-03 13:59:34.636   -0.33        NaN
2018-04-03 14:00:34.565   -0.33        NaN
2018-04-03 14:01:19.994   -0.37        NaN
2018-04-03 14:02:29.636   -0.34        NaN
2018-04-03 14:03:31.599   -0.32        NaN
2018-04-03 14:04:30.779   -0.33        NaN
2018-04-03 14:05:31.733   -0.35        NaN
2018-04-03 14:06:33.290   -0.38        NaN
2018-04-03 14:07:37.459   -0.39        NaN
2018-04-03 14:08:36.361   -0.36        NaN
2018-04-03 14:09:36.577   -0.37       62.2

Bin size in Matplotlib (Histogram)

Actually, it's quite easy: instead of the number of bins you can give a list with the bin boundaries. They can be unequally distributed, too:

plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100])

If you just want them equally distributed, you can simply use range:

plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth))

Added to original answer

The above line works for data filled with integers only. As macrocosme points out, for floats you can use:

import numpy as np
plt.hist(data, bins=np.arange(min(data), max(data) + binwidth, binwidth))

How to send JSON instead of a query string with $.ajax?

No, the dataType option is for parsing the received data.

To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

Squash my last X commits together using Git

If you are on a remote branch(called feature-branch) cloned from a Golden Repository(golden_repo_name), then here's the technique to squash your commits into one:

  1. Checkout the golden repo

    git checkout golden_repo_name
    
  2. Create a new branch from it(golden repo) as follows

    git checkout -b dev-branch
    
  3. Squash merge with your local branch that you have already

    git merge --squash feature-branch
    
  4. Commit your changes (this will be the only commit that goes in dev-branch)

    git commit -m "My feature complete"
    
  5. Push the branch to your local repository

    git push origin dev-branch
    

HtmlSpecialChars equivalent in Javascript?

Here's a function to escape HTML:

function escapeHtml(str)
{
    var map =
    {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return str.replace(/[&<>"']/g, function(m) {return map[m];});
}

And to decode:

function decodeHtml(str)
{
    var map =
    {
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&quot;': '"',
        '&#039;': "'"
    };
    return str.replace(/&amp;|&lt;|&gt;|&quot;|&#039;/g, function(m) {return map[m];});
}

angular.min.js.map not found, what is it exactly?

Monkey is right, according to the link given by monkey

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location.

I am not sure if it is angular's fault that no map files were generated. But you can turn off source map files by unchecking this option in chrome console setting

enter image description here

How do I run a bat file in the background from another bat file?

Actually, the following works fine for me and creates new windows:

test.cmd:

@echo off
start test2.cmd
start test3.cmd
echo Foo
pause

test2.cmd

@echo off
echo Test 2
pause
exit

test3.cmd

@echo off
echo Test 3
pause
exit

Combine that with parameters to start, such as /min, as Moshe pointed out if you don't want the new windows to spawn in front of you.

How to convert DateTime to a number with a precision greater than days in T-SQL?

You can use T-SQL to convert the date before it gets to your .NET program. This often is simpler if you don't need to do additional date conversion in your .NET program.

DECLARE @Date DATETIME = Getdate()
DECLARE @DateInt INT = CONVERT(VARCHAR(30), @Date, 112)
DECLARE @TimeInt INT = REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
DECLARE @DateTimeInt BIGINT = CONVERT(VARCHAR(30), @Date, 112) + REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
SELECT @Date as Date, @DateInt DateInt, @TimeInt TimeInt, @DateTimeInt DateTimeInt

Date                    DateInt     TimeInt     DateTimeInt
------------------------- ----------- ----------- --------------------
2013-01-07 15:08:21.680 20130107    150821      20130107150821

How to check if a variable is an integer in JavaScript?

The simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following:

function isInteger(x) { return (x^0) === x; } 

The following solution would also work, although not as elegant as the one above:

function isInteger(x) { return Math.round(x) === x; }

Note that Math.ceil() or Math.floor() could be used equally well (instead of Math.round()) in the above implementation.

Or alternatively:

function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); }

One fairly common incorrect solution is the following:

function isInteger(x) { return parseInt(x, 10) === x; }

While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe:

> String(1000000000000000000000)
'1e+21'

> parseInt(1000000000000000000000, 10)
1

> parseInt(1000000000000000000000, 10) === 1000000000000000000000
false

SVG fill color transparency / alpha?

Use attribute fill-opacity in your element of SVG.

Default value is 1, minimum is 0, in step use decimal values EX: 0.5 = 50% of alpha. Note: It is necessary to define fill color to apply fill-opacity.

See my example.

References.

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

Resize an Array while keeping current elements in Java?

Here are a couple of ways to do it.


Method 1: System.arraycopy():

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.

Object[] originalArray = new Object[5];   
Object[] largerArray = new Object[10];
System.arraycopy(originalArray, 0, largerArray, 0, originalArray.length);

Method 2: Arrays.copyOf():

Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.

Object[] originalArray = new Object[5];   
Object[] largerArray = Arrays.copyOf(originalArray, 10);

Note that this method usually uses System.arraycopy() behind the scenes.


Method 3: ArrayList:

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)

ArrayList functions similarly to an array, except it automatically expands when you add more elements than it can contain. It's backed by an array, and uses Arrays.copyOf.

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

// This will add the element, resizing the ArrayList if necessary.
list.add(new Object());

How to Join to first row

Tried the cross, works nicely, but takes slightly longer. Adjusted line columns to have max and added group which kept speed and dropped the extra record.

Here's the adjusted query:

SELECT Orders.OrderNumber, max(LineItems.Quantity), max(LineItems.Description)
FROM Orders
    INNER JOIN LineItems 
    ON Orders.OrderID = LineItems.OrderID
Group by Orders.OrderNumber

Custom Input[type="submit"] style not working with jquerymobile button

jQuery Mobile >= 1.4

Create a custom class, e.g. .custom-btn. Note that to override jQM styles without using !important, CSS hierarchy should be respected. .ui-btn.custom-class or .ui-input-btn.custom-class.

.ui-input-btn.custom-btn {
   border:1px solid red;
   text-decoration:none;
   font-family:helvetica;
   color:red;
   background:url(img.png) repeat-x;
}

Add a data-wrapper-class to input. The custom class will be added to input wrapping div.

<input type="button" data-wrapper-class="custom-btn">

Demo


jQuery Mobile <= 1.3

Input button is wrapped by a DIV with class ui-btn. You need to select that div and the input[type="submit"]. Using !important is essential to override Jquery Mobile styles.

Demo

div.ui-btn, input[type="submit"] {
 border:1px solid red !important;
 text-decoration:none !important;
 font-family:helvetica !important;
 color:red !important;
 background:url(../images/btn_hover.png) repeat-x !important;
}

Taking multiple inputs from user in python

In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way. I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ','.

items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')]

print items

RE error: illegal byte sequence on Mac OS X

A sample command that exhibits the symptom: sed 's/./@/' <<<$'\xfc' fails, because byte 0xfc is not a valid UTF-8 char.
Note that, by contrast, GNU sed (Linux, but also installable on macOS) simply passes the invalid byte through, without reporting an error.

Using the formerly accepted answer is an option if you don't mind losing support for your true locale (if you're on a US system and you never need to deal with foreign characters, that may be fine.)

However, the same effect can be had ad-hoc for a single command only:

LC_ALL=C sed -i "" 's|"iphoneos-cross","llvm-gcc:-O3|"iphoneos-cross","clang:-Os|g' Configure

Note: What matters is an effective LC_CTYPE setting of C, so LC_CTYPE=C sed ... would normally also work, but if LC_ALL happens to be set (to something other than C), it will override individual LC_*-category variables such as LC_CTYPE. Thus, the most robust approach is to set LC_ALL.

However, (effectively) setting LC_CTYPE to C treats strings as if each byte were its own character (no interpretation based on encoding rules is performed), with no regard for the - multibyte-on-demand - UTF-8 encoding that OS X employs by default, where foreign characters have multibyte encodings.

In a nutshell: setting LC_CTYPE to C causes the shell and utilities to only recognize basic English letters as letters (the ones in the 7-bit ASCII range), so that foreign chars. will not be treated as letters, causing, for instance, upper-/lowercase conversions to fail.

Again, this may be fine if you needn't match multibyte-encoded characters such as é, and simply want to pass such characters through.

If this is insufficient and/or you want to understand the cause of the original error (including determining what input bytes caused the problem) and perform encoding conversions on demand, read on below.


The problem is that the input file's encoding does not match the shell's.
More specifically, the input file contains characters encoded in a way that is not valid in UTF-8 (as @Klas Lindbäck stated in a comment) - that's what the sed error message is trying to say by invalid byte sequence.

Most likely, your input file uses a single-byte 8-bit encoding such as ISO-8859-1, frequently used to encode "Western European" languages.

Example:

The accented letter à has Unicode codepoint 0xE0 (224) - the same as in ISO-8859-1. However, due to the nature of UTF-8 encoding, this single codepoint is represented as 2 bytes - 0xC3 0xA0, whereas trying to pass the single byte 0xE0 is invalid under UTF-8.

Here's a demonstration of the problem using the string voilà encoded as ISO-8859-1, with the à represented as one byte (via an ANSI-C-quoted bash string ($'...') that uses \x{e0} to create the byte):

Note that the sed command is effectively a no-op that simply passes the input through, but we need it to provoke the error:

  # -> 'illegal byte sequence': byte 0xE0 is not a valid char.
sed 's/.*/&/' <<<$'voil\x{e0}'

To simply ignore the problem, the above LCTYPE=C approach can be used:

  # No error, bytes are passed through ('á' will render as '?', though).
LC_CTYPE=C sed 's/.*/&/' <<<$'voil\x{e0}'

If you want to determine which parts of the input cause the problem, try the following:

  # Convert bytes in the 8-bit range (high bit set) to hex. representation.
  # -> 'voil\x{e0}'
iconv -f ASCII --byte-subst='\x{%02x}' <<<$'voil\x{e0}'

The output will show you all bytes that have the high bit set (bytes that exceed the 7-bit ASCII range) in hexadecimal form. (Note, however, that that also includes correctly encoded UTF-8 multibyte sequences - a more sophisticated approach would be needed to specifically identify invalid-in-UTF-8 bytes.)


Performing encoding conversions on demand:

Standard utility iconv can be used to convert to (-t) and/or from (-f) encodings; iconv -l lists all supported ones.

Examples:

Convert FROM ISO-8859-1 to the encoding in effect in the shell (based on LC_CTYPE, which is UTF-8-based by default), building on the above example:

  # Converts to UTF-8; output renders correctly as 'voilà'
sed 's/.*/&/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

Note that this conversion allows you to properly match foreign characters:

  # Correctly matches 'à' and replaces it with 'ü': -> 'voilü'
sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

To convert the input BACK to ISO-8859-1 after processing, simply pipe the result to another iconv command:

sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')" | iconv -t ISO-8859-1

Change key pair for ec2 instance

Run this command after you download your AWS pem.

ssh-keygen -f YOURKEY.pem -y

Then dump the output into authorized_keys.

Or copy pem file to your AWS instance and execute following commands

chmod 600 YOURKEY.pem

and then

ssh-keygen -f YOURKEY.pem -y >> ~/.ssh/authorized_keys

I can't install intel HAXM

For HP Ultra book with windows 7 enabling hyper-v through bios worked for intel haxm problem.

For enabling hyper-v:-

F10-> Bios advanced setting-> device configurations->enable Hyper-V then install.

It will work.

Regular Expression Validation For Indian Phone Number and Mobile number

You can use regular expression like this.

/^[(]+\ ++\d{2}[)]+[^0]+\d{9}/

How to delete specific rows and columns from a matrix in a smarter way?

You can also remove rows and columns by feeding a vector of logical boolean values to the matrix. This handles the situation where you have multiple non-contiguous rows or non-contiguous columns that need to be deleted.

# TRUE = Keep a row/column
# FALSE = Delete a row/column
#
# FALSE for rows 4, 5, and 6
# Row:            1     2     3     4      5      6      7     8     9     10
rows_to_keep <- c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
    
# FALSE for columns 7, 8, and 9
# Column:         1     2     3     4     5     6     7      8      9      10
cols_to_keep <- c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE) 

To remove just the rows:

t1 <- t1[rows_to_keep,]

To remove just the columns:

t1 <- t1[,cols_to_keep]

To remove both the rows and columns:

t1 <- t1[rows_to_keep, cols_to_keep]

This coding technique is useful if you don't know in advance what rows or columns you need to remove. The rows_to_keep and cols_to_keep vectors can be calculated as appropriate by your code.

Convert a file path to Uri in Android

Below code works fine before 18 API :-

public String getRealPathFromURI(Uri contentUri) {

        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery( contentUri,
                        proj, // Which columns to return
                        null,       // WHERE clause; which rows to return (all rows)
                        null,       // WHERE clause selection arguments (none)
                        null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
}

below code use on kitkat :-

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

see below link for more info:-

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

xls to csv converter

I would use xlrd - it's faster, cross platform and works directly with the file. One thing to note - it doesn't work on xlsx files - so you'd have to save your Excel file as xls. Edit: As of version 0.8.0, xlrd reads both XLS and XLSX files.

import xlrd
import csv

def csv_from_excel():
    wb = xlrd.open_workbook('your_workbook.xls')
    sh = wb.sheet_by_name('Sheet1')
    your_csv_file = open('your_csv_file.csv', 'wb')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in xrange(sh.nrows):
        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

Use the following extensions and just pass the action like:

_frmx.PerformSafely(() => _frmx.Show());
_frmx.PerformSafely(() => _frmx.Location = new Point(x,y));

Extension class:

public static class CrossThreadExtensions
{
    public static void PerformSafely(this Control target, Action action)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action);
        }
        else
        {
            action();
        }
    }

    public static void PerformSafely<T1>(this Control target, Action<T1> action,T1 parameter)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action, parameter);
        }
        else
        {
            action(parameter);
        }
    }

    public static void PerformSafely<T1,T2>(this Control target, Action<T1,T2> action, T1 p1,T2 p2)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action, p1,p2);
        }
        else
        {
            action(p1,p2);
        }
    }
}

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

I made some minor modification to you code and tested it with a spring project that I have and it works, The logic will only work with POST if I use GET it throws an error with invalid request. Also in your ajax call I commented out commit(true), the browser debugger flagged and error that it is not defined. Just modify the url to fit your Spring project architecture.

 $.ajax({ 
                    url: "/addDepartment", 
                    method: 'POST', 
                    dataType: 'json', 
                    data: "{\"message\":\"abc\",\"success\":true}",
                    contentType: 'application/json',
                    mimeType: 'application/json',
                    success: function(data) { 
                        alert(data.success + " " + data.message);
                        //commit(true);
                    },
                    error:function(data,status,er) { 
                        alert("error: "+data+" status: "+status+" er:"+er);
                    }
                });



@RequestMapping(value="/addDepartment", method=RequestMethod.POST)
  public AjaxResponse addDepartment(@RequestBody final AjaxResponse  departmentDTO)
  {
    System.out.println("addDepartment: >>>>>>> "+departmentDTO);
    AjaxResponse response=new AjaxResponse();
    response.setSuccess(departmentDTO.isSuccess());
    response.setMessage(departmentDTO.getMessage());
    return response;
  }

How to enumerate an enum

I think you can use

Enum.GetNames(Suit)

Create array of regex matches

        Set<String> keyList = new HashSet();
        Pattern regex = Pattern.compile("#\\{(.*?)\\}");
        Matcher matcher = regex.matcher("Content goes here");
        while(matcher.find()) {
            keyList.add(matcher.group(1)); 
        }
        return keyList;

Synchronizing a local Git repository with a remote one

git fetch --prune

-p, --prune
After fetching, remove any remote-tracking branches which no longer exist on the remote. prune options

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

WSDL vs REST Pros and Cons

for enterprise systems in which your system is confined within your corporations, its easier and proper to use soap because you are almost in control of clients. it's easier since there a variety of tools which creates classes (proxies) and looks like you are doing your regular OOP which matches your java or .net environment (in which most corporates use).

I would use REST for internet facing applications for exposing interfaces (like twitter api) since clients can be using javascripts or html or others in which typing is not strict. REST being more liberal makes more sense.

Also for internet facing clients (world wide web), its easier to parse json or xml coming out of a rest interface rather than a purely xml coming from a soap interface. it's hard to use proxies on javascript and javascript does not naturally support objects. If you are using REST with javascript, you would just usually parse the json string and you're off. internet facing interfaces are usually very simple (so most of the time its simple parsing) and does not usually demand consistency that is why REST is adequate enough.

For enterprise applications I don't think REST is adequate because transactions, security, strict typing, schemas play a very important in enterprise applications development that is why SOAP is more suited for them.

My conclusion is that SOAP is for Enterprise systems, REST is for the Internet or WWW. You can use it interchangeably but you may find yourself having a difficult time eventually not using the correct tool for the job.

sorry for my bad english.

Is there a way to collapse all code blocks in Eclipse?

The question is a bit old, but let me add a different approach. In addition to the above hot-key approaches, there are default preference settings that can be toggled.

As of Eclipse Galileo (and definitely in my Eclipse Version: Indigo Service Release 2 Build id: 20120216-1857) language specific preferences can open up new files to edit which are already collapsed or expanded.

Here is a link to Eclipse Galileo online docs showing the feature for C/C++: http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.cdt.doc.user/reference/cdt_u_c_editor_folding.htm .

In my Eclipse Indigo I can open the Folding Preferences window via : menu/ Window/ Preferences/ Java/ Editor/ Folding and set all options on so I can open files by default that are completely collapsed.

How does Python return multiple values from a function?

Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple values and then returns it from the function??

I'm just adding a name and print the result that returns from the function. the type of result is 'tuple'.

  class FigureOut:
   first_name = None
   last_name = None
   def setName(self, name):
      fullname = name.split()
      self.first_name = fullname[0]
      self.last_name = fullname[1]
      self.special_name = fullname[2]
   def getName(self):
      return self.first_name, self.last_name, self.special_name

f = FigureOut()
f.setName("Allen Solly Jun")
name = f.getName()
print type(name)


I don't know whether you have heard about 'first class function'. Python is the language that has 'first class function'

I hope my answer could help you. Happy coding.

If statements for Checkboxes

I'm making an assumption that you mean not checked. I don't have a C# compiler handy but:

if (checkbox1.Checked && !checkbox2.Checked)
{

}
else if (!checkbox1.Checked && checkbox2.Checked)
{

}

Basic example for sharing text or image with UIActivityViewController in Swift

I found this to work flawlessly if you want to share whole screen.

@IBAction func shareButton(_ sender: Any) {

    let bounds = UIScreen.main.bounds
    UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
    self.view.drawHierarchy(in: bounds, afterScreenUpdates: false)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    self.present(activityViewController, animated: true, completion: nil)
}

Add CSS to <head> with JavaScript?

Here's a function that will dynamically create a CSS rule in all major browsers. createCssRule takes a selector (e.g. "p.purpleText"), a rule (e.g. "color: purple;") and optionally a Document (the current document is used by default):

var addRule;

if (typeof document.styleSheets != "undefined" && document.styleSheets) {
    addRule = function(selector, rule) {
        var styleSheets = document.styleSheets, styleSheet;
        if (styleSheets && styleSheets.length) {
            styleSheet = styleSheets[styleSheets.length - 1];
            if (styleSheet.addRule) {
                styleSheet.addRule(selector, rule)
            } else if (typeof styleSheet.cssText == "string") {
                styleSheet.cssText = selector + " {" + rule + "}";
            } else if (styleSheet.insertRule && styleSheet.cssRules) {
                styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
            }
        }
    }
} else {
    addRule = function(selector, rule, el, doc) {
        el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
    };
}

function createCssRule(selector, rule, doc) {
    doc = doc || document;
    var head = doc.getElementsByTagName("head")[0];
    if (head && addRule) {
        var styleEl = doc.createElement("style");
        styleEl.type = "text/css";
        styleEl.media = "screen";
        head.appendChild(styleEl);
        addRule(selector, rule, styleEl, doc);
        styleEl = null;
    }
};

createCssRule("body", "background-color: purple;");

Is it better in C++ to pass by value or pass by constant reference?

Sounds like you got your answer. Passing by value is expensive, but gives you a copy to work with if you need it.

How can I make an svg scale with its parent container?

Another simple way is

transform: scale(1.5);

How to 'grep' a continuous stream?

I think that your problem is that grep uses some output buffering. Try

tail -f file | stdbuf -o0 grep my_pattern

it will set output buffering mode of grep to unbuffered.

React won't load local images

I too would like to add to the answers from @Hawkeye Parker and @Kiszuriwalilibori:

As was noted from the docs here, it is typically best to import the images as needed.

However, I needed many files to be dynamically loaded, which led me to put the images in the public folder (also stated in the README), because of this recommendation below from the documentation:

Normally we recommend importing stylesheets, images, and fonts from JavaScript. The public folder is useful as a workaround for a number of less common cases:

  • You need a file with a specific name in the build output, such as manifest.webmanifest.
  • You have thousands of images and need to dynamically reference their paths.
  • You want to include a small script like pace.js outside of the bundled code.
  • Some library may be incompatible with Webpack and you have no other option but to include it as a tag.

Hope that helps someone else! Leave me a comment if I need to clear any of that up.

Clearing content of text file using php

 $fp = fopen("$address",'w+');
 if(!$fp)
    echo 'not Open';
        //-----------------------------------
 while(!feof($fp))
     {
        fputs($fp,' ',999);                    
     } 

 fclose($fp);

Backup/Restore a dockerized PostgreSQL database

Backup Database

generate sql:

  • docker exec -t your-db-container pg_dumpall -c -U your-db-user > dump_$(date +%Y-%m-%d_%H_%M_%S).sql

to reduce the size of the sql you can generate a compress:

  • docker exec -t your-db-container pg_dumpall -c -U your-db-user | gzip > ./dump_$(date +"%Y-%m-%d_%H_%M_%S").gz

Restore Database

  • cat your_dump.sql | docker exec -i your-db-container psql -U your-db-user -d your-db-name

to restore a compressed sql:

  • gunzip < your_dump.sql.gz | docker exec -i your-db-container psql -U your-db-user -d your-db-name

PD: this is a compilation of what worked for me, and what I got from here and elsewhere. I am beginning to make contributions, any feedback will be appreciated.

Opening port 80 EC2 Amazon web services

  1. Check what security group you are using for your instance. See value of Security Groups column in row of your instance. It's important - I changed rules for default group, but my instance was under quickstart-1 group when I had similar issue.
  2. Go to Security Groups tab, go to Inbound tab, select HTTP in Create a new rule combo-box, leave 0.0.0.0/0 in source field and click Add Rule, then Apply rule changes.

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

How to put a component inside another component in Angular2?

I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent] from decorator.

import {myDirective} from './myDirective';

remote rejected master -> master (pre-receive hook declined)

I got the same error and looked into activity. Where I found that I had two package lock files which was causing the error.

Convert dictionary values into array

Store it in a list. It is easier;

List<Foo> arr = new List<Foo>(dict.Values);

Of course if you specifically want it in an array;

Foo[] arr = (new List<Foo>(dict.Values)).ToArray();

SyntaxError: Unexpected token function - Async Await Nodejs

node v6.6.0

If you just use in development. You can do this:

npm i babel-cli babel-plugin-transform-async-to-generator babel-polyfill --save-dev

the package.json would be like this:

"devDependencies": {
   "babel-cli": "^6.18.0",
   "babel-plugin-transform-async-to-generator": "^6.16.0",
   "babel-polyfill": "^6.20.0"
}

create .babelrc file and write this:

{
  "plugins": ["transform-async-to-generator"]
}

and then, run your async/await script like this:

./node_modules/.bin/babel-node script.js

How can I read a whole file into a string variable

If you just want the content as string, then the simple solution is to use the ReadFile function from the io/ioutil package. This function returns a slice of bytes which you can easily convert to a string.

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    b, err := ioutil.ReadFile("file.txt") // just pass the file name
    if err != nil {
        fmt.Print(err)
    }

    fmt.Println(b) // print the content as 'bytes'

    str := string(b) // convert content to a 'string'

    fmt.Println(str) // print the content as a 'string'
}

Split Div Into 2 Columns Using CSS

I know this post is old, but if any of you still looking for a simpler solution.

#container .left,
#container .right {
    display: inline-block;
}

#container .left {
    width: 20%;
    float: left;
}
#container .right {
    width: 80%;
    float: right;
}

Python String and Integer concatenation

I did something else. I wanted to replace a word, in lists off lists, that contained phrases. I wanted to replace that sttring / word with a new word that will be a join between string and number, and that number / digit will indicate the position of the phrase / sublist / lists of lists.

That is, I replaced a string with a string and an incremental number that follow it.

    myoldlist_1=[[' myoldword'],[''],['tttt myoldword'],['jjjj ddmyoldwordd']]
        No_ofposition=[]
        mynewlist_2=[]
        for i in xrange(0,4,1):
            mynewlist_2.append([x.replace('myoldword', "%s" % i+"_mynewword") for x in myoldlist_1[i]])
            if len(mynewlist_2[i])>0:
                No_ofposition.append(i)
mynewlist_2
No_ofposition

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

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

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

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

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

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

   if (d) {
      struct dirent *p;

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

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

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

          if (buf) {
             struct stat statbuf;

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

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

   return r;
}

Alert handling in Selenium WebDriver (selenium 2) with Java

You could try

 try{
        if(webDriver.switchTo().alert() != null){
           Alert alert = webDriver.switchTo().alert();
           alert.getText();
           //etc.
        }
    }catch(Exception e){}

If that doesn't work, you could try looping through all the window handles and see if the alert exists. I'm not sure if the alert opens as a new window using selenium.

for(String s: webDriver.getWindowHandles()){
 //see if alert exists here.
}

Dynamic tabs with user-click chosen components

I'm not cool enough for comments. I fixed the plunker from the accepted answer to work for rc2. Nothing fancy, links to the CDN were just broken is all.

'@angular/core': {
  main: 'bundles/core.umd.js',
  defaultExtension: 'js'
},
'@angular/compiler': {
  main: 'bundles/compiler.umd.js',
  defaultExtension: 'js'
},
'@angular/common': {
  main: 'bundles/common.umd.js',
  defaultExtension: 'js'
},
'@angular/platform-browser-dynamic': {
  main: 'bundles/platform-browser-dynamic.umd.js',
  defaultExtension: 'js'
},
'@angular/platform-browser': {
  main: 'bundles/platform-browser.umd.js',
  defaultExtension: 'js'
},

https://plnkr.co/edit/kVJvI1vkzrLZJeRFsZuv?p=preview

Obtain form input fields using jQuery?

Sometimes I find getting one at a time is more useful. For that, there's this:

var input_name = "firstname";
var input = $("#form_id :input[name='"+input_name+"']"); 

EC2 instance types's exact network performance?

FWIW CloudFront supports streaming as well. Might be better than plain streaming from instances.

BarCode Image Generator in Java

iText is a great Java PDF library. They also have an API for creating barcodes. You don't need to be creating a PDF to use it.

This page has the details on creating barcodes. Here is an example from that site:

BarcodeEAN codeEAN = new BarcodeEAN();
codeEAN.setCodeType(codeEAN.EAN13);
codeEAN.setCode("9780201615883");
Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);

The biggest thing you will need to determine is what type of barcode you need. There are many different barcode formats and iText does support a lot of them. You will need to know what format you need before you can determine if this API will work for you.

removing html element styles via javascript

In JavaScript:

document.getElementById("id").style.display = null;

In jQuery:

$("#id").css('display',null);

Chrome Extension: Make it run every page load

This code should do it:

manifest.json

   {
      "name": "Alert 'hello world!' on page opening",
      "version": "1.0",
      "manifest_version": 2,
      "content_scripts": [
        {
          "matches": [
            "<all_urls>"
          ],
          "js": ["content.js"]
        }
      ]
    }

content.js

alert('Hello world!')

re.sub erroring with "Expected string or bytes-like object"

The simplest solution is to apply Python str function to the column you are trying to loop through.

If you are using pandas, this can be implemented as:

dataframe['column_name']=dataframe['column_name'].apply(str)

How do you get centered content using Twitter Bootstrap?

<div class="container">
  <div class="col-md-12 centered">
    <div class="row">
      <div class="col-md-1"></div>
       <div class="col-md-10">
           label
       </div>
      <div class="col-md-1"></div>
    </div>
  </div>
</div>

Do not use container-fluid in the main.

How do I restart a program based on user input?

You can do this simply with a function. For example:

def script():
    # program code here...
    restart = raw_input("Would you like to restart this program?")
    if restart == "yes" or restart == "y":
        script()
    if restart == "n" or restart == "no":
        print "Script terminating. Goodbye."
script()

Of course you can change a lot of things here. What is said, what the script will accept as a valid input, the variable and function names. You can simply nest the entire program in a user-defined function (Of course you must give everything inside an extra indent) and have it restart at anytime using this line of code: myfunctionname(). More on this here.

How to get local server host and port in Spring Boot?

An easy workaround, at least to get the running port, is to add the parameter javax.servlet.HttpServletRequest in the signature of one of the controller's methods. Once you have the HttpServletRequest instance is straightforward to get the baseUrl with this: request.getRequestURL().toString()

Have a look at this code:

@PostMapping(value = "/registration" , produces = "application/json")
public StringResponse register(@RequestBody RequestUserDTO userDTO, 
    HttpServletRequest request) {
request.getRequestURL().toString();
//value: http://localhost:8080/registration
------
return "";
}

MySQL LIKE IN()?

Just a little tip:

I prefer to use the variant RLIKE (exactly the same command as REGEXP) as it sounds more like natural language, and is shorter; well, just 1 char.

The "R" prefix is for Reg. Exp., of course.

How to save a dictionary to a file?

file_name = open("data.json", "w")
json.dump(test_response, file_name)
file_name.close()

or use context manager, which is better:

with open("data.json", "w") as file_name:
    json.dump(test_response, file_name)

How to select option in drop down protractorjs e2e tests

If none of the answer's above worked for you, try this

works with async/await too

For selecting options by text

let textOption = "option2"
await element(by.whichever('YOUR_DROPDOWN_SELECTOR'))
  .getWebElement()
  .findElement(by.xpath(`.//option[text()="${textOption}"]`))
  .click();

or by number

let optionNumber = 2
await element(by.whichever('YOUR_DROPDOWN_SELECTOR'))
  .getWebElement()
  .findElement(by.xpath(`.//option[${optionNumber}]`))
  .click();

Of course you may need to modify the xpath of child options

Don't ask me why, but this is the only way I could automate my dropdowns, when I lost hope already

python 2 instead of python 3 as the (temporary) default python?

You don't want a "temporary default Python"

You want the 2.7 scripts to start with

/usr/bin/env python2.7

And you want the 3.2 scripts to begin with

/usr/bin/env python3.2

There's really no use for a "default" Python. And the idea of a "temporary default" is just a road to absolute confusion.

Remember.

Explicit is better than Implicit.

Running PowerShell as another user, and launching a script

Here's also nice way to achieve this via UI.

0) Right click on PowerShell icon when on task bar

1) Shift + right click on Windows PowerShell

2) "Run as different user"

Pic

Express.js req.body undefined

For anyone who none of the answers above have worked for I had to enable cors between my front-end and express.

You can do this either by:

  1. Downloading and turning on a CORS extension for your browser, such as:

    https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

    for Chrome,

or by

  1. Adding the lines

    var cors=require('cors');
    
    app.use(cors());
    

to your express app.js page. (After npm install cors)

How to convert Javascript datetime to C# datetime?

You can also send Js time to C# with Moment.js Library :

JavaScript : var dateString = moment(new Date()).format('LLLL')

C# : DateTime.Parse(dateString);

Open a local HTML file using window.open in Chrome

This worked for me fine:

File 1:

    <html>
    <head></head>
    <body>
        <a href="#" onclick="window.open('file:///D:/Examples/file2.html'); return false">CLICK ME</a>
    </body>
    <footer></footer>
    </html>

File 2:

    <html>
        ...
    </html>

This method works regardless of whether or not the 2 files are in the same directory, BUT both files must be local.

For obvious security reasons, if File 1 is located on a remote server you absolutely cannot open a file on some client's host computer and trying to do so will open a blank target.

Source file not compiled Dev C++

I was having this issue and fixed it by going to: C:\Dev-Cpp\libexec\gcc\mingw32\3.4.2 , then deleting collect2.exe

Why can I ping a server but not connect via SSH?

ping (ICMP protocol) and ssh are two different protocols.

  1. It could be that ssh service is not running or not installed

  2. firewall restriction (local to server like iptables or even sshd config lock down ) or (external firewall that protects incomming traffic to network hosting 111.111.111.111)

First check is to see if ssh port is up

nc -v -w 1 111.111.111.111 -z 22

if it succeeds then ssh should communicate if not then it will never work until restriction is lifted or ssh is started

Convert Unicode data to int in python

int(limit) returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).

Do this instead:

limit = int(limit)

Or when definiting limit:

if 'limit' in user_data :
    limit = int(user_data['limit'])

How can I make robocopy silent in the command line except for progress?

There's no need to redirect to a file and delete it later. Try:

Robocopy src dest > null 

How to add minutes to current time in swift

You can use Calendar's method

func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?

to add any Calendar.Component to any Date. You can create a Date extension to add x minutes to your UIDatePicker's date:

Xcode 8 and Xcode 9 • Swift 3.0 and Swift 4.0

extension Date {
    func adding(minutes: Int) -> Date {
        return Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
    }
}

Then you can just use the extension method to add minutes to the sender (UIDatePicker):

let section1 = sender.date.adding(minutes: 5)
let section2 = sender.date.adding(minutes: 10)

Playground testing:

Date().adding(minutes: 10)  //  "Jun 14, 2016, 5:31 PM"

Sorting a DropDownList? - C#, ASP.NET

If your data is coming to you as a System.Data.DataTable, call the DataTable's .Select() method, passing in "" for the filterExpression and "COLUMN1 ASC" (or whatever column you want to sort by) for the sort. This will return an array of DataRow objects, sorted as specified, that you can then iterate through and dump into the DropDownList.

Automatically open Chrome developer tools when new tab/new window is opened

Under the Chrome DevTools settings you enable:

Under Network -> Preserve Log Under DevTools -> Auto-open DevTools for popups

String.Replace ignoring case

You could use a Regex and perform a case insensitive replace:

class Program
{
    static void Main()
    {
        string input = "hello WoRlD";
        string result = 
           Regex.Replace(input, "world", "csharp", RegexOptions.IgnoreCase);
        Console.WriteLine(result); // prints "hello csharp"
    }
}

how to access the command line for xampp on windows

Run PHP file from command Promp.

Please set Environment Variable as per below mention steps.

  1. Right Click on MY Computer Icon and Click on Properties or Go to "Control Panel\System and Security\System".
  2. Select "Advanced System Settings" and select "Advance" Tab
  3. Now Select "Environment Variable" option and select "Path" from "System Variables" and click on "Edit" button
  4. Now set path where php.exe file is available - For example if XAMPP install in to C: drive then Path is "C:\xampp\php"
  5. After set path Click Ok and Apply.

Now open Command prompt where your source file are available and run command "php test.php"

Center Oversized Image in Div

This is an old Q, but a modern solution without flexbox or position absolute works like this.

margin-left: 50%;
transform: translateX(-50%);

_x000D_
_x000D_
.outer {_x000D_
  border: 1px solid green;_x000D_
  margin: 20px auto;_x000D_
  width: 20%;_x000D_
  padding: 10px 0;_x000D_
  /*   overflow: hidden; */_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  width: 150%;_x000D_
  background-color: gold;_x000D_
  /* Set left edge of inner element to 50% of the parent element */_x000D_
  margin-left: 50%; _x000D_
  /* Move to the left by 50% of own width */_x000D_
  transform: translateX(-50%); _x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos exercitationem error nemo amet cum quia eaque alias nihil, similique laboriosam enim expedita fugit neque earum et esse ad, dolores sapiente sit cumque vero odit! Ullam corrupti iure eum similique magnam voluptatum ipsam. Maxime ad cumque ut atque suscipit enim quidem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi impedit esse modi, porro quibusdam voluptate dolores molestias, sit dolorum veritatis laudantium rem, labore et nobis ratione. Ipsum, aliquid totam repellendus non fugiat id magni voluptate, doloribus tenetur illo mollitia. Voluptatum.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

So why does it work?
At first glance it seems that we shift 50% to the right and then 50% to the left again. That would result in zero shift, so what?
But the 50% are not the same, because context is important. If you use relative units, a margin will be calculated as percentage of the width of the parent element, while the transform will be 50% relative to the same element.

We have this situation before we add the CSS

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       +-----------------------------------------------------------+
       | Element E                                                 |
       +-----------------------------------------------------------+
       |                                           |
       +-------------------------------------------+

With the added style margin-left: 50% we have

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       |                     +-----------------------------------------------------------+
       |                     | Element E                                                 |
       |                     +-----------------------------------------------------------+
       |                     |                     |
       +---------------------|---------------------+
       |========= a ========>|

       a is 50% width of P

And the transform: translateX(-50%) shifts back to the left

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
+-----------------------------------------------------------+
| Element E                 |                               |
+-----------------------------------------------------------+
|<============ b ===========|                      |
       |                    |                      |
       +--------------------|----------------------+
       |========= a =======>|

       a is 50% width of P
       b is 50% width of E

Unfortunately this does only work for horizontal centering as the margin percentage calculation is always relative to the width. I.e. not only margin-left and margin-right, but also margin-top and margin-bottom are calculated with respect to width.

Browser compatibility should be no problem: https://caniuse.com/#feat=transforms2d

PHP call Class method / function

Create object for the class and call, if you want to call it from other pages.

$obj = new Functions();

$var = $obj->filter($_GET['params']);

Or inside the same class instances [ methods ], try this.

$var = $this->filter($_GET['params']);

How to sort findAll Doctrine's method?

As @Lighthart as shown, yes it's possible, although it adds significant fat to the controller and isn't DRY.

You should really define your own query in the entity repository, it's simple and best practice.

use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository
{
    public function findAll()
    {
        return $this->findBy(array(), array('username' => 'ASC'));
    }
}

Then you must tell your entity to look for queries in the repository:

/**
 * @ORM\Table(name="User")
 * @ORM\Entity(repositoryClass="Acme\UserBundle\Entity\Repository\UserRepository")
 */
class User
{
    ...
}

Finally, in your controller:

$this->getDoctrine()->getRepository('AcmeBundle:User')->findAll();

WPF Check box: Check changed handling

That you can handle the checked and unchecked events seperately doesn't mean you have to. If you don't want to follow the MVVM pattern you can simply attach the same handler to both events and you have your change signal:

<CheckBox Checked="CheckBoxChanged" Unchecked="CheckBoxChanged"/>

and in Code-behind;

private void CheckBoxChanged(object sender, RoutedEventArgs e)
{
  MessageBox.Show("Eureka, it changed!");
}

Please note that WPF strongly encourages the MVVM pattern utilizing INotifyPropertyChanged and/or DependencyProperties for a reason. This is something that works, not something I would like to encourage as good programming habit.

jQuery add required to input fields

I have found that the following implementations are effective:

$('#freeform_first_name').removeAttr('required');

$('#freeform_first_name').attr('required', 'required');

These commands (attr, removeAttr, prop) behave differently depending on the version of JQuery you are using. Please reference the documentation here: https://api.jquery.com/attr/

How do the post increment (i++) and pre increment (++i) operators work in Java?

I believe you are executing all these statements differently
executing together will result => 38 ,29

int a=5,i;
i=++a + ++a + a++;
//this means i= 6+7+7=20 and when this result is stored in i,
//then last *a* will be incremented <br>
i=a++ + ++a + ++a;
//this means i= 5+7+8=20 (this could be complicated, 
//but its working like this),<br>
a=++a + ++a + a++;
//as a is 6+7+7=20 (this is incremented like this)

What's the difference between ViewData and ViewBag?

Can I recommend to you to not use either?

If you want to "send" data to your screen, send a strongly typed object (A.K.A. ViewModel) because it's easier to test.

If you bind to some sort of "Model" and have random "viewbag" or "viewdata" items then it makes automated testing very difficult.

If you are using these consider how you might be able to restructure and just use ViewModels.

Find an item in List by LINQ?

This will help you in getting the first or default value in your Linq List search

var results = _List.Where(item => item == search).FirstOrDefault();

This search will find the first or default value it will return.

Calling Java from Python

I'm just beginning to use JPype 0.5.4.2 (july 2011) and it looks like it's working nicely...
I'm on Xubuntu 10.04

Download data url file

For anyone having issues in IE:

Please upvote the answer here by Yetti: saving canvas locally in IE

dataURItoBlob = function(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var array = [];
    for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {type: 'image/png'});
}

var blob = dataURItoBlob(uri);
window.navigator.msSaveOrOpenBlob(blob, "my-image.png");

Printing without newline (print 'a',) prints a space, how to remove?

as simple as that

def printSleeping():
     sleep = "I'm sleeping"
     v = ""
     for i in sleep:
         v += i
         system('cls')
         print v
         time.sleep(0.02)

Display fullscreen mode on Tkinter

Yeah mate i was trying to do the same in windows, and what helped me was a bit of lambdas with the root.state() method.

root = Tk()
root.bind('<Escape>', lambda event: root.state('normal'))
root.bind('<F11>', lambda event: root.state('zoomed'))

Has Facebook sharer.php changed to no longer accept detailed parameters?

Facebook no longer supports custom parameters in sharer.php

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

Use dialog/feeds instead of sharer.php

https://www.facebook.com/dialog/feed?
  app_id=145634995501895
  &display=popup&caption=An%20example%20caption 
  &link=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fdialogs%2F
  &redirect_uri=https://developers.facebook.com/tools/explorer

Official answer from fb team

Installing Python 3 on RHEL

For those working on AWS EC2 RHEL 7.5, (use sudo) enable required repos

yum-config-manager --enable rhui-REGION-rhel-server-optional
yum-config-manager --enable rhui-REGION-rhel-server-rhscl

Install Python 3.6

yum install rh-python36

Install other dependencies

yum install rh-python36-numpy  rh-python36-scipy  rh-python36-python-tools  rh-python36-python-six

Difference between hamiltonian path and euler path

They are related but are neither dependent nor mutually exclusive. If a graph has an Eurler cycle, it may or may not also have a Hamiltonian cyle and vice versa.


Euler cycles visit every edge in the graph exactly once. If there are vertices in the graph with more than two edges, then by definition, the cycle will pass through those vertices more than once. As a result, vertices can be repeated but edges cannot.

Hamiltonian cycles visit every vertex in the graph exactly once (similar to the travelling salesman problem). As a result, neither edges nor vertices can be repeated.

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

... right now it happens only to the website I'm testing. I can't post it here because it's confidential.

Then I guess it is one of the sites which is incompatible with TLS1.2. The openssl as used in 12.04 does not use TLS1.2 on the client side while with 14.04 it uses TLS1.2 which might explain the difference. To work around try to explicitly use --secure-protocol=TLSv1. If this does not help check if you can access the site with openssl s_client -connect ... (probably not) and with openssl s_client -tls1 -no_tls1_1, -no_tls1_2 ....

Please note that it might be other causes, but this one is the most probable and without getting access to the site everything is just speculation anyway.

The assumed problem in detail: Usually clients use the most compatible handshake to access a server. This is the SSLv23 handshake which is compatible to older SSL versions but announces the best TLS version the client supports, so that the server can pick the best version. In this case wget would announce TLS1.2. But there are some broken servers which never assumed that one day there would be something like TLS1.2 and which refuse the handshake if the client announces support for this hot new version (from 2008!) instead of just responding with the best version the server supports. To access these broken servers the client has to lie and claim that it only supports TLS1.0 as the best version.

Is Ubuntu 14.04 or wget 1.15 not compatible with TLS 1.0 websites? Do I need to install/download any library/software to enable this connection?

The problem is the server, not the client. Most browsers work around these broken servers by retrying with a lower version. Most other applications fail permanently if the first connection attempt fails, i.e. they don't downgrade by itself and one has to enforce another version by some application specific settings.

How to get the last five characters of a string using Substring() in C#?

string input = "OneTwoThree";
(if input.length >5)
{
string str=input.substring(input.length-5,5);
}

What is the purpose of Looper and how to use it?

What is Looper?

FROM DOCS

Looper

Looper Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

  • A Looper is a message handling loop:
  • An important character of Looper is that it's associated with the thread within which the Looper is created
  • The Looper class maintains a MessageQueue, which contains a list messages. An important character of Looper is that it's associated with the thread within which the Looper is created.
  • The Looper is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler is called a handler because someone could not invent a better name
  • Android Looper is a Java class within the Android user interface that together with the Handler class to process UI events such as button clicks, screen redraws and orientation switches.

How it works?

enter image description here

Creating Looper

A thread gets a Looper and MessageQueue by calling Looper.prepare() after its running. Looper.prepare() identifies the calling thread, creates a Looper and MessageQueue object and associate the thread

SAMPLE CODE

class MyLooperThread extends Thread {

      public Handler mHandler; 

      public void run() { 

          // preparing a looper on current thread  
          Looper.prepare();

          mHandler = new Handler() { 
              public void handleMessage(Message msg) { 
                 // process incoming messages here
                 // this will run in non-ui/background thread
              } 
          }; 

          Looper.loop();
      } 
  }

For more information check below post

git: diff between file in local repo and origin

For that I wrote a bash script:

#set -x 
branchname=`git branch | grep -F '*' |  awk '{print $2}'`
echo $branchname
git fetch origin ${branchname}
for file in `git status | awk '{if ($1 == "modified:") print $2;}'`
do
echo "PLEASE CHECK OUT GIT DIFF FOR "$file 
git difftool  FETCH_HEAD $file ;
done

In the above script, I fetch the remote main branch (not necessary its master branch ANY branch) to FETCH_HEAD, then make a list of my modified file only and compare modified files to git difftool.

There are many difftool supported by git, I configured Meld Diff Viewer for good GUI comparison.
From the above script, I have prior knowledge what changes done by other teams in same file, before I follow git stages untrack-->staged-->commit which help me to avoid unnecessary resolve merge conflict with remote team or make new local branch and compare and merge on the main branch.

A div with auto resize when changing window width\height

Use vh attributes. It means viewport height and is a percentage. So height: 90vh would mean 90% of the viewport height. This works in most modern browsers.

Eg.

div {
  height: 90vh;
}

You can forego the rest of your silly 100% stuff on the body.

If you have a header you can also do some fun things like take it into account by using the calc function in CSS.

Eg.

div {
  height: calc(100vh - 50px);
}

This will give you 100% of the viewport height, minus 50px for your header.

How to set text size of textview dynamically for different screens

You should use the resource folders such as

values-ldpi
values-mdpi
values-hdpi

And write the text size in 'dimensions.xml' file for each range.

And in the java code you can set the text size with

textView.setTextSize(getResources().getDimension(R.dimen.textsize));

Sample dimensions.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="textsize">15sp</dimen>
</resources>

ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)

The solution that worked for me is:

  1. Downloaded mysql-8.0.22-winx64.zip file
  2. Extracted the zip file
  3. Moved the extracted folder to C:/Program Files
  4. Opened cmd.exe as admin
  5. Navigated to the directory cd C:\Program Files\mysql-8.0.22\mysql-8.0.22-winx64\bin
  6. mysqld -install (Service successfully installed)
  7. mysqld --initialize (no prompt)
  8. Opened services.msc
  9. Found MySQL
  10. Right-click and start

Let me know if it helps!

css - position div to bottom of containing div

.outside {
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Needs to be

.outside {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Absolute positioning looks for the nearest relatively positioned parent within the DOM, if one isn't defined it will use the body.

How to close the command line window after running a batch file?

If you only need to execute only one command all by itself and no wait needed, you should try "cmd /c", this works for me!

cmd /c start iexplore "http://your/url.html"

cmd /c means executing a command and then exit.

You can learn the functions of your switches by typing in your command prompt

anycmd /?

changing the language of error message in required field in html5 contact form

Do it using JS. Grab the class of the error message, and change it's content for whereever it appears.

var myClasses = document.getElementsByClassName("wpcf7-not-valid-tip");

for (var i = 0; i < myClasses.length; i++) {
    myClasses[i].innerHTML = "Bitte füllen Sie das Pflichtfeld aus.";
}

How to get the number of columns from a JDBC ResultSet?

After establising the connection and executing the query try this:

 ResultSet resultSet;
 int columnCount = resultSet.getMetaData().getColumnCount();
 System.out.println("column count : "+columnCount);

How to get the cell value by column name not by index in GridView in asp.net

//get the value of a gridview
public string getUpdatingGridviewValue(GridView gridviewEntry, string fieldEntry)
    {//start getGridviewValue
        //scan gridview for cell value
            string result = Convert.ToString(functionsOther.getCurrentTime()); 
            for(int i = 0; i < gridviewEntry.HeaderRow.Cells.Count; i++)
                {//start i for
                    if(gridviewEntry.HeaderRow.Cells[i].Text == fieldEntry)
                        {//start check field match
                            result = gridviewEntry.Rows[rowUpdateIndex].Cells[i].Text;
                            break;
                        }//end check field match
                }//end i for
        //return
            return result;
    }//end getGridviewValue

nginx missing sites-available directory

I tried sudo apt install nginx-full. You will get all the required packages.

What does /p mean in set /p?

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Two ways I've used it... first:

SET /P variable=

When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.

And second:

SET /P variable=<%temp%\filename.txt

Will set variable to contents (the first line) of the txt file. This method won't work unless the /P is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.

Are one-line 'if'/'for'-statements good Python style?

an example of a language feature that isn't just removing line breaks, although still not convinced this is clearer than the more verbose version

a = 1 if x > 15 else 2

How to change 1 char in the string?

Strings are immutable, meaning you can't change a character. Instead, you create new strings.

What you are asking can be done several ways. The most appropriate solution will vary depending on the nature of the changes you are making to the original string. Are you changing only one character? Do you need to insert/delete/append?

Here are a couple ways to create a new string from an existing string, but having a different first character:

str = 'M' + str.Remove(0, 1);

str = 'M' + str.Substring(1);

Above, the new string is assigned to the original variable, str.

I'd like to add that the answers from others demonstrating StringBuilder are also very appropriate. I wouldn't instantiate a StringBuilder to change one character, but if many changes are needed StringBuilder is a better solution than my examples which create a temporary new string in the process. StringBuilder provides a mutable object that allows many changes and/or append operations. Once you are done making changes, an immutable string is created from the StringBuilder with the .ToString() method. You can continue to make changes on the StringBuilder object and create more new strings, as needed, using .ToString().

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

This expression 12-4-2005 is a calculated int and the value is -1997. You should do like this instead '2005-04-12' with the ' before and after.

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

I've found a post here on Stackoverflow and implemented your design:

http://jsfiddle.net/bKsad/25/

Here's the original post: https://stackoverflow.com/a/5768262/1368423

Is that what you're looking for?

HTML:

<div class="container-fluid wrapper">

  <div class="row-fluid columns content"> 

    <div class="span2 article-tree">
      navigation column
    </div>

    <div class="span10 content-area">
      content column 
    </div>
  </div>

  <div class="footer">
     footer content
  </div>
</div>

CSS:

html, body {
    height: 100%;
}
.container-fluid {
    margin: 0 auto;
    height: 100%;
    padding: 20px 0;

    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.columns {
    background-color: #C9E6FF;
    height: 100%;   
}

.content-area, .article-tree{
    background: #bada55;
    overflow:auto;
    height: 100%;
}

.footer {
    background: red;
    height: 20px;
}

How to assign execute permission to a .sh file in windows to be executed in linux

The ZIP file format does allow to store the permission bits, but Windows programs normally ignore it. The zip utility on Cygwin however does preserve the x bit, just like it does on Linux. If you do not want to use Cygwin, you can take a source code and tweak it so that all *.sh files get the executable bit set. Or write a script like explained here

Selecting Values from Oracle Table Variable / Array?

You might need a GLOBAL TEMPORARY TABLE.

In Oracle these are created once and then when invoked the data is private to your session.

Oracle Documentation Link

Try something like this...

CREATE GLOBAL TEMPORARY TABLE temp_number
   ( number_column   NUMBER( 10, 0 )
   )
   ON COMMIT DELETE ROWS;

BEGIN 
   INSERT INTO temp_number
      ( number_column )
      ( select distinct sgbstdn_pidm 
          from sgbstdn 
         where sgbstdn_majr_code_1 = 'HS04' 
           and sgbstdn_program_1 = 'HSCOMPH' 
      ); 

    FOR pidms_rec IN ( SELECT number_column FROM temp_number )
    LOOP 
        -- Do something here
        NULL; 
    END LOOP; 
END; 
/

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

I have solved above problem Applying below steps

enter image description here

And after you made thses changes, do following changes in your web.config

 <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v12.0;AttachDbFilename=|DataDirectory|\aspnet-Real-Time-Commenting-20170927122714.mdf;Initial Catalog=aspnet-Real-Time-Commenting-20170927122714;Integrated Security=true" providerName="System.Data.SqlClient" />

javascript code to check special characters

You could also do it this way.

specialRegex = /[^A-Z a-z0-9]/ specialRegex.test('test!') // evaluates to true Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character

scale Image in an UIButton to AspectFit?

I have a method that does it for me. The method takes UIButton and makes the image aspect fit.

-(void)makeImageAspectFitForButton:(UIButton*)button{
    button.imageView.contentMode=UIViewContentModeScaleAspectFit;
    button.contentHorizontalAlignment=UIControlContentHorizontalAlignmentFill;
    button.contentVerticalAlignment=UIControlContentVerticalAlignmentFill;
}

Alternate background colors for list items

You can by hardcoding the sequence, like so:

li, li + li + li, li + li + li + li + li {
  background-color: black;
}

li + li, li + li + li + li {
  background-color: white;
}

TypeScript: casting HTMLElement

You always can hack type system using:

var script = (<HTMLScriptElement[]><any>document.getElementsByName(id))[0];

Importing a CSV file into a sqlite3 database table using Python

in the interest of simplicity, you could use the sqlite3 command line tool from the Makefile of your project.

%.sql3: %.csv
    rm -f $@
    sqlite3 $@ -echo -cmd ".mode csv" ".import $< $*"
%.dump: %.sql3
    sqlite3 $< "select * from $*"

make test.sql3 then creates the sqlite database from an existing test.csv file, with a single table "test". you can then make test.dump to verify the contents.

How to convert a date String to a Date or Calendar object?

In brief:

DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
try {
  Date date = formatter.parse("01/29/02");
} catch (ParseException e) {
  e.printStackTrace();
}

See SimpleDateFormat javadoc for more.

And to turn it into a Calendar, do:

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

live output from subprocess command

Based on all the above I suggest a slightly modified version (python3):

  • while loop calling readline (The iter solution suggested seemed to block forever for me - Python 3, Windows 7)
  • structered so handling of read data does not need to be duplicated after poll returns not-None
  • stderr piped into stdout so both output outputs are read
  • Added code to get exit value of cmd.

Code:

import subprocess
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT, universal_newlines=True)
while True:
    rd = proc.stdout.readline()
    print(rd, end='')  # and whatever you want to do...
    if not rd:  # EOF
        returncode = proc.poll()
        if returncode is not None:
            break
        time.sleep(0.1)  # cmd closed stdout, but not exited yet

# You may want to check on ReturnCode here

error: Libtool library used but 'LIBTOOL' is undefined

For people using Tiny Core Linux, you also need to install libtool-dev as it has the *.m4 files needed for libtoolize.

What does Include() do in LINQ?

Let's say for instance you want to get a list of all your customers:

var customers = context.Customers.ToList();

And let's assume that each Customer object has a reference to its set of Orders, and that each Order has references to LineItems which may also reference a Product.

As you can see, selecting a top-level object with many related entities could result in a query that needs to pull in data from many sources. As a performance measure, Include() allows you to indicate which related entities should be read from the database as part of the same query.

Using the same example, this might bring in all of the related order headers, but none of the other records:

var customersWithOrderDetail = context.Customers.Include("Orders").ToList();

As a final point since you asked for SQL, the first statement without Include() could generate a simple statement:

SELECT * FROM Customers;

The final statement which calls Include("Orders") may look like this:

SELECT *
FROM Customers JOIN Orders ON Customers.Id = Orders.CustomerId;

How to loop through a dataset in powershell?

The parser is having trouble concatenating your string. Try this:

write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])

Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string:

write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"

How to get JS variable to retain value after page refresh?

In addition to cookies and localStorage, there's at least one other place you can store "semi-persistent" client data: window.name. Any string value you assign to window.name will stay there until the window is closed.

To test it out, just open the console and type window.name = "foo", then refresh the page and type window.name; it should respond with foo.

This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage for whatever reason (legacy clients), it may be an option to consider.

window.name has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.

Note that window.name can only store strings, but with the wide availability of JSON, this shouldn't be much of an issue even for complex data.

Get width in pixels from element with style set with %?

yourItem.style['cssProperty']

this way you can call the property string dynamically

Cannot find name 'require' after upgrading to Angular4

Will work in Angular 7+


I was facing the same issue, I was adding

"types": ["node"]

to tsconfig.json of root folder.

There was one more tsconfig.app.json under src folder and I got solved this by adding

"types": ["node"]

to tsconfig.app.json file under compilerOptions

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["node"]  ----------------------< added node to the array
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.

Try

    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

Maven: How to include jars, which are not available in reps into a J2EE project?

Create a repository folder under your project. Let's take

${project.basedir}/src/main/resources/repo

Then, install your custom jar to this repo:

mvn install:install-file -Dfile=[FILE_PATH] \
-DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] \ 
-Dpackaging=jar -DlocalRepositoryPath=[REPO_DIR]

Lastly, add the following repo and dependency definitions to the projects pom.xml:

<repositories>
    <repository>
        <id>project-repo</id>
        <url>file://${project.basedir}/src/main/resources/repo</url>
    </repository>
</repositories>

<dependencies>    
    <dependency>
        <groupId>[GROUP]</groupId>
        <artifactId>[ARTIFACT]</artifactId>
        <version>[VERS]</version>
    </dependency>
</dependencies>

HTML5 Local storage vs. Session storage

  • sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores)

  • localStorage does the same thing, but persists even when the browser is closed and reopened.

I took this from Web Storage API

Select option padding not working in chrome

I have a little trick for your problem. But for that you must use javascript. If you detected that the browser is Chrome insert "dummy" options between every options. Give a new class for those "dummy" options and make them disabled. The height of "dummy" options you can define with font-size property.

CSS:

option.dummy-option-for-chrome {
  font-size:2px;
  color:transparent;
}

Script:

function prepareHtml5Selects() {

  var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
  if(!is_chrome) return;

  $('select > option').each(function() {
    $('<option class="dummy-option-for-chrome" disabled></option>')
     .insertBefore($(this));
  });
  $('<option class="dummy-option-for-chrome" disabled></option>')
    .insertAfter($('select > option:last-child'));
}

HTTP 400 (bad request) for logical error, not malformed request syntax

Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.

Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)

Thank You, Vish

Android video streaming example

I was facing the same problem and found a solution to get the code to work.

The code given in the android-Sdk/samples/android-?/ApiDemos works fine. Copy paste each folder in the android project and then in the MediaPlayerDemo_Video.java put the path of the video you want to stream in the path variable. It is left blank in the code.

The following video stream worked for me: http://www.pocketjourney.com/downloads/pj/video/famous.3gp

I know that RTSP protocol is to be used for streaming, but mediaplayer class supports http for streaming as mentioned in the code.

I googled for the format of the video and found that the video if converted to mp4 or 3gp using Quicktime Pro works fine for streaming.

I tested the final apk on android 2.1. The application dosent work on emulators well. Try it on devices.

I hope this helps..

Jackson JSON: get node name from json-tree

fields() and fieldNames() both were not working for me. And I had to spend quite sometime to find a way to iterate over the keys. There are two ways by which it can be done.

One is by converting it into a map (takes up more space):

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> result = mapper.convertValue(jsonNode, Map.class);
for (String key : result.keySet())
{
    if(key.equals(foo))
    {
        //code here
    }
}

Another, by using a String iterator:

Iterator<String> it = jsonNode.getFieldNames();
while (it.hasNext())
{
    String key = it.next();
    if (key.equals(foo))
    {
         //code here
    }
}

How create a new deep copy (clone) of a List<T>?

If the Array class meets your needs, you could also use the List.ToArray method, which copies elements to a new array.

Reference: http://msdn.microsoft.com/en-us/library/x303t819(v=vs.110).aspx

Accessing SQL Database in Excel-VBA

@firedrawndagger: to list field names/column headers iterate through the recordset Fields collection and insert the name:

Dim myRS as ADODB.Recordset
Dim fld as Field
Dim strFieldName as String 

For Each fld in myRS.Fields
    Activesheet.Selection = fld.Name
    [Some code that moves to next column]
Next

How to embed a video into GitHub README.md?

I combine Alexandre Jasmin and Gab Le Roux answers like this:

[![Demo CountPages alpha](https://share.gifyoutube.com/KzB6Gb.gif)](https://www.youtube.com/watch?v=ek1j272iAmc)

Demo:

Demo CountPages alpha

You can see this demo on github.

I used gifyoutube here, but I recommend using a local gif converter (like ffmpeg, see how) instead of an online one.

To record your screen to gif directly, you may want to check ScreenToGif.

Java associative-array

Java equivalent of Perl's hash

HashMap<Integer, HashMap<String, String>> hash;

How to create a JavaScript callback for knowing when an image is loaded?

If you are using React.js, you could do this:

render() {

// ...

<img 
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}

src={item.src} key={item.key}
ref={item.key} />

// ... }

Where:

  • - onLoad (...) now will called with something like this: { src: "https://......png", key:"1" } you can use this as "key" to know which images is loaded correctly and which not.
  • - onError(...) it is the same but for errors.
  • - the object "item" is something like this { key:"..", src:".."} you can use to store the images' URL and key in order to use in a list of images.

  • MySQL Daemon Failed to Start - centos 6

     /etc/init.d/mysqld stop
    
     mysqld_safe --skip-grant-tables & mysql_upgrade
    
     /etc/init.d/mysqld stop
    
     /etc/init.d/mysqld start
    

    java SSL and cert keystore

    SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.

    The specific keys you have to set are below:

    javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.

    javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).

    javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes, /, in place of backslashes, \.

    If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):

    1. $JAVA_HOME/lib/security/jssecacerts
    2. $JAVA_HOME/lib/security/cacerts

    javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by javax.net.ssl.trustStore.

    javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.

    javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.

    Convert array of strings into a string in Java

    Use Apache commons StringUtils.join(). It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation. Each elements string representation is then joined into one string with a separator in between if one is specified:

    String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
    System.out.println(joinedString);
    

    Produces:

    a-b-1
    

    Configure hibernate to connect to database via JNDI Datasource

    Tomcat-7 JNDI configuration:

    Steps:

    1. Open the server.xml in the tomcat-dir/conf
    2. Add below <Resource> tag with your DB details inside <GlobalNamingResources>
    <Resource name="jdbc/mydb"
              global="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/test"
              username="root"
              password=""
              maxActive="10"
              maxIdle="10"
              minIdle="5"
              maxWait="10000"/>
    
    1. Save the server.xml file
    2. Open the context.xml in the tomcat-dir/conf
    3. Add the below <ResourceLink> inside the <Context> tag.
    <ResourceLink name="jdbc/mydb" 
                  global="jdbc/mydb"
                  auth="Container"
                  type="javax.sql.DataSource" />
    
    1. Save the context.xml
    2. Open the hibernate-cfg.xml file and add and remove below properties.
    Adding:
    -------
    <property name="connection.datasource">java:comp/env/jdbc/mydb</property>
    
    Removing:
    --------
    <!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
    <!--<property name="connection.username">root</property> -->
    <!--<property name="connection.password"></property> -->
    
    1. Save the file and put latest .WAR file in tomcat.
    2. Restart the tomcat. the DB connection will work.

    Android Fragment onClick button Method

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View view = inflater.inflate(R.layout.writeqrcode_main, container, false);
        // Inflate the layout for this fragment
    
        txt_name = (TextView) view.findViewById(R.id.name);
        txt_usranme = (TextView) view.findViewById(R.id.surname);
        txt_number = (TextView) view.findViewById(R.id.number);
        txt_province = (TextView) view.findViewById(R.id.province);
        txt_write = (EditText) view.findViewById(R.id.editText_write);
        txt_show1 = (Button) view.findViewById(R.id.buttonShow1);
    
        txt_show1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("Onclick","Onclick");
    
                txt_show1.setVisibility(View.INVISIBLE);
                txt_name.setVisibility(View.VISIBLE);
                txt_usranme.setVisibility(View.VISIBLE);
                txt_number.setVisibility(View.VISIBLE);
                txt_province.setVisibility(View.VISIBLE);
            }
        });
        return view;
    }
    

    You OK !!!!

    Comparing mongoose _id and strings

    I faced exactly the same problem and i simply resolved the issue with the help of JSON.stringify() as follow:-

    if (JSON.stringify(results.userId) === JSON.stringify(AnotherMongoDocument._id)) {
            console.log('This is never true');
    }
    

    How to iterate through a list of dictionaries in Jinja template?

    {% for i in yourlist %}
      {% for k,v in i.items() %}
        {# do what you want here #}
      {% endfor %}
    {% endfor %}
    

    Correct location of openssl.cnf file

    RHEL: /etc/pki/tls/openssl.cnf

    Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

    I had this problem when running sudo ionic run android as root as these environmental variables were not persisted. Fixed by running sudo -E ionic run android.

    In OS X Lion, LANG is not set to UTF-8, how to fix it?

    This is a headbreaker for a long time. I see now it's OSX.. i change it system-wide and it works perfect

    When i add this the LANG in Centos6 and Fedora is also my preferred LANG. You can also "uncheck" export or set locale in terminal settings (OSX) /etc/profile

    export LC_ALL=en_US.UTF-8
    export LANG=en_US.UTF-8

    How to use npm with ASP.NET Core

    I give you two answers. npm combined with other tools is powerful but requires some work to setup. If you just want to download some libraries, you might want to use Library Manager instead (released in Visual Studio 15.8).

    NPM (Advanced)

    First add package.json in the root of you project. Add the following content:

    {
      "version": "1.0.0",
      "name": "asp.net",
      "private": true,
      "devDependencies": {
        "gulp": "3.9.1",
        "del": "3.0.0"
      },
      "dependencies": {
        "jquery": "3.3.1",
        "jquery-validation": "1.17.0",
        "jquery-validation-unobtrusive": "3.2.10",
        "bootstrap": "3.3.7"
      }
    }
    

    This will make NPM download Bootstrap, JQuery and other libraries that is used in a new asp.net core project to a folder named node_modules. Next step is to copy the files to an appropriate place. To do this we will use gulp, which also was downloaded by NPM. Then add a new file in the root of you project named gulpfile.js. Add the following content:

    /// <binding AfterBuild='default' Clean='clean' />
    /*
    This file is the main entry point for defining Gulp tasks and using Gulp plugins.
    Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
    */
    
    var gulp = require('gulp');
    var del = require('del');
    
    var nodeRoot = './node_modules/';
    var targetPath = './wwwroot/lib/';
    
    gulp.task('clean', function () {
        return del([targetPath + '/**/*']);
    });
    
    gulp.task('default', function () {
        gulp.src(nodeRoot + "bootstrap/dist/js/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/js"));
        gulp.src(nodeRoot + "bootstrap/dist/css/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/css"));
        gulp.src(nodeRoot + "bootstrap/dist/fonts/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/fonts"));
    
        gulp.src(nodeRoot + "jquery/dist/jquery.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
        gulp.src(nodeRoot + "jquery/dist/jquery.min.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
        gulp.src(nodeRoot + "jquery/dist/jquery.min.map").pipe(gulp.dest(targetPath + "/jquery/dist"));
    
        gulp.src(nodeRoot + "jquery-validation/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation/dist"));
    
        gulp.src(nodeRoot + "jquery-validation-unobtrusive/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation-unobtrusive"));
    });
    

    This file contains a JavaScript code that is executed when the project is build and cleaned. It’s will copy all necessary files to lib2 (not lib – you can easily change this). I have used the same structure as in a new project, but it’s easy to change files to a different location. If you move the files, make sure you also update _Layout.cshtml. Note that all files in the lib2-directory will be removed when the project is cleaned.

    If you right click on gulpfile.js, you can select Task Runner Explorer. From here you can run gulp manually to copy or clean files.

    Gulp could also be useful for other tasks like minify JavaScript and CSS-files:

    https://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp?view=aspnetcore-2.1

    Library Manager (Simple)

    Right click on you project and select Manage client side-libraries. The file libman.json is now open. In this file you specify which library and files to use and where they should be stored locally. Really simple! The following file copies the default libraries that is used when creating a new ASP.NET Core 2.1 project:

    {
      "version": "1.0",
      "defaultProvider": "cdnjs",
      "libraries": [
        {
          "library": "[email protected]",
          "files": [ "jquery.js", "jquery.min.map", "jquery.min.js" ],
          "destination": "wwwroot/lib/jquery/dist/"
        },
        {
          "library": "[email protected]",
          "files": [ "additional-methods.js", "additional-methods.min.js", "jquery.validate.js", "jquery.validate.min.js" ],
          "destination": "wwwroot/lib/jquery-validation/dist/"
        },
        {
          "library": "[email protected]",
          "files": [ "jquery.validate.unobtrusive.js", "jquery.validate.unobtrusive.min.js" ],
          "destination": "wwwroot/lib/jquery-validation-unobtrusive/"
        },
        {
          "library": "[email protected]",
          "files": [
            "css/bootstrap.css",
            "css/bootstrap.css.map",
            "css/bootstrap.min.css",
            "css/bootstrap.min.css.map",
            "css/bootstrap-theme.css",
            "css/bootstrap-theme.css.map",
            "css/bootstrap-theme.min.css",
            "css/bootstrap-theme.min.css.map",
            "fonts/glyphicons-halflings-regular.eot",
            "fonts/glyphicons-halflings-regular.svg",
            "fonts/glyphicons-halflings-regular.ttf",
            "fonts/glyphicons-halflings-regular.woff",
            "fonts/glyphicons-halflings-regular.woff2",
            "js/bootstrap.js",
            "js/bootstrap.min.js",
            "js/npm.js"
          ],
          "destination": "wwwroot/lib/bootstrap/dist"
        },
        {
          "library": "[email protected]",
          "files": [ "list.js", "list.min.js" ],
          "destination": "wwwroot/lib/listjs"
        }
      ]
    }
    

    If you move the files, make sure you also update _Layout.cshtml.

    PostgreSQL: How to change PostgreSQL user password?

    To change password using Linux command line, use:

    sudo -u <user_name> psql -c "ALTER USER <user_name> PASSWORD '<new_password>';"
    

    How do I pass command-line arguments to a WinForms application?

    This may not be a popular solution for everyone, but I like the Application Framework in Visual Basic, even when using C#.

    Add a reference to Microsoft.VisualBasic

    Create a class called WindowsFormsApplication

    public class WindowsFormsApplication : WindowsFormsApplicationBase
    {
    
        /// <summary>
        /// Runs the specified mainForm in this application context.
        /// </summary>
        /// <param name="mainForm">Form that is run.</param>
        public virtual void Run(Form mainForm)
        {
            // set up the main form.
            this.MainForm = mainForm;
    
            // Example code
            ((Form1)mainForm).FileName = this.CommandLineArgs[0];
    
            // then, run the the main form.
            this.Run(this.CommandLineArgs);
        }
    
        /// <summary>
        /// Runs this.MainForm in this application context. Converts the command
        /// line arguments correctly for the base this.Run method.
        /// </summary>
        /// <param name="commandLineArgs">Command line collection.</param>
        private void Run(ReadOnlyCollection<string> commandLineArgs)
        {
            // convert the Collection<string> to string[], so that it can be used
            // in the Run method.
            ArrayList list = new ArrayList(commandLineArgs);
            string[] commandLine = (string[])list.ToArray(typeof(string));
            this.Run(commandLine);
        }
    
    }
    

    Modify your Main() routine to look like this

    static class Program
    {
    
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
    
            var application = new WindowsFormsApplication();
            application.Run(new Form1());
        }
    }
    

    This method offers some additional usefull features (like SplashScreen support and some usefull events)

    public event NetworkAvailableEventHandler NetworkAvailabilityChanged;d.
    public event ShutdownEventHandler Shutdown;
    public event StartupEventHandler Startup;
    public event StartupNextInstanceEventHandler StartupNextInstance;
    public event UnhandledExceptionEventHandler UnhandledException;
    

    No route matches "/users/sign_out" devise rails 3

    With one exception, Jessie's answer worked for me:

    <%= link_to "Sign out", destroy_user_session_path, :method => :delete %>
    

    change:

    :delete
    

    ... to:

    'delete'
    

    So the code that worked for me is:

    <%= link_to "Sign out", destroy_user_session_path, :method => 'delete' %>
    

    How can I check if a background image is loaded?

    Here is a small plugin I made to allow you to do exactly this, it also works on multiple background images and multiple elements:

    Read the article:

    http://catmull.uk/code-lab/background-image-loaded/

    or go straight to the plugin code:

    http://catmull.uk/downloads/bg-loaded/bg-loaded.js

    So just include the plugin and then call it on the element:

    <script type="text/javascript" src="http://catmull.uk/downloads/bg-loaded/bg-loaded.js"></script>
    <script type="text/javascript">
       $('body').bgLoaded();
    </script>
    

    Obviously download the plugin and store it on your own hosting.

    By default it adds an additional "bg-loaded" class to each matched element once the background is loaded but you can easily change that by passing it a different function like this:

    <script type="text/javascript" src="http://catmull.uk/downloads/bg-loaded/bg-loaded.js"></script>
    <script type="text/javascript">
       $('body').bgLoaded({
          afterLoaded : function() {
             alert('Background image done loading');
          }
       });
    </script>
    

    Here is a codepen demonstrating it working.

    http://codepen.io/catmull/pen/Lfcpb

    python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

    So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:

    r" |(?<![0-9])[.,](?![0-9])"
    

    How can I get a list of Git branches, ordered by most recent commit?

    Here is a simple command that lists all branches with latest commits:

    git branch -v
    

    To order by most recent commit, use

    git branch -v --sort=committerdate
    

    Source: http://git-scm.com/book/en/Git-Branching-Branch-Management

    File opens instead of downloading in internet explorer in a href link

    It should be fixed on server side. Your server should return this headers for this file types:

    Content-Type: application/octet-stream
    Content-Disposition: attachment;filename=\"filename.xxx\"
    

    Removing single-quote from a string in php

    You could also be more restrictive in removing disallowed characters. The following regex would remove all characters that are not letters, digits or underscores:

    $FileName = preg_replace('/[^\w]/', '', $UserInput);
    

    You might want to do this to ensure maximum compatibility for filenames across different operating systems.

    split string only on first instance of specified character

    Nowadays String.prototype.split does indeed allow you to limit the number of splits.

    str.split([separator[, limit]])

    ...

    limit Optional

    A non-negative integer limiting the number of splits. If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.

    The array may contain fewer entries than limit if the end of the string is reached before the limit is reached. If limit is 0, no splitting is performed.

    caveat

    It might not work the way you expect. I was hoping it would just ignore the rest of the delimiters, but instead, when it reaches the limit, it splits the remaining string again, omitting the part after the split from the return results.

    let str = 'A_B_C_D_E'
    const limit_2 = str.split('_', 2)
    limit_2
    (2) ["A", "B"]
    const limit_3 = str.split('_', 3)
    limit_3
    (3) ["A", "B", "C"]
    

    I was hoping for:

    let str = 'A_B_C_D_E'
    const limit_2 = str.split('_', 2)
    limit_2
    (2) ["A", "B_C_D_E"]
    const limit_3 = str.split('_', 3)
    limit_3
    (3) ["A", "B", "C_D_E"]
    
    

    Mongoose: findOneAndUpdate doesn't return updated document

    So, "findOneAndUpdate" requires an option to return original document. And, the option is:

    MongoDB shell

    {returnNewDocument: true}

    Ref: https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

    Mongoose

    {new: true}

    Ref: http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate

    Node.js MongoDB Driver API:

    {returnOriginal: false}

    Ref: http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#findOneAndUpdate

    Javascript event handler with parameters

    I don't understand exactly what your code is trying to do, but you can make variables available in any event handler using the advantages of function closures:

    function addClickHandler(elem, arg1, arg2) {
        elem.addEventListener('click', function(e) {
            // in the event handler function here, you can directly refer
            // to arg1 and arg2 from the parent function arguments
        }, false);
    }
    

    Depending upon your exact coding situation, you can pretty much always make some sort of closure preserve access to the variables for you.

    From your comments, if what you're trying to accomplish is this:

    element.addEventListener('click', func(event, this.elements[i]))
    

    Then, you could do this with a self executing function (IIFE) that captures the arguments you want in a closure as it executes and returns the actual event handler function:

    element.addEventListener('click', (function(passedInElement) {
        return function(e) {func(e, passedInElement); };
    }) (this.elements[i]), false);
    

    For more info on how an IIFE works, see these other references:

    Javascript wrapping code inside anonymous function

    Immediately-Invoked Function Expression (IIFE) In JavaScript - Passing jQuery

    What are good use cases for JavaScript self executing anonymous functions?

    This last version is perhaps easier to see what it's doing like this:

    // return our event handler while capturing an argument in the closure
    function handleEvent(passedInElement) {
        return function(e) {
            func(e, passedInElement); 
        };
    }
    
    element.addEventListener('click', handleEvent(this.elements[i]));
    

    It is also possible to use .bind() to add arguments to a callback. Any arguments you pass to .bind() will be prepended to the arguments that the callback itself will have. So, you could do this:

    elem.addEventListener('click', function(a1, a2, e) {
        // inside the event handler, you have access to both your arguments
        // and the event object that the event handler passes
    }.bind(elem, arg1, arg2));
    

    Remove unwanted parts from strings in a column

    Suppose your DF is having those extra character in between numbers as well.The last entry.

      result   time
    0   +52A  09:00
    1   +62B  10:00
    2   +44a  11:00
    3   +30b  12:00
    4  -110a  13:00
    5   3+b0  14:00
    

    You can try str.replace to remove characters not only from start and end but also from in between.

    DF['result'] = DF['result'].str.replace('\+|a|b|\-|A|B', '')
    

    Output:

      result   time
    0     52  09:00
    1     62  10:00
    2     44  11:00
    3     30  12:00
    4    110  13:00
    5     30  14:00
    

    How to invoke function from external .c file in C?

    Change your Main.c like so

    #include <stdlib.h>
    #include <stdio.h>
    #include "ClasseAusiliaria.h"
    
    int main(void)
    {
      int risultato;
      risultato = addizione(5,6);
      printf("%d\n",risultato);
    }
    

    Create ClasseAusiliaria.h like so

    extern int addizione(int a, int b);
    

    I then compiled and ran your code, I got an output of

    11
    

    Entity Framework Timeouts

    If you are using Entity Framework like me, you should define Time out on Startup class as follows:

     services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), o => o.CommandTimeout(180)));
    

    SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

    In my case, it was a .pem file. Turns out holds good for that too. Changed permissions of the file and it worked.

    chmod 400 ~/.ssh/dev-shared.pem

    Thanks for all of those who helped above.

    SyntaxError: missing ) after argument list

    SyntaxError: missing ) after argument list.

    the issue also may occur if you pass string directly without a single or double quote.

    $('#contentData').append("<div class='media'><div class='media-body'><a class='btn' href='" + type + "'  onclick=\"(canLaunch(' + v.LibraryItemName +  '))\">View &raquo;</a></div></div>").
    

    so always keep the habit to pass in a quote like

     onclick=\"(canLaunch(\'' + v.LibraryItemName  + '\'))"\
    

    Is it possible to program iPhone in C++

    You have to use Objective C to interface with the Cocoa API, so there is no choice. Of course, you can use as much C++ as you like behind the scenes (Objective C++ makes this easy).

    It is an insane language indeed, but it's also... kind of fun to use once you're a bit used to it. :-)

    Regular Expression to reformat a US phone number in Javascript

    The solutions above are superior, especially if using Java, and encountering more numbers with more than 10 digits such as the international code prefix or additional extension numbers. This solution is basic (I'm a beginner in the regex world) and designed with US Phone numbers in mind and is only useful for strings with just 10 numbers with perhaps some formatting characters, or perhaps no formatting characters at all (just 10 numbers). As such I would recomend this solution only for semi-automatic applications. I Personally prefer to store numbers as just 10 numbers without formatting characters, but also want to be able to convert or clean phone numbers to the standard format normal people and apps/phones will recognize instantly at will.

    I came across this post looking for something I could use with a text cleaner app that has PCRE Regex capabilities (but no java functions). I will post this here for people who could use a simple pure Regex solution that could work in a variety of text editors, cleaners, expanders, or even some clipboard managers. I personally use Sublime and TextSoap. This solution was made for Text Soap as it lives in the menu bar and provides a drop-down menu where you can trigger text manipulation actions on what is selected by the cursor or what's in the clipboard.

    My approach is essentially two substitution/search and replace regexes. Each substitution search and replace involves two regexes, one for search and one for replace.

    Substitution/ Search & Replace #1

    • The first substitution/ search & replace strips non-numeric numbers from an otherwise 10-digit number to a 10-digit string.

    First Substitution/ Search Regex: \D

    • This search string matches all characters that is not a digit.

    First Substitution/ Replace Regex: "" (nothing, not even a space)

    • Leave the substitute field completely blank, no white space should exist including spaces. This will result in all matched non-digit characters being deleted. You should have gone in with 10 digits + formatting characters prior this operation and come out with 10 digits sans formatting characters.

    Substitution/ Search & Replace #2

    • The second substitution/search and replace search part of the operation captures groups for area code $1, a capture group for the second set of three numbers $2, and the last capture group for the last set of four numbers $3. The regex for the substitute portion of the operation inserts US phone number formatting in between the captured group of digits.

    Second Substitution/ Search Regex: (\d{3})(\d{3})(\d{4})

    Second Substitution/ Replace Regex: \($1\) $2\-$3

    • The backslash \ escapes the special characters (, ) , (<-whitespace), and - since we are inserting them between our captured numbers in capture groups $1, $2, & $3 for US phone number formatting purposes.

    • In TextSoap I created a custom cleaner that includes the two substitution operation actions, so in practice it feels identical to executing a script. I'm sure this solution could be improved but I expect complexity to go up quite a bit. An improved version of this solution is welcomed as a learning experience if anyone wants to add to this.

    How do you properly use WideCharToMultiByte

    Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:

    #include <windows.h>
    #include <stdio.h>
    #include <wchar.h>
    #include <string.h>
    
    /* string consisting of several Asian characters */
    wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";
    
    int main() 
    {
    
        size_t wcsChars = wcslen( wcsString);
    
        size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1, 
                                                   NULL, 0,  NULL, NULL);
    
        printf( "Wide chars in wcsString: %u\n", wcsChars);
        printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
                 sizeRequired-1);
    
        sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
                                            NULL, 0,  NULL, NULL);
        printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
                 sizeRequired-1);
    }
    

    And the output:

    Wide chars in wcsString: 6
    Bytes required for CP950 encoding (excluding NUL terminator): 12
    Bytes required for UTF8 encoding (excluding NUL terminator): 18
    

    How do I import the javax.servlet API in my Eclipse project?

    For maven projects add following dependancy :

    <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
    

    Reference

    For gradle projects:

    dependencies {
    providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
    }
    

    or download javax.servlet.jar and add to your project.

    Web colors in an Android color xml resource file

    I specifically was looking for the XML representation for Android.Graphics.Color. I didn't find these, so here you are. More details are in the help document.

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="sysBlack">#FF000000</color>
        <color name="sysBlue">#FF0000FF</color>
        <color name="sysCyan">#FF00FFFF</color>
        <color name="sysDkGray">#FF444444</color>
        <color name="sysGray">#FF888888</color>
        <color name="sysGreen">#FF00FF00</color>
        <color name="sysLtGray">#FFCCCCCC</color>
        <color name="sysMagenta">#FFFF00FF</color>
        <color name="sysRed">#FFFF0000</color>
        <color name="sysTransparent">#00000000</color>
        <color name="sysWhite">#FFFFFFFF</color>
        <color name="sysYellow">#FFFFFF00</color>
    </resources>
    

    Of course, this is used like this:

    android:textColor="@color/sysGray"
    

    Update Angular model after setting input value with jQuery

    I've written this little plugin for jQuery which will make all calls to .val(value) update the angular element if present:

    (function($, ng) {
      'use strict';
    
      var $val = $.fn.val; // save original jQuery function
    
      // override jQuery function
      $.fn.val = function (value) {
        // if getter, just return original
        if (!arguments.length) {
          return $val.call(this);
        }
    
        // get result of original function
        var result = $val.call(this, value);
    
        // trigger angular input (this[0] is the DOM object)
        ng.element(this[0]).triggerHandler('input');
    
        // return the original result
        return result; 
      }
    })(window.jQuery, window.angular);
    

    Just pop this script in after jQuery and angular.js and val(value) updates should now play nice.


    Minified version:

    !function(n,t){"use strict";var r=n.fn.val;n.fn.val=function(n){if(!arguments.length)return r.call(this);var e=r.call(this,n);return t.element(this[0]).triggerHandler("input"),e}}(window.jQuery,window.angular);
    

    Example:

    _x000D_
    _x000D_
    // the function_x000D_
    (function($, ng) {_x000D_
      'use strict';_x000D_
      _x000D_
      var $val = $.fn.val;_x000D_
      _x000D_
      $.fn.val = function (value) {_x000D_
        if (!arguments.length) {_x000D_
          return $val.call(this);_x000D_
        }_x000D_
        _x000D_
        var result = $val.call(this, value);_x000D_
        _x000D_
        ng.element(this[0]).triggerHandler('input');_x000D_
        _x000D_
        return result;_x000D_
        _x000D_
      }_x000D_
    })(window.jQuery, window.angular);_x000D_
    _x000D_
    (function(ng){ _x000D_
      ng.module('example', [])_x000D_
        .controller('ExampleController', function($scope) {_x000D_
          $scope.output = "output";_x000D_
          _x000D_
          $scope.change = function() {_x000D_
            $scope.output = "" + $scope.input;_x000D_
          }_x000D_
        });_x000D_
    })(window.angular);_x000D_
    _x000D_
    (function($){  _x000D_
      $(function() {_x000D_
        var button = $('#button');_x000D_
      _x000D_
        if (button.length)_x000D_
          console.log('hello, button');_x000D_
        _x000D_
        button.click(function() {_x000D_
          var input = $('#input');_x000D_
          _x000D_
          var value = parseInt(input.val());_x000D_
          value = isNaN(value) ? 0 : value;_x000D_
          _x000D_
          input.val(value + 1);_x000D_
        });_x000D_
      });_x000D_
    })(window.jQuery);
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <div ng-app="example" ng-controller="ExampleController">_x000D_
      <input type="number" id="input" ng-model="input" ng-change="change()" />_x000D_
      <span>{{output}}</span>_x000D_
      <button id="button">+</button>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How should I throw a divide by zero exception in Java without actually dividing by zero?

    public class ZeroDivisionException extends ArithmeticException {
        // ...
    }
    
    if (denominator == 0) {
        throw new ZeroDivisionException();
    }
    

    HTML checkbox - allow to check only one checkbox

    sapSet = mbo.getThisMboSet()
    sapCount = sapSet.count()
    saplist = []
    
    if sapCount > 1:
       for i in range(sapCount):`enter code here`
         defaultCheck = sapSet.getMbo(i)
         saplist.append(defaultCheck.getInt("HNADEFACC"))
       defCount = saplist.count(1)
       if defCount > 1:
          errorgroup = " Please Note: you are allowed"
          errorkey = "  only One Default Account"
       if defCount < 1:
          errorgroup = " Please enter "
          errorkey = "  at leat One Default Account"
    else:
       mbo.setValue("HNADEFACC",1,MboConstants.NOACCESSCHECK)
    

    How to simulate browsing from various locations?

    Sometimes a website doesn't work on my PC and I want to know if it's the website or a problem local to me(e.g. my ISP, my router, etc).

    The simplest way to check a website and avoid using your local network resources(and thus avoid any problems caused by them) is using a web proxy such as Proxy.org.

    How to present popover properly in iOS 8

    I found a complete example of how to get this all to work so that you can always display a popover no matter the device/orientation https://github.com/frogcjn/AdaptivePopover_iOS8_Swift.

    The key is to implement UIAdaptivePresentationControllerDelegate

    func adaptivePresentationStyleForPresentationController(PC: UIPresentationController!) -> UIModalPresentationStyle {
        // This *forces* a popover to be displayed on the iPhone
        return .None
    }
    

    Then extend the example above (from Imagine Digital):

    nav.popoverPresentationController!.delegate = implOfUIAPCDelegate
    

    How can I enable CORS on Django REST Framework

    Below are the working steps without the need for any external modules:

    Step 1: Create a module in your app.

    E.g, lets assume we have an app called user_registration_app. Explore user_registration_app and create a new file.

    Lets call this as custom_cors_middleware.py

    Paste the below Class definition:

    class CustomCorsMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response
            # One-time configuration and initialization.
    
        def __call__(self, request):
            # Code to be executed for each request before
            # the view (and later middleware) are called.
    
            response = self.get_response(request)
            response["Access-Control-Allow-Origin"] = "*"
            response["Access-Control-Allow-Headers"] = "*"
    
            # Code to be executed for each request/response after
            # the view is called.
    
            return response
    

    Step 2: Register a middleware

    In your projects settings.py file, add this line

    'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'

    E.g:

      MIDDLEWARE = [
            'user_registration_app.custom_cors_middleware.CustomCorsMiddleware', # ADD THIS LINE BEFORE CommonMiddleware
             ...
            'django.middleware.common.CommonMiddleware',
    
        ]
    

    Remember to replace user_registration_app with the name of your app where you have created your custom_cors_middleware.py module.

    You can now verify it will add the required response headers to all the views in the project!

    oracle diff: how to compare two tables?

    You may try dbForge Data Compare for Oracle, a **free GUI tool for data comparison and synchronization, that can do these actions over all database or partially.

    alt text

    cmake and libpthread

    target_compile_options solution above is wrong, it won't link the library.

    Use:

    SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")

    OR

    target_link_libraries(XXX PUBLIC pthread)

    OR

    set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)

    Increase JVM max heap size for Eclipse

    You can use this configuration:

    -startup
    plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
    --launcher.library
    plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
    -showsplash
    org.eclipse.platform
    --launcher.XXMaxPermSize
    256m
    --launcher.defaultAction
    openFile
    -vmargs
    -Xms512m
    -Xmx1024m
    -XX:+UseParallelGC
    -XX:PermSize=256M
    -XX:MaxPermSize=512M
    

    Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

    You use RAISE_APPLICATION_ERROR in order to create an Oracle style exception/error that is specific to your code/needs. Good use of these help to produce code that is clearer, more maintainable, and easier to debug.

    For example, if I have an application calling a stored procedure that adds a user and that user already exists, you'll usually get back an error like:

    ORA-00001: unique constraint (USERS.PK_USER_KEY) violated
    

    Obviously this error and associated message are not unique to the task you were trying to do. Creating your own Oracle application errors allow you to be clearer on the intent of the action and the cause of the issue.

    raise_application_error(-20101, 'User ' || in_user || ' already exists!');
    

    Now your application code can write an exception handler in order to process this specific error condition. Think of it as a way to make Oracle communicate error conditions that your application expects in a "language" (for lack of a better term) that you have defined and is more meaningful to your application's problem domain.

    Note that user defined errors must be in the range between -20000 and -20999.

    The following link provides lots of good information on this topic and Oracle exceptions in general.

    How to transform currentTimeMillis to a readable date format?

    It will work.

    long yourmilliseconds = System.currentTimeMillis();
    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");    
    Date resultdate = new Date(yourmilliseconds);
    System.out.println(sdf.format(resultdate));
    

    Spring MVC @PathVariable with dot (.) is getting truncated

    If you are using Spring 3.2.x and <mvc:annotation-driven />, create this little BeanPostProcessor:

    package spring;
    
    public final class DoNotTruncateMyUrls implements BeanPostProcessor {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof RequestMappingHandlerMapping) {
                ((RequestMappingHandlerMapping)bean).setUseSuffixPatternMatch(false);
            }
            return bean;
        }
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }
    }
    

    Then put this in your MVC config xml:

    <bean class="spring.DoNotTruncateMyUrls" />
    

    What is the best way to trigger onchange event in react js

    For HTMLSelectElement, i.e. <select>

    var element = document.getElementById("element-id");
    var trigger = Object.getOwnPropertyDescriptor(
      window.HTMLSelectElement.prototype,
      "value"
    ).set;
    trigger.call(element, 4); // 4 is the select option's value we want to set
    var event = new Event("change", { bubbles: true });
    element.dispatchEvent(event);
    

    How can I represent an infinite number in Python?

    I don't know exactly what you are doing, but float("inf") gives you a float Infinity, which is greater than any other number.

    How can I create a copy of an Oracle table without copying the data?

    Just use a where clause that won't select any rows:

    create table xyz_new as select * from xyz where 1=0;
    

    Limitations

    The following things will not be copied to the new table:

    • sequences
    • triggers
    • indexes
    • some constraints may not be copied
    • materialized view logs

    This also does not handle partitions


    number of values in a list greater than a certain number

    If you are using NumPy (as in ludaavic's answer), for large arrays you'll probably want to use NumPy's sum function rather than Python's builtin sum for a significant speedup -- e.g., a >1000x speedup for 10 million element arrays on my laptop:

    >>> import numpy as np
    >>> ten_million = 10 * 1000 * 1000
    >>> x, y = (np.random.randn(ten_million) for _ in range(2))
    >>> %timeit sum(x > y)  # time Python builtin sum function
    1 loops, best of 3: 24.3 s per loop
    >>> %timeit (x > y).sum()  # wow, that was really slow! time NumPy sum method
    10 loops, best of 3: 18.7 ms per loop
    >>> %timeit np.sum(x > y)  # time NumPy sum function
    10 loops, best of 3: 18.8 ms per loop
    

    (above uses IPython's %timeit "magic" for timing)

    How to change the text color of first select option

    If the first item is to be used as a placeholder (empty value) and your select is required then you can use the :invalid pseudo-class to target it.

    _x000D_
    _x000D_
    select {_x000D_
      -webkit-appearance: menulist-button;_x000D_
      color: black;_x000D_
    }_x000D_
    _x000D_
    select:invalid {_x000D_
      color: green;_x000D_
    }
    _x000D_
    <select required>_x000D_
      <option value="">Item1</option>_x000D_
      <option value="Item2">Item2</option>_x000D_
      <option value="Item3">Item3</option>_x000D_
    </select>
    _x000D_
    _x000D_
    _x000D_