Programs & Examples On #Extract

Questions related to retrieving specific information from a (typically minimally structured) data source, such as a web site, media file, source code collection or compressed archive (in which case the desired information is one or more original, uncompressed files). When using this tag, please include additional tags to clarify which specific environment/language/scenario your question refers to.

Accessing last x characters of a string in Bash

Last three characters of string:

${string: -3}

or

${string:(-3)}

(mind the space between : and -3 in the first form).

Please refer to the Shell Parameter Expansion in the reference manual:

${parameter:offset}
${parameter:offset:length}

Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.

If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.

Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.

Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3} expands to the empty string. If, in this case, you want the expansion of string, you may use:

${string:${#string}<3?0:-3}

This uses the ?: ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.


Update for a POSIX-compliant solution

The previous part gives the best option when using Bash. If you want to target POSIX shells, here's an option (that doesn't use pipes or external tools like cut):

# New variable with 3 last characters removed
prefix=${string%???}
# The new string is obtained by removing the prefix a from string
newstring=${string#"$prefix"}

One of the main things to observe here is the use of quoting for prefix inside the parameter expansion. This is mentioned in the POSIX ref (at the end of the section):

The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Pattern Matching Notation), rather than regular expression notation, shall be used to evaluate the patterns. If parameter is '#', '*', or '@', the result of the expansion is unspecified. If parameter is unset and set -u is in effect, the expansion shall fail. Enclosing the full parameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces shall have this effect. In each variety, if word is omitted, the empty pattern shall be used.

This is important if your string contains special characters. E.g. (in dash),

$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
*ext
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"
ext

Of course, this is usable only when then number of characters is known in advance, as you have to hardcode the number of ? in the parameter expansion; but when it's the case, it's a good portable solution.

How can I extract the folder path from file path in Python?

Here is the code:

import os
existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = os.path.dirname(existGDBPath)
print wkspFldr # T:\Data\DBDesign

Get string after character

Use parameter expansion, if the value is already stored in a variable.

$ str="GenFiltEff=7.092200e-01"
$ value=${str#*=}

Or use read

$ IFS="=" read name value <<< "GenFiltEff=7.092200e-01"

Either way,

$ echo $value
7.092200e-01

How to get the first word of a sentence in PHP?

personally strsplit / explode / strtok does not support word boundaries, so to get a more accute split use regular expression with the \w

preg_split('/[\s]+/',$string,1);

This would split words with boundaries to a limit of 1.

python pandas extract year from datetime: df['year'] = df['date'].year is not working

This works:

df['date'].dt.year

Now:

df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month

gives this data frame:

        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

Javascript - How to extract filename from a file input control

If you are using jQuery then

$("#fileupload").val();

Extract images from PDF without resampling, in python?

Much easier solution:

Use the poppler-utils package. To install it use homebrew (homebrew is MacOS specific, but you can find the poppler-utils package for Widows or Linux here: https://poppler.freedesktop.org/). First line of code below installs poppler-utils using homebrew. After installation the second line (run from the command line) then extracts images from a PDF file and names them "image*". To run this program from within Python use the os or subprocess module. Third line is code using os module, beneath that is an example with subprocess (python 3.5 or later for run() function). More info here: https://www.cyberciti.biz/faq/easily-extract-images-from-pdf-file/

brew install poppler

pdfimages file.pdf image

import os
os.system('pdfimages file.pdf image')

or

import subprocess
subprocess.run('pdfimages file.pdf image', shell=True)

Excel - extracting data based on another list

New Excel versions

=IF(ISNA(VLOOKUP(A1,B,B,1,FALSE)),"",A1)

Older Excel versions

=IF(ISNA(VLOOKUP(A1;B:B;1;FALSE));"";A1)

That is: "If the value of A1 exists in the B column, display it here. If it doesn't exist, leave it empty."

Extract and delete all .gz in a directory- Linux

Try:

ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 tar xvfz

Then Try:

ls -1 | grep -E "\.tar\.gz$" | xargs -n 1 rm

This will untar all .tar.gz files in the current directory and then delete all the .tar.gz files. If you want an explanation, the "|" takes the stdout of the command before it, and uses that as the stdin of the command after it. Use "man command" w/o the quotes to figure out what those commands and arguments do. Or, you can research online.

Java: export to an .jar file in eclipse

No need for external plugins. In the Export JAR dialog, make sure you select all the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below. JAR Export Dialog

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

I finished my work on this stuff - that is, iOS 4 + iTunes 9.2 update of my backup decoder library for Python - http://www.iki.fi/fingon/iphonebackupdb.py

It does what I need, little documentation, but feel free to copy ideas from there ;-)

(Seems to work fine with my backups at least.)

How can I extract all values from a dictionary in Python?

If you want all of the values, use this:

dict_name_goes_here.values()

If you want all of the keys, use this:

dict_name_goes_here.keys()

IF you want all of the items (both keys and values), I would use this:

dict_name_goes_here.items()

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

Just adding here that [[ also is equipped for recursive indexing.

This was hinted at in the answer by @JijoMatthew but not explored.

As noted in ?"[[", syntax like x[[y]], where length(y) > 1, is interpreted as:

x[[ y[1] ]][[ y[2] ]][[ y[3] ]] ... [[ y[length(y)] ]]

Note that this doesn't change what should be your main takeaway on the difference between [ and [[ -- namely, that the former is used for subsetting, and the latter is used for extracting single list elements.

For example,

x <- list(list(list(1), 2), list(list(list(3), 4), 5), 6)
x
# [[1]]
# [[1]][[1]]
# [[1]][[1]][[1]]
# [1] 1
#
# [[1]][[2]]
# [1] 2
#
# [[2]]
# [[2]][[1]]
# [[2]][[1]][[1]]
# [[2]][[1]][[1]][[1]]
# [1] 3
#
# [[2]][[1]][[2]]
# [1] 4
#
# [[2]][[2]]
# [1] 5
#
# [[3]]
# [1] 6

To get the value 3, we can do:

x[[c(2, 1, 1, 1)]]
# [1] 3

Getting back to @JijoMatthew's answer above, recall r:

r <- list(1:10, foo=1, far=2)

In particular, this explains the errors we tend to get when mis-using [[, namely:

r[[1:3]]

Error in r[[1:3]] : recursive indexing failed at level 2

Since this code actually tried to evaluate r[[1]][[2]][[3]], and the nesting of r stops at level one, the attempt to extract through recursive indexing failed at [[2]], i.e., at level 2.

Error in r[[c("foo", "far")]] : subscript out of bounds

Here, R was looking for r[["foo"]][["far"]], which doesn't exist, so we get the subscript out of bounds error.

It probably would be a bit more helpful/consistent if both of these errors gave the same message.

how to extract only the year from the date in sql server 2008?

the year function dose, like this:

select year(date_column) from table_name

Read Content from Files which are inside Zip file

If you're wondering how to get the file content from each ZipEntry it's actually quite simple. Here's a sample code:

public static void main(String[] args) throws IOException {
    ZipFile zipFile = new ZipFile("C:/test.zip");

    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while(entries.hasMoreElements()){
        ZipEntry entry = entries.nextElement();
        InputStream stream = zipFile.getInputStream(entry);
    }
}

Once you have the InputStream you can read it however you want.

How to extract one column of a csv file

Been using this code for a while, it is not "quick" unless you count "cutting and pasting from stackoverflow".

It uses ${##} and ${%%} operators in a loop instead of IFS. It calls 'err' and 'die', and supports only comma, dash, and pipe as SEP chars (that's all I needed).

err()  { echo "${0##*/}: Error:" "$@" >&2; }
die()  { err "$@"; exit 1; }

# Return Nth field in a csv string, fields numbered starting with 1
csv_fldN() { fldN , "$1" "$2"; }

# Return Nth field in string of fields separated
# by SEP, fields numbered starting with 1
fldN() {
        local me="fldN: "
        local sep="$1"
        local fldnum="$2"
        local vals="$3"
        case "$sep" in
                -|,|\|) ;;
                *) die "$me: arg1 sep: unsupported separator '$sep'" ;;
        esac
        case "$fldnum" in
                [0-9]*) [ "$fldnum" -gt 0 ] || { err "$me: arg2 fldnum=$fldnum must be number greater or equal to 0."; return 1; } ;;
                *) { err "$me: arg2 fldnum=$fldnum must be number"; return 1;} ;;
        esac
        [ -z "$vals" ] && err "$me: missing arg2 vals: list of '$sep' separated values" && return 1
        fldnum=$(($fldnum - 1))
        while [ $fldnum -gt 0 ] ; do
                vals="${vals#*$sep}"
                fldnum=$(($fldnum - 1))
        done
        echo ${vals%%$sep*}
}

Example:

$ CSVLINE="example,fields with whitespace,field3"
$ $ for fno in $(seq 3); do echo field$fno: $(csv_fldN $fno "$CSVLINE");  done
field1: example
field2: fields with whitespace
field3: field3

Get min and max value in PHP Array

Option 1. First you map the array to get those numbers (and not the full details):

$numbers = array_column($array, 'weight')

Then you get the min and max:

$min = min($numbers);
$max = max($numbers);

Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map:

$numbers = array_map(function($details) {
  return $details['Weight'];
}, $array);

Option 3.

Option 4. If you only need a min OR max, array_reduce() might be faster:

$min = array_reduce($array, function($min, $details) {
  return min($min, $details['weight']);
}, PHP_INT_MAX);

This does more min()s, but they're very fast. The PHP_INT_MAX is to start with a high, and get lower and lower. You could do the same for $max, but you'd start at 0, or -PHP_INT_MAX.

Extract MSI from EXE

Starting with parameter:

setup.exe /A

asks for saving included files (including MSI).

This may depend on the software which created the setup.exe.

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

I had the same problem, you have to load first the Moment.js file!

_x000D_
_x000D_
<script src="path/moment.js"></script>_x000D_
<script src="path/bootstrap-datetimepicker.js"></script>
_x000D_
_x000D_
_x000D_

How to make a Qt Widget grow with the window size?

In Designer, activate the centralWidget and assign a layout, e.g. horizontal or vertical layout. Then your QFormLayout will automatically resize.

Image of Designer

Always make sure, that all widgets have a layout! Otherwise, automatic resizing will break with that widget!

See also

Controls insist on being too large, and won't resize, in QtDesigner

Send request to curl with post data sourced from a file

I had to use a HTTP connection, because on HTTPS there is default file size limit.

https://techcommunity.microsoft.com/t5/IIS-Support-Blog/Solution-for-Request-Entity-Too-Large-error/ba-p/501134

    curl -i -X 'POST' -F 'file=@/home/testeincremental.xlsx' 'http://example.com/upload.aspx?user=example&password=example123&type=XLSX'

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

You are missing <context:annotation-config /> from your spring context so the annotations are not being scanned!

How do you make an array of structs in C?

That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file. Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.

Correct format specifier for double in printf

Format %lf is a perfectly correct printf format for double, exactly as you used it. There's nothing wrong with your code.

Format %lf in printf was not supported in old (pre-C99) versions of C language, which created superficial "inconsistency" between format specifiers for double in printf and scanf. That superficial inconsistency has been fixed in C99.

You are not required to use %lf with double in printf. You can use %f as well, if you so prefer (%lf and %f are equivalent in printf). But in modern C it makes perfect sense to prefer to use %f with float, %lf with double and %Lf with long double, consistently in both printf and scanf.

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

This is the way to be absolutely certain :

<!doctype html> <!-- html5 -->
<html lang="en"> <!-- lang="xx" is allowed, but NO xmlns="http://www.w3.org/1999/xhtml", lang:xml="", and so on -->
<head>
<meta http-equiv="x-ua-compatible" content="IE=Edge"/> 
<!-- as the **very** first line just after head-->
..
</head>

Reason :
Whenever IE meets anything that conflicts, it turns back to "IE 7 standards mode", ignoring the x-ua-compatible.

(I know this is an answer to a very old question, but I have struggled with this myself, and above scheme is the correct answer. It works all the way, everytime)

What's the quickest way to multiply multiple cells by another number?

As one of the answers above says: " then drag the formula fill handle." This KEY feature is not mentioned in MS's explanation, nor in others here. I spent over an hour trying to follow the various instructions, to no avail. This is because you have to click and hold near the bottom of the cell just right (and at least on my computer that is not at all easy) so that a sort of "handle" appears. Once you're luck enough to get that, then carefully slide ["drag"] your cursor down to the lowermost of the cells you want to be multiplied by the constant. The products should show up in each cell as you move down. Just dragging down will give you only the answer in the first cell and a lot of white space.

How to find whether MySQL is installed in Red Hat?

Usually you can find a program under a subdirectory "../bin". System programs are under /usr/bin or /bin. To check where files of mysql package are placed, on RHEL 6 type like this :

rpm -ql mysql (which is the main part of the package)

and the result is a list of "exe" files such as "mysqladmin" tool. About to know the version of the server, run the command:

mysqladmin -u "valid-user" version

How do I get the path and name of the file that is currently executing?

import os

import wx


# return the full path of this file
print(os.getcwd())

icon = wx.Icon(os.getcwd() + '/img/image.png', wx.BITMAP_TYPE_PNG, 16, 16)

# put the icon on the frame
self.SetIcon(icon)

how to know status of currently running jobs

This query will give you the exact output for current running jobs. This will also shows the duration of running job in minutes.

   WITH
    CTE_Sysession (AgentStartDate)
    AS 
    (
        SELECT MAX(AGENT_START_DATE) AS AgentStartDate FROM MSDB.DBO.SYSSESSIONS
    )   
SELECT sjob.name AS JobName
        ,CASE 
            WHEN SJOB.enabled = 1 THEN 'Enabled'
            WHEN sjob.enabled = 0 THEN 'Disabled'
            END AS JobEnabled
        ,sjob.description AS JobDescription
        ,CASE 
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL  THEN 'Running'
            WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NOT NULL AND HIST.run_status = 1 THEN 'Stopped'
            WHEN HIST.run_status = 0 THEN 'Failed'
            WHEN HIST.run_status = 3 THEN 'Canceled'
        END AS JobActivity
        ,DATEDIFF(MINUTE,act.start_execution_date, GETDATE()) DurationMin
        ,hist.run_date AS JobRunDate
        ,run_DURATION/10000 AS Hours
        ,(run_DURATION%10000)/100 AS Minutes 
        ,(run_DURATION%10000)%100 AS Seconds
        ,hist.run_time AS JobRunTime 
        ,hist.run_duration AS JobRunDuration
        ,'tulsql11\dba' AS JobServer
        ,act.start_execution_date AS JobStartDate
        ,act.last_executed_step_id AS JobLastExecutedStep
        ,act.last_executed_step_date AS JobExecutedStepDate
        ,act.stop_execution_date AS JobStopDate
        ,act.next_scheduled_run_date AS JobNextRunDate
        ,sjob.date_created AS JobCreated
        ,sjob.date_modified AS JobModified      
            FROM MSDB.DBO.syssessions AS SYS1
        INNER JOIN CTE_Sysession AS SYS2 ON SYS2.AgentStartDate = SYS1.agent_start_date
        JOIN  msdb.dbo.sysjobactivity act ON act.session_id = SYS1.session_id
        JOIN msdb.dbo.sysjobs sjob ON sjob.job_id = act.job_id
        LEFT JOIN  msdb.dbo.sysjobhistory hist ON hist.job_id = act.job_id AND hist.instance_id = act.job_history_id
        WHERE ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL
        ORDER BY ACT.start_execution_date DESC

Android LinearLayout Gradient Background

<?xml version="1.0" encoding="utf-8"?>

<gradient
    android:angle="90"
    android:startColor="@color/colorPrimary"
    android:endColor="@color/colorPrimary"
    android:centerColor="@color/white"
    android:type="linear"/>

<corners android:bottomRightRadius="10dp"
    android:bottomLeftRadius="10dp"
    android:topRightRadius="10dp"
    android:topLeftRadius="10dp"/>

enter image description here

Synchronous XMLHttpRequest warning and <script>

Even the latest jQuery has that line, so you have these options:

  • Change the source of jQuery yourself - but maybe there is a good reason for its usage
  • Live with the warning, please note that this option is deprecated and not obsolete.
  • Change your code, so it does not use this function

I think number 2 is the most sensible course of action in this case.

By the way if you haven't already tried, try this out: $.ajaxSetup({async:true});, but I don't think it will work.

div background color, to change onhover

To make the whole div act as a link, set the anchor tag as:

display: block

And set your height of the anchor tag to 100%. Then set a fixed height to your div tag. Then style your anchor tag like usual.

For example:

<html>
<head>
    <title>DIV Link</title>

    <style type="text/css">
    .link-container {
        border: 1px solid;
        width: 50%;
        height: 20px;
    }

    .link-container a {
        display: block;
        background: #c8c8c8;
        height: 100%;
        text-align: center;
    }

    .link-container a:hover {
        background: #f8f8f8;
    }

    </style>

</head>
<body>

    <div class="link-container">
        <a href="http://www.stackoverflow.com">Stack Overflow</a>
    </div>

    <div class="link-container">
        <a href="http://www.stackoverflow.com">Stack Overflow</a>
    </div>

</body> </html>

Good luck!

A generic error occurred in GDI+, JPEG Image to MemoryStream

Had a very similar problem and also tried cloning the image which doesn't work. I found that the best solution was to create a new Bitmap object from the image that was loaded from the memory stream. That way the stream can be disposed of e.g.

using (var m = new MemoryStream())
{
    var img = new Bitmap(Image.FromStream(m));
    return img;
}

Hope this helps.

Eclipse gives “Java was started but returned exit code 13”

if you have updated your jdk to 7 you are most likely to face this problem.

This happens mainly due to:

  1. incompatible sdk and jdk versions
  2. using a 32 bit java version for your 64 bit eclipse JVM (programfilex86-java)

WHAT YOU HAVE TO DO : firstly check the eclipse.ini file to see if you have a path that is pointing to your jdk it should look something like this

-vm    
C:\Program Files\Java\blah\blah\blah\javaw.exe    

if not then locate the jdk 7 javaw.exe file
sample :

C:\Program Files\Java\jdk1.7.0_45\jre\bin\javaw.exe 

paste -vm and the path below it into your eclipse.ini file

-vm  
C:\Program Files\Java\jdk1.7.0_45\jre\bin\javaw.exe        

make sure that you type the above just before the -vmargs and after the OpenFile

How to submit http form using C#

Your HTML file is not going to interact with C# directly, but you can write some C# to behave as if it were the HTML file.

For example: there is a class called System.Net.WebClient with simple methods:

using System.Net;
using System.Collections.Specialized;

...
using(WebClient client = new WebClient()) {

    NameValueCollection vals = new NameValueCollection();
    vals.Add("test", "test string");
    client.UploadValues("http://www.someurl.com/page.php", vals);
}

For more documentation and features, refer to the MSDN page.

Parse JSON from JQuery.ajax success data

Well... you are about 3/4 of the way there... you already have your JSON as text.

The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.

It isn't... its just a string.

Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.

You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.

myResult = JSON.parse(request.responseText);

Now myResult is a javascript object containing the properties that were transmitted through AJAX.

That should allow you to handle it the way you appear to be trying to.

Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.

For the record, this was already answered by Andy E for someone else HERE.

edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.

Get row-index values of Pandas DataFrame as list?

To get the index values as a list/list of tuples for Index/MultiIndex do:

df.index.values.tolist()  # an ndarray method, you probably shouldn't depend on this

or

list(df.index.values)  # this will always work in pandas

How to ignore a property in class if null, using json.net

You can write: [JsonProperty("property_name",DefaultValueHandling = DefaultValueHandling.Ignore)]

It also takes care of not serializing properties with default values (not only null). It can be useful for enums for example.

In C# check that filename is *possibly* valid (not that it exists)

You can get a list of invalid characters from Path.GetInvalidPathChars and GetInvalidFileNameChars as discussed in this question.

As noted by jberger, there some other characters which are not included in the response from this method. For much more details of the windows platform, take a look at Naming Files, Paths and Namespaces on MSDN,

As Micah points out, there is Directory.GetLogicalDrives to get a list of valid drives.

How to get a reversed list view on a list in Java?

I know this is an old post but today I was looking for something like this. In the end I wrote the code myself:

private List reverseList(List myList) {
    List invertedList = new ArrayList();
    for (int i = myList.size() - 1; i >= 0; i--) {
        invertedList.add(myList.get(i));
    }
    return invertedList;
}

Not recommended for long Lists, this is not optimized at all. It's kind of an easy solution for controlled scenarios (the Lists I handle have no more than 100 elements).

Hope it helps somebody.

How can I get a JavaScript stack trace when I throw an exception?

In Google Chrome (version 19.0 and beyond), simply throwing an exception works perfectly. For example:

/* file: code.js, line numbers shown */

188: function fa() {
189:    console.log('executing fa...');
190:    fb();
191: }
192:
193: function fb() {
194:    console.log('executing fb...');
195:    fc()
196: }
197:
198: function fc() {
199:    console.log('executing fc...');
200:    throw 'error in fc...'
201: }
202:
203: fa();

will show the stack trace at the browser's console output:

executing fa...                         code.js:189
executing fb...                         code.js:194
executing fc...                         cdoe.js:199
/* this is your stack trace */
Uncaught error in fc...                 code.js:200
    fc                                  code.js:200
    fb                                  code.js:195
    fa                                  code.js:190
    (anonymous function)                code.js:203

Hope this help.

What is the difference between os.path.basename() and os.path.dirname()?

To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

import { HttpClientModule } from '@angular/common/http';

The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below

http.get('friends.json').subscribe(result => this.result =result);

Confusing "duplicate identifier" Typescript error message

Update: Version 1.0 of Typings changed the output structure and the below answer relates to pre 1.0 version.

If you are using Typings and exclude in your tsconfig.json, you may run into the issue of duplicate types and need something like the following:

{
  "exclude": [
    "typings/browser.d.ts",
    "typings/browser",
    "node_modules"
  ]
}

To simplify integration with TypeScript, two files - typings/main.d.ts and typings/browser.d.ts - are generated which reference all the typings installed in the project only one of which can be used at a time.

So depending on which version you need, you should exclude (or include) the "browser" or the "main" type files, but not both, as this is where the duplicates come from.

This Typings issue discusses it more.

mysql server port number

port number 3306 is used for MySQL and tomcat using 8080 port.more port numbers are available for run the servers or software whatever may be for our instant compilation..8080 is default for number so only we are getting port error in eclipse IDE. jvm and tomcat always prefer the 8080.3306 is default port number for MySQL.So only do not want to mention every time as "localhost:3306"

  <?php  
    $dbhost = 'localhost:3306';
//3306 default port number $dbhost='localhost'; is enough to specify the port number
//when we are utilizing xammp default port number is 8080.
      $dbuser = 'root';
      $dbpass = '';
         $db='users';

             $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$db) or die ("could not connect to mysql");      

              // mysqli_select_db("users") or die ("no database");  

    if(! $conn ) {
        die('Could not connect: ' . mysqli_error($conn));
    }else{
        echo 'Connected successfully';
    }
    ?>

Is it possible in Java to catch two exceptions in the same catch block?

For Java < 7 you can use if-else along with Exception:

try {
    // common logic to handle both exceptions
} catch (Exception ex) {
    if (ex instanceof Exception1 || ex instanceof Exception2) {

    }
    else {
        throw ex;
        // or if you don't want to have to declare Exception use
        // throw new RuntimeException(ex);
    }
}

Edited and replaced Throwable with Exception.

How to change ViewPager's page?

Supplemental answer

I was originally having trouble getting a reference to the ViewPager from other class methods because the addOnTabSelectedListener made an anonymous inner class, which in turn required the ViewPager variable to be declared final. The solution was to use a class member variable and not use the anonymous inner class.

public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        viewPager = (ViewPager) findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        // don't use an anonymous inner class here
        tabLayout.addOnTabSelectedListener(tabListener);

    }

    TabLayout.OnTabSelectedListener tabListener = new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };

    // The view pager can now be accessed here, too.
    public void someMethod() {
        viewPager.setCurrentItem(0);
    }

}

Assign command output to variable in batch file

Okay here some more complex sample for the use of For /F

:: Main
@prompt -$G
    call :REGQUERY  "Software\Classes\CLSID\{3E6AE265-3382-A429-56D1-BB2B4D1D}"

@goto :EOF

:REGQUERY
:: Checks HKEY_LOCAL_MACHINE\ and HKEY_CURRENT_USER\ 
:: for the key and lists its content

    @call :EXEC "REG QUERY  HKCU\%~1"
    @call :EXEC "REG QUERY "HKLM\%~1""

@goto :EOF    

:EXEC
    @set output=

    @for /F "delims=" %%i in ('%~1 2^>nul') do @(
        set output=%%i
    )

    @if not "%output%"=="" (
        echo %1 -^> %output%
    )

@goto :EOF

I packed it into the sub function :EXEC so all of its nasty details of implementation doesn't litters the main script. So it got some kinda some batch tutorial. Notes 'bout the code:

  1. the output from the command executed via call :EXEC command is stored in %output%. Batch cmd doesn't cares about scopes so %output% will be also available in the main script.
  2. the @ the beginning is just decoration and there to suppress echoing the command line. You may delete them all and just put some @echo off at the first line is really dislike that. However like this I find debugging much more nice. Decoration Number two is prompt -$G. It's there to make command prompt look like this ->
  3. I use :: instead of rem
  4. the tilde(~) in %~1 is to remove quotes from the first argument
  5. 2^>nul is there to suppress/discard stderr error output. Normally you would do it via 2>nul. Well the ^ the batch escape char is there avoids to early resolving the redirector(>). There's some simulare use a little later in the script: echo %1 -^>... so there ^ makes it possible the output a '>' via echo what else wouldn't have been possible.
  6. even if the compare at @if not "%output%"==""looks like in most common programming languages - it's maybe different that you expected (if you're not used to MS-batch). Well remove the '@' at the beginning. Study the output. Change it tonot %output%==""-rerun and consider why this doesn't work. ;)

Remove part of string in Java

String Replace

String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");

Edit:

By Index

s = s.substring(0, s.indexOf("(") - 1);

Opening a .ipynb.txt File

Try the following steps:

  1. Download the file open it in the Juypter Notebook.
  2. Go to File -> Rename and remove the .txt extension from the end; so now the file name has just .ipynb extension.
  3. Now reopen it from the Juypter Notebook.

What is FCM token in Firebase?

They deprecated getToken() method in the below release notes. Instead, we have to use getInstanceId.

https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId

Task<InstanceIdResult> task = FirebaseInstanceId.getInstance().getInstanceId();
task.addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
      @Override
      public void onSuccess(InstanceIdResult authResult) {
          // Task completed successfully
          // ...
          String fcmToken = authResult.getToken();
      }
});

task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
    // Task failed with an exception
    // ...
}
});

To handle success and failure in the same listener, attach an OnCompleteListener:

task.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
    if (task.isSuccessful()) {
        // Task completed successfully
        InstanceIdResult authResult = task.getResult();
        String fcmToken = authResult.getToken();
    } else {
        // Task failed with an exception
        Exception exception = task.getException();
    }
}
});

Also, the FirebaseInstanceIdService Class is deprecated and they came up with onNewToken method in FireBaseMessagingService as replacement for onTokenRefresh,

you can refer to the release notes here, https://firebase.google.com/support/release-notes/android

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Use this code logic to send the info to your server.
    //sendRegistrationToServer(s);
}

Java converting Image to BufferedImage

From a Java Game Engine:

/**
 * Converts a given Image into a BufferedImage
 *
 * @param img The Image to be converted
 * @return The converted BufferedImage
 */
public static BufferedImage toBufferedImage(Image img)
{
    if (img instanceof BufferedImage)
    {
        return (BufferedImage) img;
    }

    // Create a buffered image with transparency
    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

    // Draw the image on to the buffered image
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    // Return the buffered image
    return bimage;
}

Compare objects in Angular

I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.

BE MINDFUL, If you use angular.equals() on objects that have property obj.$something (property name starts with $) those properties will get ignored in comparison.

Example:

var obj1 = {
  $key0: "A",
  key1: "value1",
  key2: "value2",
  key3: {a: "aa", b: "bb"}
}

var obj2 = {
  $key0: "B"
  key2: "value2",
  key1: "value1",
  key3: {a: "aa", b: "bb"}
}

angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)

How can I search Git branches for a file or directory?

git log + git branch will find it for you:

% git log --all -- somefile

commit 55d2069a092e07c56a6b4d321509ba7620664c63
Author: Dustin Sallings <[email protected]>
Date:   Tue Dec 16 14:16:22 2008 -0800

    added somefile


% git branch -a --contains 55d2069
  otherbranch

Supports globbing, too:

% git log --all -- '**/my_file.png'

The single quotes are necessary (at least if using the Bash shell) so the shell passes the glob pattern to git unchanged, instead of expanding it (just like with Unix find).

How do I get a reference to the app delegate in Swift?

I use this in Swift 2.3.

1.in AppDelegate class

static let sharedInstance: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

2.Call AppDelegate with

let appDelegate = AppDelegate.sharedInstance

ASP.NET MVC3 Razor - Html.ActionLink style

Reviving an old question because it seems to appear at the top of search results.

I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.

  1. I wrapped the action link with a div that would contain the parent style:
<div class="parent-style-one">
      @Html.ActionLink("Homepage", "Home", "Home")
</div>
  1. Next I create the CSS for the div, this will be the parent css and will be inherited by the child elements such as the action link.
  .parent-style-one {
     /* your styles here */
  }
  1. Because all an action link is, is an element when broken down as html so you just need to target that element in your css selection:
  .parent-style-one a {
     text-decoration: none;
  }
  1. For transition effects I did this:
  .parent-style-one a:hover {
        text-decoration: underline;
        -webkit-transition-duration: 1.1s; /* Safari */
        transition-duration: 1.1s;         
  }

This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.

In STL maps, is it better to use map::insert than []?

This is a rather restricted case, but judging from the comments I've received I think it's worth noting.

I've seen people in the past use maps in the form of

map< const key, const val> Map;

to evade cases of accidental value overwriting, but then go ahead writing in some other bits of code:

const_cast< T >Map[]=val;

Their reason for doing this as I recall was because they were sure that in these certain bits of code they were not going to be overwriting map values; hence, going ahead with the more 'readable' method [].

I've never actually had any direct trouble from the code that was written by these people, but I strongly feel up until today that risks - however small - should not be taken when they can be easily avoided.

In cases where you're dealing with map values that absolutely must not be overwritten, use insert. Don't make exceptions merely for readability.

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

Confirmation dialog on ng-click - AngularJS

ng-click return confirm 100% works

in html file call delete_plot() function

<i class="fa fa-trash delete-plot" ng-click="delete_plot()"></i> 
 
  

Add this to your controller

    $scope.delete_plot = function(){
        check = confirm("Are you sure to delete this plot?")
        if(check){
            console.log("yes, OK pressed")
        }else{
            console.log("No, cancel pressed")

        }
    }

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

Another use for bootstrap.yml is to load configuration from kubernetes configmap and secret resources. The application must import the spring-cloud-starter-kubernetes dependency.

As with the Spring Cloud Config, this has to take place during the bootstrap phrase.

From the docs :

spring:
  application:
    name: cloud-k8s-app
  cloud:
    kubernetes:
      config:
        name: default-name
        namespace: default-namespace
        sources:
         # Spring Cloud Kubernetes looks up a ConfigMap named c1 in namespace default-namespace
         - name: c1

So properties stored in the configmap resource with meta.name default-name can be referenced just the same as properties in application.yml

And the same process applies to secrets :

spring:
  application:
    name: cloud-k8s-app
  cloud:
    kubernetes:
      secrets:
        name: default-name
        namespace: default-namespace
        sources:
         # Spring Cloud Kubernetes looks up a Secret named s1 in namespace default-namespace
         - name: s1

How to use an output parameter in Java?

As a workaround a generic "ObjectHolder" can be used. See code example below.

The sample output is:

name: John Doe
dob:1953-12-17
name: Jim Miller
dob:1947-04-18

so the Person parameter has been modified since it's wrapped in the Holder which is passed by value - the generic param inside is a reference where the contents can be modified - so actually a different person is returned and the original stays as is.

/**
 * show work around for missing call by reference in java
 */
public class OutparamTest {

 /**
  * a test class to be used as parameter
  */
 public static class Person {
   public String name;
     public String dob;
     public void show() {
      System.out.println("name: "+name+"\ndob:"+dob);
   }
 }

 /**
  * ObjectHolder (Generic ParameterWrapper)
  */
 public static class ObjectHolder<T> {
    public ObjectHolder(T param) {
     this.param=param;
    }
    public T param;
 }

 /**
  * ObjectHolder is substitute for missing "out" parameter
  */
 public static void setPersonData(ObjectHolder<Person> personHolder,String name,String dob) {
    // Holder needs to be dereferenced to get access to content
    personHolder.param=new Person();
    personHolder.param.name=name;
    personHolder.param.dob=dob;
 } 

  /**
   * show how it works
   */
  public static void main(String args[]) {
    Person jim=new Person();
    jim.name="Jim Miller";
    jim.dob="1947-04-18";
    ObjectHolder<Person> testPersonHolder=new ObjectHolder(jim);
    // modify the testPersonHolder person content by actually creating and returning
    // a new Person in the "out parameter"
    setPersonData(testPersonHolder,"John Doe","1953-12-17");
    testPersonHolder.param.show();
    jim.show();
  }
}

Easy way to get a test file into JUnit

If you need to actually get a File object, you could do the following:

URL url = this.getClass().getResource("/test.wsdl");
File testWsdl = new File(url.getFile());

Which has the benefit of working cross platform, as described in this blog post.

Global Events in Angular

Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.

But make sure to unsubscribe to that on destroy of the parent component.

Fixing broken UTF-8 encoding

This script had a nice approach. Converting it to the language of your choice should not be too difficult:

http://plasmasturm.org/log/416/

#!/usr/bin/perl
use strict;
use warnings;

use Encode qw( decode FB_QUIET );

binmode STDIN, ':bytes';
binmode STDOUT, ':encoding(UTF-8)';

my $out;

while ( <> ) {
  $out = '';
  while ( length ) {
    # consume input string up to the first UTF-8 decode error
    $out .= decode( "utf-8", $_, FB_QUIET );
    # consume one character; all octets are valid Latin-1
    $out .= decode( "iso-8859-1", substr( $_, 0, 1 ), FB_QUIET ) if length;
  }
  print $out;
}

Font awesome is not showing icon

Watch out for Bootstrap! Bootstrap will override .fa classes. If you're bringing in both packages separately thinking "I'll use Bootstrap for responsive block handling and Font-Awesome for icons", you need to address the .fa classes inside Bootstrap so they don't interfere with Font-Awesome's stand-alone implementation.

eg: font-family 'FontAwesome' in Bootstrap will interfere with font-family 'Font Awesome 5 Free' in Font-Awesome and you will get a white box instead of the icon you want.

There may be cleaner ways of handling this, but if you've gone down the checklist trying to fix the "white box" issue and still can't figure it out (like I did), this may be the answer you're looking for.

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

How to select where ID in Array Rails ActiveRecord without exception

Now .find and .find_by_id methods are deprecated in rails 4. So instead we can use below:

Comment.where(id: [2, 3, 5])

It will work even if some of the ids don't exist. This works in the

user.comments.where(id: avoided_ids_array)

Also for excluding ID's

Comment.where.not(id: [2, 3, 5])

Conditionally change img src based on model data

Another alternative (other than binary operators suggested by @jm-) is to use ng-switch:

<span ng-switch on="interface">
   <img ng-switch-when="UP" src='green-checkmark.png'>
   <img ng-switch-default   src='big-black-X.png'>
</span>

ng-switch will likely be better/easier if you have more than two images.

Popup window in PHP?

You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.

Get the decimal part from a double

the best of the best way is:

var floatNumber = 12.5523;

var x = floatNumber - Math.Truncate(floatNumber);

result you can convert however you like

How to select unique records by SQL

It depends on which rown you want to return for each unique item. Your data seems to indicate the minimum data value so in this instance for SQL Server.

SELECT item, min(data)
FROM  table
GROUP BY item

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

Making a PowerShell POST request if a body param starts with '@'

You should be able to do the following:

$params = @{"@type"="login";
 "username"="[email protected]";
 "password"="yyy";
}

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body $params

This will send the post as the body. However - if you want to post this as a Json you might want to be explicit. To post this as a JSON you can specify the ContentType and convert the body to Json by using

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"

Extra: You can also use the Invoke-RestMethod for dealing with JSON and REST apis (which will save you some extra lines for de-serializing)

Android studio Gradle build speed up

I was able to reduce my gradle build from 43 seconds down to 25 seconds on my old core2duo laptop (running linux mint) by adding the following to the gradle.properties file in android studio

org.gradle.parallel=true
org.gradle.daemon=true

source on why the daemon setting makes builds faster: https://www.timroes.de/2013/09/12/speed-up-gradle/

Is there a way to perform "if" in python's lambda

Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.

a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))

How to determine if binary tree is balanced?

If this is for your job, I suggest:

  1. do not reinvent the wheel and
  2. use/buy COTS instead of fiddling with bits.
  3. Save your time/energy for solving business problems.

How to print an unsigned char in C?

There are two bugs in this code. First, in most C implementations with signed char, there is a problem in char ch = 212 because 212 does not fit in an 8-bit signed char, and the C standard does not fully define the behavior (it requires the implementation to define the behavior). It should instead be:

unsigned char ch = 212;

Second, in printf("%u",ch), ch will be promoted to an int in normal C implementations. However, the %u specifier expects an unsigned int, and the C standard does not define behavior when the wrong type is passed. It should instead be:

printf("%u", (unsigned) ch);

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

This happened to me when I was debugging my C# WinForms application in Visual Studio. My application makes calls to Win32 stuff via DllImport, e.g.

[DllImport("Secur32.dll", SetLastError = false)]
private static extern uint LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList);

Running Visual Studio "as Administrator" solved the problem for me.

symfony 2 No route found for "GET /"

i could have been only one who made this mistake but maybe not so i'll post.

the format for annotations in the comments before a route has to start with a slash and two asterisks. i was making the mistake of a slash and only one asterisk, which PHPStorm autocompleted.

my route looked like this:

/*
 * @Route("/",name="homepage")
 */
public function indexAction(Request $request) {
    return $this->render('default/index.html.twig');
}

when it should have been this

/**
 * @Route("/",name="homepage")
 */
public function indexAction(Request $request) {
    return $this->render('default/base.html.twig');
}

@RequestParam vs @PathVariable

@RequestParam is use for query parameter(static values) like: http://localhost:8080/calculation/pow?base=2&ext=4

@PathVariable is use for dynamic values like : http://localhost:8080/calculation/sqrt/8

@RequestMapping(value="/pow", method=RequestMethod.GET)
public int pow(@RequestParam(value="base") int base1, @RequestParam(value="ext") int ext1){
    int pow = (int) Math.pow(base1, ext1);
    return pow;
}

@RequestMapping("/sqrt/{num}")
public double sqrt(@PathVariable(value="num") int num1){
    double sqrtnum=Math.sqrt(num1);
    return sqrtnum;
}

How to check if AlarmManager already has an alarm set?

    Intent intent = new Intent("com.my.package.MY_UNIQUE_ACTION");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    sqlitewraper.context, 0, intent,
                    PendingIntent.FLAG_NO_CREATE);

FLAG_NO_CREATE is not create pending intent so that it gives boolean value false.

            boolean alarmUp = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
                    new Intent("com.my.package.MY_UNIQUE_ACTION"),
                    PendingIntent.FLAG_NO_CREATE) != null);

            if (alarmUp) {
                System.out.print("k");

            }

            AlarmManager alarmManager = (AlarmManager) sqlitewraper.context
                    .getSystemService(Context.ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis(), 1000 * 60, pendingIntent);

After the AlarmManager check the value of Pending Intent it gives true because AlarmManager Update The Flag of Pending Intent.

            boolean alarmUp1 = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
                    new Intent("com.my.package.MY_UNIQUE_ACTION"),
                    PendingIntent.FLAG_UPDATE_CURRENT) != null);
            if (alarmUp1) {
                System.out.print("k");

            }

Set font-weight using Bootstrap classes

You should use bootstarp's variables to control your font-weight if you want a more customized value and/or you're following a scheme that needs to be repeated ; Variables are used throughout the entire project as a way to centralize and share commonly used values like colors, spacing, or font stacks;

you can find all the documentation at http://getbootstrap.com/css.

What are Java command line options to set to allow JVM to be remotely debugged?

Before Java 5.0, use -Xdebug and -Xrunjdwp arguments. These options will still work in later versions, but it will run in interpreted mode instead of JIT, which will be slower.

From Java 5.0, it is better to use the -agentlib:jdwp single option:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1044

Options on -Xrunjdwp or agentlib:jdwp arguments are :

  • transport=dt_socket : means the way used to connect to JVM (socket is a good choice, it can be used to debug a distant computer)
  • address=8000 : TCP/IP port exposed, to connect from the debugger,
  • suspend=y : if 'y', tell the JVM to wait until debugger is attached to begin execution, otherwise (if 'n'), starts execution right away.

JQuery style display value

This will return what you asked, but I wouldnt recommend using css like this. Use external CSS instead of inline css.

$("tr[id='pDetails']").attr("style").split(':')[1];

List of remotes for a Git repository?

FWIW, I had exactly the same question, but I could not find the answer here. It's probably not portable, but at least for gitolite, I can run the following to get what I want:

$ ssh [email protected] info
hello akim, this is gitolite 2.3-1 (Debian) running on git 1.7.10.4
the gitolite config gives you the following access:
     R   W     android
     R   W     bistro
     R   W     checkpn
...

Converting a float to a string without rounding it

I know this is too late but for those who are coming here for the first time, I'd like to post a solution. I have a float value index and a string imgfile and I had the same problem as you. This is how I fixed the issue

index = 1.0
imgfile = 'data/2.jpg'
out = '%.1f,%s' % (index,imgfile)
print out

The output is

1.0,data/2.jpg

You may modify this formatting example as per your convenience.

How do I cancel form submission in submit button onclick event?

You need to return false;:

<input type='submit' value='submit request' onclick='return btnClick();' />

function btnClick() {
    return validData();
}

Excel to CSV with UTF8 encoding

Microsoft Excel has an option to export spreadsheet using Unicode encoding. See following screenshot.

enter image description here

How to use JavaScript regex over multiple lines?

I have tested it (Chrome) and it working for me( both [^] and [^\0]), by changing the dot (.) by either [^\0] or [^] , because dot doesn't match line break (See here: http://www.regular-expressions.info/dot.html).

_x000D_
_x000D_
var ss= "<pre>aaaa\nbbb\nccc</pre>ddd";_x000D_
var arr= ss.match( /<pre[^\0]*?<\/pre>/gm );_x000D_
alert(arr);     //Working
_x000D_
_x000D_
_x000D_

nodejs send html file to client

you can render the page in express more easily


 var app   = require('express')();    
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
 
    app.get('/signup',function(req,res){      
    res.sendFile(path.join(__dirname,'/signup.html'));
    });

so if u request like http://127.0.0.1:8080/signup that it will render signup.html page under views folder.

Remove all the children DOM elements in div

If you are looking for a modern >1.7 Dojo way of destroying all node's children this is the way:

// Destroys all domNode's children nodes
// domNode can be a node or its id:
domConstruct.empty(domNode);

Safely empty the contents of a DOM element. empty() deletes all children but keeps the node there.

Check "dom-construct" documentation for more details.

// Destroys domNode and all it's children
domConstruct.destroy(domNode);

Destroys a DOM element. destroy() deletes all children and the node itself.

OWIN Startup Class Missing

This could be faced in Visual Studio 2015 as well when you use the Azure AD with a MVC project. Here it create the startup file as Startup.Auth.cs in App_Start folder but it will be missing the

[assembly: OwinStartup(typeof(MyWebApp.Startup))]

So add it and you should be good to go. This goes before the namespace start.

How to center the content inside a linear layout?

android:gravity can be used on a Layout to align its children.

android:layout_gravity can be used on any view to align itself in its parent.

NOTE: If self or children is not centering as expected, check if width/height is match_parent and change to something else

Computing cross-correlation function?

I just finished writing my own optimised implementation of normalized cross-correlation for N-dimensional arrays. You can get it from here.

It will calculate cross-correlation either directly, using scipy.ndimage.correlate, or in the frequency domain, using scipy.fftpack.fftn/ifftn depending on whichever will be quickest.

setBackground vs setBackgroundDrawable (Android)

Now you can use either of those options. And it is going to work in any case. Your color can be a HEX code, like this:

myView.setBackgroundResource(ContextCompat.getColor(context, Color.parseColor("#FFFFFF")));

A color resource, like this:

myView.setBackgroundResource(ContextCompat.getColor(context,R.color.blue_background));

Or a custom xml resource, like so:

myView.setBackgroundResource(R.drawable.my_custom_background);

Hope it helps!

How to check which version of Keras is installed?

The simplest way is using pip command:

pip list | grep Keras

How to use Scanner to accept only valid int as input

What you could do is also to take the next token as a String, converts this string to a char array and test that each character in the array is a digit.

I think that's correct, if you don't want to deal with the exceptions.

e.printStackTrace equivalent in python

import traceback
traceback.print_exc()

When doing this inside an except ...: block it will automatically use the current exception. See http://docs.python.org/library/traceback.html for more information.

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

Visual Studio: How to show Overloads in IntelliSense?

Mine showed up in VS2010 after writing the first parenthesis..

so, prams.Add(

After doings something like that, the box with the up and down arrows appeared.

Count the occurrences of DISTINCT values

Just changed Amber's COUNT(*) to COUNT(1) for the better performance.

SELECT name, COUNT(1) as count 
FROM tablename 
GROUP BY name 
ORDER BY count DESC;

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Oracle has two different ways of making views updatable:-

  1. The view is "key preserved" with respect to what you are trying to update. This means the primary key of the underlying table is in the view and the row appears only once in the view. This means Oracle can figure out exactly which underlying table row to update OR
  2. You write an instead of trigger.

I would stay away from instead-of triggers and get your code to update the underlying tables directly rather than through the view.

How to register multiple servlets in web.xml in one Spring application

I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.

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

if (num < 0) {
  //negative
}
if (num > 0) {
  //positive
}
if (num == 0) {
  //neither positive or negative,
}

or use "else ifs"

Can a java lambda have more than 1 parameter?

It's possible if you define such a functional interface with multiple type parameters. There is no such built in type. (There are a few limited types with multiple parameters.)

@FunctionalInterface
interface Function6<One, Two, Three, Four, Five, Six> {
    public Six apply(One one, Two two, Three three, Four four, Five five);
}

public static void main(String[] args) throws Exception {
    Function6<String, Integer, Double, Void, List<Float>, Character> func = (a, b, c, d, e) -> 'z';
}

I've called it Function6 here. The name is at your discretion, just try not to clash with existing names in the Java libraries.


There's also no way to define a variable number of type parameters, if that's what you were asking about.


Some languages, like Scala, define a number of built in such types, with 1, 2, 3, 4, 5, 6, etc. type parameters.

JavaScript calculate the day of the year (1 - 366)

I've made one that's readable and will do the trick very quickly, as well as handle JS Date objects with disparate time zones.

I've included quite a few test cases for time zones, DST, leap seconds and Leap years.

P.S. ECMA-262 ignores leap seconds, unlike UTC. If you were to convert this to a language that uses real UTC, you could just add 1 to oneDay.

_x000D_
_x000D_
// returns 1 - 366_x000D_
findDayOfYear = function (date) {_x000D_
  var oneDay = 1000 * 60 * 60 * 24; // A day in milliseconds_x000D_
  var og = {                        // Saving original data_x000D_
    ts: date.getTime(),_x000D_
    dom: date.getDate(),            // We don't need to save hours/minutes because DST is never at 12am._x000D_
    month: date.getMonth()_x000D_
  }_x000D_
  date.setDate(1);                  // Sets Date of the Month to the 1st._x000D_
  date.setMonth(0);                 // Months are zero based in JS's Date object_x000D_
  var start_ts = date.getTime();    // New Year's Midnight JS Timestamp_x000D_
  var diff = og.ts - start_ts;_x000D_
_x000D_
  date.setDate(og.dom);             // Revert back to original date object_x000D_
  date.setMonth(og.month);          // This method does preserve timezone_x000D_
  return Math.round(diff / oneDay) + 1; // Deals with DST globally. Ceil fails in Australia. Floor Fails in US._x000D_
}_x000D_
_x000D_
// Tests_x000D_
var pre_start_dst = new Date(2016, 2, 12);_x000D_
var on_start_dst = new Date(2016, 2, 13);_x000D_
var post_start_dst = new Date(2016, 2, 14);_x000D_
_x000D_
var pre_end_dst_date = new Date(2016, 10, 5);_x000D_
var on_end_dst_date = new Date(2016, 10, 6);_x000D_
var post_end_dst_date = new Date(2016, 10, 7);_x000D_
_x000D_
var pre_leap_second = new Date(2015, 5, 29);_x000D_
var on_leap_second = new Date(2015, 5, 30);_x000D_
var post_leap_second = new Date(2015, 6, 1);_x000D_
_x000D_
// 2012 was a leap year with a leap second in june 30th_x000D_
var leap_second_december31_premidnight = new Date(2012, 11, 31, 23, 59, 59, 999);_x000D_
_x000D_
var january1 = new Date(2016, 0, 1);_x000D_
var january31 = new Date(2016, 0, 31);_x000D_
_x000D_
var december31 = new Date(2015, 11, 31);_x000D_
var leap_december31 = new Date(2016, 11, 31);_x000D_
_x000D_
alert( ""_x000D_
  + "\nPre Start DST: " + findDayOfYear(pre_start_dst) + " === 72"_x000D_
  + "\nOn Start DST: " + findDayOfYear(on_start_dst) + " === 73"_x000D_
  + "\nPost Start DST: " + findDayOfYear(post_start_dst) + " === 74"_x000D_
      _x000D_
  + "\nPre Leap Second: " + findDayOfYear(pre_leap_second) + " === 180"_x000D_
  + "\nOn Leap Second: " + findDayOfYear(on_leap_second) + " === 181"_x000D_
  + "\nPost Leap Second: " + findDayOfYear(post_leap_second) + " === 182"_x000D_
      _x000D_
  + "\nPre End DST: " + findDayOfYear(pre_end_dst_date) + " === 310"_x000D_
  + "\nOn End DST: " + findDayOfYear(on_end_dst_date) + " === 311"_x000D_
  + "\nPost End DST: " + findDayOfYear(post_end_dst_date) + " === 312"_x000D_
      _x000D_
  + "\nJanuary 1st: " + findDayOfYear(january1) + " === 1"_x000D_
  + "\nJanuary 31st: " + findDayOfYear(january31) + " === 31"_x000D_
  + "\nNormal December 31st: " + findDayOfYear(december31) + " === 365"_x000D_
  + "\nLeap December 31st: " + findDayOfYear(leap_december31) + " === 366"_x000D_
  + "\nLast Second of Double Leap: " + findDayOfYear(leap_second_december31_premidnight) + " === 366"_x000D_
);
_x000D_
_x000D_
_x000D_

What is the default value for Guid?

You can use Guid.Empty. It is a read-only instance of the Guid structure with the value of 00000000-0000-0000-0000-000000000000

you can also use these instead

var g = new Guid();
var g = default(Guid);

beware not to use Guid.NewGuid() because it will generate a new Guid.

use one of the options above which you and your team think it is more readable and stick to it. Do not mix different options across the code. I think the Guid.Empty is the best one since new Guid() might make us think it is generating a new guid and some may not know what is the value of default(Guid).

How to initialize private static members in C++?

You can also include the assignment in the header file if you use header guards. I have used this technique for a C++ library I have created. Another way to achieve the same result is to use static methods. For example...

class Foo
   {
   public:
     int GetMyStatic() const
     {
       return *MyStatic();
     }

   private:
     static int* MyStatic()
     {
       static int mStatic = 0;
       return &mStatic;
     }
   }

The above code has the "bonus" of not requiring a CPP/source file. Again, a method I use for my C++ libraries.

How to get Wikipedia content using Wikipedia's API?

You can download the Wikipedia database directly and parse all pages to XML with Wiki Parser, which is a standalone application. The first paragraph is a separate node in the resulting XML.

Alternatively, you can extract the first paragraph from its plain-text output.

Laravel - Pass more than one variable to view

Use compact

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();
    return View::make('users', compact('ms','persons'));
}

npm ERR cb() never called

For me on npm 6.4.0 and node 10.9.0 none of the answers worked. Reinstalled node, npm, cleaned cache, removed folders ...

After some debugging it turned out I used npm link for two of my modules under development to link to each other. Once I removed and redid some linking I was able to get it all working again.

Serialize an object to string

Code Safety Note

Regarding the accepted answer, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible scenarios, while using the latter one fails sometimes.

Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject<T>() that is defined in the derived type's base class: http://ideone.com/1Z5J1. Note that Ideone uses Mono to execute code: the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.

For the sake of completeness I post the full code sample here for future reference, just in case Ideone (where I posted the code) becomes unavailable in the future:

using System;
using System.Xml.Serialization;
using System.IO;

public class Test
{
    public static void Main()
    {
        Sub subInstance = new Sub();
        Console.WriteLine(subInstance.TestMethod());
    }

    public class Super
    {
        public string TestMethod() {
            return this.SerializeObject();
        }
    }

    public class Sub : Super
    {
    }
}

public static class TestExt {
    public static string SerializeObject<T>(this T toSerialize)
    {
        Console.WriteLine(typeof(T).Name);             // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead
        Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringWriter textWriter = new StringWriter();

        // And now...this will throw and Exception!
        // Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType()); 
        // solves the problem
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}

Add 2 hours to current time in MySQL?

SELECT * FROM courses WHERE (NOW() + INTERVAL 2 HOUR) > start_time

Why do we need middleware for async flow in Redux?

What is wrong with this approach? Why would I want to use Redux Thunk or Redux Promise, as the documentation suggests?

There is nothing wrong with this approach. It’s just inconvenient in a large application because you’ll have different components performing the same actions, you might want to debounce some actions, or keep some local state like auto-incrementing IDs close to action creators, etc. So it is just easier from the maintenance point of view to extract action creators into separate functions.

You can read my answer to “How to dispatch a Redux action with a timeout” for a more detailed walkthrough.

Middleware like Redux Thunk or Redux Promise just gives you “syntax sugar” for dispatching thunks or promises, but you don’t have to use it.

So, without any middleware, your action creator might look like

// action creator
function loadData(dispatch, userId) { // needs to dispatch, so it is first argument
  return fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_DATA_FAILURE', err })
    );
}

// component
componentWillMount() {
  loadData(this.props.dispatch, this.props.userId); // don't forget to pass dispatch
}

But with Thunk Middleware you can write it like this:

// action creator
function loadData(userId) {
  return dispatch => fetch(`http://data.com/${userId}`) // Redux Thunk handles these
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_DATA_FAILURE', err })
    );
}

// component
componentWillMount() {
  this.props.dispatch(loadData(this.props.userId)); // dispatch like you usually do
}

So there is no huge difference. One thing I like about the latter approach is that the component doesn’t care that the action creator is async. It just calls dispatch normally, it can also use mapDispatchToProps to bind such action creator with a short syntax, etc. The components don’t know how action creators are implemented, and you can switch between different async approaches (Redux Thunk, Redux Promise, Redux Saga) without changing the components. On the other hand, with the former, explicit approach, your components know exactly that a specific call is async, and needs dispatch to be passed by some convention (for example, as a sync parameter).

Also think about how this code will change. Say we want to have a second data loading function, and to combine them in a single action creator.

With the first approach we need to be mindful of what kind of action creator we are calling:

// action creators
function loadSomeData(dispatch, userId) {
  return fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
    );
}
function loadOtherData(dispatch, userId) {
  return fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_OTHER_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_OTHER_DATA_FAILURE', err })
    );
}
function loadAllData(dispatch, userId) {
  return Promise.all(
    loadSomeData(dispatch, userId), // pass dispatch first: it's async
    loadOtherData(dispatch, userId) // pass dispatch first: it's async
  );
}


// component
componentWillMount() {
  loadAllData(this.props.dispatch, this.props.userId); // pass dispatch first
}

With Redux Thunk action creators can dispatch the result of other action creators and not even think whether those are synchronous or asynchronous:

// action creators
function loadSomeData(userId) {
  return dispatch => fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
    );
}
function loadOtherData(userId) {
  return dispatch => fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_OTHER_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_OTHER_DATA_FAILURE', err })
    );
}
function loadAllData(userId) {
  return dispatch => Promise.all(
    dispatch(loadSomeData(userId)), // just dispatch normally!
    dispatch(loadOtherData(userId)) // just dispatch normally!
  );
}


// component
componentWillMount() {
  this.props.dispatch(loadAllData(this.props.userId)); // just dispatch normally!
}

With this approach, if you later want your action creators to look into current Redux state, you can just use the second getState argument passed to the thunks without modifying the calling code at all:

function loadSomeData(userId) {
  // Thanks to Redux Thunk I can use getState() here without changing callers
  return (dispatch, getState) => {
    if (getState().data[userId].isLoaded) {
      return Promise.resolve();
    }

    fetch(`http://data.com/${userId}`)
      .then(res => res.json())
      .then(
        data => dispatch({ type: 'LOAD_SOME_DATA_SUCCESS', data }),
        err => dispatch({ type: 'LOAD_SOME_DATA_FAILURE', err })
      );
  }
}

If you need to change it to be synchronous, you can also do this without changing any calling code:

// I can change it to be a regular action creator without touching callers
function loadSomeData(userId) {
  return {
    type: 'LOAD_SOME_DATA_SUCCESS',
    data: localStorage.getItem('my-data')
  }
}

So the benefit of using middleware like Redux Thunk or Redux Promise is that components aren’t aware of how action creators are implemented, and whether they care about Redux state, whether they are synchronous or asynchronous, and whether or not they call other action creators. The downside is a little bit of indirection, but we believe it’s worth it in real applications.

Finally, Redux Thunk and friends is just one possible approach to asynchronous requests in Redux apps. Another interesting approach is Redux Saga which lets you define long-running daemons (“sagas”) that take actions as they come, and transform or perform requests before outputting actions. This moves the logic from action creators into sagas. You might want to check it out, and later pick what suits you the most.

I searched the Redux repo for clues, and found that Action Creators were required to be pure functions in the past.

This is incorrect. The docs said this, but the docs were wrong.
Action creators were never required to be pure functions.
We fixed the docs to reflect that.

How to convert a string into double and vice versa?

convert text entered in textfield to integer

double mydouble=[_myTextfield.text doubleValue];

rounding to the nearest double

mydouble=(round(mydouble));

rounding to the nearest int(considering only positive values)

int myint=(int)(mydouble);

converting from double to string

myLabel.text=[NSString stringWithFormat:@"%f",mydouble];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];

converting from int to string

myLabel.text=[NSString stringWithFormat:@"%d",myint];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];

SimpleDateFormat and locale based format string

Localization of date string:

Based on redsonic's post:

private String localizeDate(String inputdate, Locale locale) { 

    Date date = new Date();
    SimpleDateFormat dateFormatCN = new SimpleDateFormat("dd-MMM-yyyy", locale);       
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");


    try {
        date = dateFormat.parse(inputdate);
    } catch (ParseException e) {
        log.warn("Input date was not correct. Can not localize it.");
        return inputdate;
    }
    return dateFormatCN.format(date);
}

String localizedDate = localizeDate("05-Sep-2013", new Locale("zh","CN"));

will be like 05-??-2013

How can we generate getters and setters in Visual Studio?

In Visual Studio Community Edition 2015 you can select all the fields you want and then press Ctrl + . to automatically generate the properties.

You have to choose if you want to use the property instead of the field or not.

Url.Action parameters?

This works for MVC 5:

<a href="@Url.Action("ActionName", "ControllerName", new { paramName1 = item.paramValue1, paramName2 = item.paramValue2 })" >
    Link text
</a>

Java Web Service client basic authentication

If you use JAX-WS, the following works for me:

    //Get Web service Port
    WSTestService wsService = new WSTestService();
    WSTest wsPort = wsService.getWSTestPort();

    // Add username and password for Basic Authentication
    Map<String, Object> reqContext = ((BindingProvider) 
         wsPort).getRequestContext();
    reqContext.put(BindingProvider.USERNAME_PROPERTY, "username");
        reqContext.put(BindingProvider.PASSWORD_PROPERTY, "password");

How to select a record and update it, with a single queryset in Django?

If you need to set the new value based on the old field value that is do something like:

update my_table set field_1 = field_1 + 1 where pk_field = some_value

use query expressions:

MyModel.objects.filter(pk=some_value).update(field1=F('field1') + 1)

This will execute update atomically that is using one update request to the database without reading it first.

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

I coded up an equivalent C program to experiment, and I can confirm this strange behaviour. What's more, gcc believes the 64-bit integer (which should probably be a size_t anyway...) to be better, as using uint_fast32_t causes gcc to use a 64-bit uint.

I did a bit of mucking around with the assembly:
Simply take the 32-bit version, replace all 32-bit instructions/registers with the 64-bit version in the inner popcount-loop of the program. Observation: the code is just as fast as the 32-bit version!

This is obviously a hack, as the size of the variable isn't really 64 bit, as other parts of the program still use the 32-bit version, but as long as the inner popcount-loop dominates performance, this is a good start.

I then copied the inner loop code from the 32-bit version of the program, hacked it up to be 64 bit, fiddled with the registers to make it a replacement for the inner loop of the 64-bit version. This code also runs as fast as the 32-bit version.

My conclusion is that this is bad instruction scheduling by the compiler, not actual speed/latency advantage of 32-bit instructions.

(Caveat: I hacked up assembly, could have broken something without noticing. I don't think so.)

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

Select elements by attribute in CSS

If you mean using an attribute selector, sure, why not:

[data-role="page"] {
    /* Styles */
}

There are a variety of attribute selectors you can use for various scenarios which are all covered in the document I link to. Note that, despite custom data attributes being a "new HTML5 feature",

  • browsers typically don't have any problems supporting non-standard attributes, so you should be able to filter them with attribute selectors; and

  • you don't have to worry about CSS validation either, as CSS doesn't care about non-namespaced attribute names as long as they don't break the selector syntax.

How to fade changing background image

Opacity serves your purpose?

If so, try this:

$('#elem').css('opacity','0.3')

how to reset <input type = "file">

This could be done like this

_x000D_
_x000D_
var inputfile= $('#uploadCaptureInputFile')_x000D_
$('#reset').on('click',function(){_x000D_
inputfile.replaceWith(inputfile.val('').clone(true));_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="file" id="uploadCaptureInputFile" class="win-content colors" accept="image/*" />_x000D_
<a href="" id="reset">Reset</a>
_x000D_
_x000D_
_x000D_

jQuery select option elements by value

To get the value just use this:

<select id ="ari_select" onchange = "getvalue()">
<option value = "1"></option>
<option value = "2"></option>
<option value = "3"></option>
<option value = "4"></option>
</select>

<script>
function getvalue()
{
    alert($("#ari_select option:selected").val()); 
}
</script>

this will fetch the values

How to delete a whole folder and content?

Safest code I know:

private boolean recursiveRemove(File file) {
    if(file == null  || !file.exists()) {
        return false;
    }

    if(file.isDirectory()) {
        File[] list = file.listFiles();

        if(list != null) {

            for(File item : list) {
                recursiveRemove(item);
            }

        }
    }

    if(file.exists()) {
        file.delete();
    }

    return !file.exists();
}

Checks the file exists, handles nulls, checks the directory was actually deleted

How to force ViewPager to re-instantiate its items

I have found a solution. It is just a workaround to my problem but currently the only solution.

ViewPager PagerAdapter not updating the View

public int getItemPosition(Object object) {
   return POSITION_NONE;
}

Does anyone know whether this is a bug or not?

Eclipse error: indirectly referenced from required .class files?

It happens to me sometimes, I always fixed that with "mvn eclipse:clean" command to clean old properties and then run mvn eclipse:eclipse -Dwtpversion=2.0 (for web project of course). There are some old properties saved so eclipse is confused sometimes.

How to clear/delete the contents of a Tkinter Text widget?

A lot of answers ask you to use END, but if that's not working for you, try:

text.delete("1.0", "end-1c")

How to find whether or not a variable is empty in Bash?

I have also seen

if [ "x$variable" = "x" ]; then ...

which is obviously very robust and shell independent.

Also, there is a difference between "empty" and "unset". See How to tell if a string is not defined in a Bash shell script.

The developers of this app have not set up this app properly for Facebook Login?

Set LoginBehavior if you have installed facebook app in your phone

loginButton.setLoginBehavior(LoginBehavior.WEB_ONLY);

MongoDB running but can't connect using shell

If your mongoDB server(remote server)'s version is greater then 4.0.3, then you will face this issue. Hence you should replace your current mongo-client shell with below mongo :

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org

Then you mongo client will be able to connect your remove mongodb

What is the purpose of meshgrid in Python / NumPy?

The purpose of meshgrid is to create a rectangular grid out of an array of x values and an array of y values.

So, for example, if we want to create a grid where we have a point at each integer value between 0 and 4 in both the x and y directions. To create a rectangular grid, we need every combination of the x and y points.

This is going to be 25 points, right? So if we wanted to create an x and y array for all of these points, we could do the following.

x[0,0] = 0    y[0,0] = 0
x[0,1] = 1    y[0,1] = 0
x[0,2] = 2    y[0,2] = 0
x[0,3] = 3    y[0,3] = 0
x[0,4] = 4    y[0,4] = 0
x[1,0] = 0    y[1,0] = 1
x[1,1] = 1    y[1,1] = 1
...
x[4,3] = 3    y[4,3] = 4
x[4,4] = 4    y[4,4] = 4

This would result in the following x and y matrices, such that the pairing of the corresponding element in each matrix gives the x and y coordinates of a point in the grid.

x =   0 1 2 3 4        y =   0 0 0 0 0
      0 1 2 3 4              1 1 1 1 1
      0 1 2 3 4              2 2 2 2 2
      0 1 2 3 4              3 3 3 3 3
      0 1 2 3 4              4 4 4 4 4

We can then plot these to verify that they are a grid:

plt.plot(x,y, marker='.', color='k', linestyle='none')

enter image description here

Obviously, this gets very tedious especially for large ranges of x and y. Instead, meshgrid can actually generate this for us: all we have to specify are the unique x and y values.

xvalues = np.array([0, 1, 2, 3, 4]);
yvalues = np.array([0, 1, 2, 3, 4]);

Now, when we call meshgrid, we get the previous output automatically.

xx, yy = np.meshgrid(xvalues, yvalues)

plt.plot(xx, yy, marker='.', color='k', linestyle='none')

enter image description here

Creation of these rectangular grids is useful for a number of tasks. In the example that you have provided in your post, it is simply a way to sample a function (sin(x**2 + y**2) / (x**2 + y**2)) over a range of values for x and y.

Because this function has been sampled on a rectangular grid, the function can now be visualized as an "image".

enter image description here

Additionally, the result can now be passed to functions which expect data on rectangular grid (i.e. contourf)

Android ADB commands to get the device properties

adb shell getprop ro.build.version.sdk

If you want to see the whole list of parameters just type:

adb shell getprop

How can I search sub-folders using glob.glob module?

configfiles = glob.glob('C:/Users/sam/Desktop/**/*.txt")

Doesn't works for all cases, instead use glob2

configfiles = glob2.glob('C:/Users/sam/Desktop/**/*.txt")

Task<> does not contain a definition for 'GetAwaiter'

The Problem Occur Because the application I was using and the dll i added to my application both have different Versions.

Add this Package- Install-Package Microsoft.Bcl.Async -Version 1.0.168

ADDING THIS PACKAGE async Code becomes Compatible in version 4.0 as well, because Async only work on applications whose Versions are more than or equal to 4.5

How do I convert a float number to a whole number in JavaScript?

One more possible way — use XOR operation:

_x000D_
_x000D_
console.log(12.3 ^ 0); // 12
console.log("12.3" ^ 0); // 12
console.log(1.2 + 1.3 ^ 0); // 2
console.log(1.2 + 1.3 * 2 ^ 0); // 3
console.log(-1.2 ^ 0); // -1
console.log(-1.2 + 1 ^ 0); // 0
console.log(-1.2 - 1.3 ^ 0); // -2
_x000D_
_x000D_
_x000D_

Priority of bitwise operations is less then priority of math operations, it's useful. Try on https://jsfiddle.net/au51uj3r/

Why is System.Web.Mvc not listed in Add References?

Check these step:

  1. Check MVC is installed properly.
  2. Check the project's property and see what is the project Target Framework. If the target framework is not set to .Net Framework 4, set it.

Note: if target framework is set to .Net Framework 4 Client Profile, it will not list MVC reference on references list. You can find different between .Net Framework 4 and .Net Framework 4 Client Profile here.

The .NET Framework 4 Client Profile is a subset of the .NET Framework 4 that is optimized for client applications. It provides functionality for most client applications, including Windows Presentation Foundation (WPF), Windows Forms, Windows Communication Foundation (WCF), and ClickOnce features. This enables faster deployment and a smaller install package for applications that target the .NET Framework 4 Client Profile.

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Make sure the user you are using to access your database has the privileges to do so.
GRANT ALL PRIVILEGES ON * . * TO 'user'@'localhost';
Where the first star can be replaced by database name, second star specifies table. Make sure to flush privileges after.

set dropdown value by text using jquery

For GOOGLE, GOOGLEDOWN, GOOGLEUP i.e similar kind of value you can try below code

   $("#HowYouKnow option:contains('GOOGLE')").each(function () {

                        if($(this).html()=='GOOGLE'){
                            $(this).attr('selected', 'selected');
                        }
                    });

In this way,number of loop iteration can be reduced and will work in all situation.

Java: Simplest way to get last word in a string

String test =  "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);

Java Inheritance - calling superclass method

You can do:

super.alphaMethod1();

Note, that super is a reference to the parent, but super() is it's constructor.

How to track untracked content?

I just had the same problem. The reason was because there was a subfolder that contained a ".git" folder. Removing it made git happy.

Horizontal ListView in Android?

I've done a lot of searching for a solution to this problem. The short answer is, there is no good solution, without overriding private methods and that sort of thing. The best thing I found was to implement it myself from scratch by extending AdapterView. It's pretty miserable. See my SO question about horizontal ListViews.

Regex to get string between curly braces

Try this

let path = "/{id}/{name}/{age}";
const paramsPattern = /[^{\}]+(?=})/g;
let extractParams = path.match(paramsPattern);
console.log("extractParams", extractParams) // prints all the names between {} = ["id", "name", "age"]

What is an Android PendingIntent?

PendingIntent is basically an object that wraps another Intent object. Then it can be passed to a foreign application where you’re granting that app the right to perform the operation, i.e., execute the intent as if it were executed from your own app’s process (same permission and identity). For security reasons you should always pass explicit intents to a PendingIntent rather than being implicit.

 PendingIntent aPendingIntent = PendingIntent.getService(Context, 0, aIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

Convert text into number in MySQL query

This should work:

SELECT field,CONVERT(SUBSTRING_INDEX(field,'-',-1),UNSIGNED INTEGER) AS num
FROM table
ORDER BY num;

No shadow by default on Toolbar?

If you are seting the ToolBar as ActionBar then just call:

getSupportActionBar().setElevation(YOUR_ELEVATION);

Note: This must be called after setSupportActionBar(toolbar);

What is the iBeacon Bluetooth Profile

For an iBeacon with ProximityUUID E2C56DB5-DFFB-48D2-B060-D0F5A71096E0, major 0, minor 0, and calibrated Tx Power of -59 RSSI, the transmitted BLE advertisement packet looks like this:

d6 be 89 8e 40 24 05 a2 17 6e 3d 71 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 52 ab 8d 38 a5

This packet can be broken down as follows:

d6 be 89 8e # Access address for advertising data (this is always the same fixed value)
40 # Advertising Channel PDU Header byte 0.  Contains: (type = 0), (tx add = 1), (rx add = 0)
24 # Advertising Channel PDU Header byte 1.  Contains:  (length = total bytes of the advertising payload + 6 bytes for the BLE mac address.)
05 a2 17 6e 3d 71 # Bluetooth Mac address (note this is a spoofed address)
02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 # Bluetooth advertisement
52 ab 8d 38 a5 # checksum

The key part of that packet is the Bluetooth Advertisement, which can be broken down like this:

02 # Number of bytes that follow in first AD structure
01 # Flags AD type
1A # Flags value 0x1A = 000011010  
   bit 0 (OFF) LE Limited Discoverable Mode
   bit 1 (ON) LE General Discoverable Mode
   bit 2 (OFF) BR/EDR Not Supported
   bit 3 (ON) Simultaneous LE and BR/EDR to Same Device Capable (controller)
   bit 4 (ON) Simultaneous LE and BR/EDR to Same Device Capable (Host)
1A # Number of bytes that follow in second (and last) AD structure
FF # Manufacturer specific data AD type
4C 00 # Company identifier code (0x004C == Apple)
02 # Byte 0 of iBeacon advertisement indicator
15 # Byte 1 of iBeacon advertisement indicator
e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 # iBeacon proximity uuid
00 00 # major 
00 00 # minor 
c5 # The 2's complement of the calibrated Tx Power

Any Bluetooth LE device that can be configured to send a specific advertisement can generate the above packet. I have configured a Linux computer using Bluez to send this advertisement, and iOS7 devices running Apple's AirLocate test code pick it up as an iBeacon with the fields specified above. See: Use BlueZ Stack As A Peripheral (Advertiser)

This blog has full details about the reverse engineering process.

How does @synchronized lock/unlock in Objective-C?

It just associates a semaphore with every object, and uses that.

Python: pandas merge multiple dataframes

Look at this pandas three-way joining multiple dataframes on columns

filenames = ['fn1', 'fn2', 'fn3', 'fn4',....]
dfs = [pd.read_csv(filename, index_col=index_col) for filename in filenames)]
dfs[0].join(dfs[1:])

How do I convert ticks to minutes?

The clearest way in my view is to use TimeSpan.FromTicks and then convert that to minutes:

TimeSpan ts = TimeSpan.FromTicks(ticks);
double minutes = ts.TotalMinutes;

How to set OnClickListener on a RadioButton in Android?

I'd think a better way is to use RadioGroup and set the listener on this to change and update the View accordingly (saves you having 2 or 3 or 4 etc listeners).

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);        
    radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() 
    {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected
        }
    });

Any way to exit bash script, but not quitting the terminal

Also make sure to return with expected return value. Else if you use exit when you will encounter an exit it will exit from your base shell since source does not create another process (instance).

Return multiple values in JavaScript?

No, but you could return an array containing your values:

function getValues() {
    return [getFirstValue(), getSecondValue()];
}

Then you can access them like so:

var values = getValues();
var first = values[0];
var second = values[1];

With the latest ECMAScript 6 syntax*, you can also destructure the return value more intuitively:

const [first, second] = getValues();

If you want to put "labels" on each of the returned values (easier to maintain), you can return an object:

function getValues() {
    return {
        first: getFirstValue(),
        second: getSecondValue(),
    };
}

And to access them:

var values = getValues();
var first = values.first;
var second = values.second;

Or with ES6 syntax:

const {first, second} = getValues();

* See this table for browser compatibility. Basically, all modern browsers aside from IE support this syntax, but you can compile ES6 code down to IE-compatible JavaScript at build time with tools like Babel.

How can I use Guzzle to send a POST request in JSON?

$client = new \GuzzleHttp\Client();

$body['grant_type'] = "client_credentials";
$body['client_id'] = $this->client_id;
$body['client_secret'] = $this->client_secret;

$res = $client->post($url, [ 'body' => json_encode($body) ]);

$code = $res->getStatusCode();
$result = $res->json();

Saving a Numpy array as an image

An answer using PIL (just in case it's useful).

given a numpy array "A":

from PIL import Image
im = Image.fromarray(A)
im.save("your_file.jpeg")

you can replace "jpeg" with almost any format you want. More details about the formats here

How do I concatenate two strings in C?

I'll assume you need it for one-off things. I'll assume you're a PC developer.

Use the Stack, Luke. Use it everywhere. Don't use malloc / free for small allocations, ever.

#include <string.h>
#include <stdio.h>

#define STR_SIZE 10000

int main()
{
  char s1[] = "oppa";
  char s2[] = "gangnam";
  char s3[] = "style";

  {
    char result[STR_SIZE] = {0};
    snprintf(result, sizeof(result), "%s %s %s", s1, s2, s3);
    printf("%s\n", result);
  }
}

If 10 KB per string won't be enough, add a zero to the size and don't bother, - they'll release their stack memory at the end of the scopes anyway.

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

How to get current html page title with javascript

try like this

$('title').text();

Spring cron expression for every after 30 minutes

If someone is using @Sceduled this might work for you.

@Scheduled(cron = "${name-of-the-cron:0 0/30 * * * ?}")

This worked for me.

How to print Unicode character in Python?

To include Unicode characters in your Python source code, you can use Unicode escape characters in the form \u0123 in your string. In Python 2.x, you also need to prefix the string literal with 'u'.

Here's an example running in the Python 2.x interactive console:

>>> print u'\u0420\u043e\u0441\u0441\u0438\u044f'
??????

In Python 2, prefixing a string with 'u' declares them as Unicode-type variables, as described in the Python Unicode documentation.

In Python 3, the 'u' prefix is now optional:

>>> print('\u0420\u043e\u0441\u0441\u0438\u044f')
??????

If running the above commands doesn't display the text correctly for you, perhaps your terminal isn't capable of displaying Unicode characters.

These examples use Unicode escapes (\u...), which allows you to print Unicode characters while keeping your source code as plain ASCII. This can help when working with the same source code on different systems. You can also use Unicode characters directly in your Python source code (e.g. print u'??????' in Python 2), if you are confident all your systems handle Unicode files properly.

For information about reading Unicode data from a file, see this answer:

Character reading from file in Python

Change Default branch in gitlab

For GitLab 11.5.0-ee, go to https://gitlab.com/<username>/<project name>/settings/repository.

You should see:

Default Branch

Select the branch you want to set as the default for this project. All merge requests and commits will automatically be made against this branch unless you specify a different one.

Click Expand, select a branch, and click Save Changes.

Typedef function pointer?

typedef is a language construct that associates a name to a type.
You use it the same way you would use the original type, for instance

  typedef int myinteger;
  typedef char *mystring;
  typedef void (*myfunc)();

using them like

  myinteger i;   // is equivalent to    int i;
  mystring s;    // is the same as      char *s;
  myfunc f;      // compile equally as  void (*f)();

As you can see, you could just replace the typedefed name with its definition given above.

The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.

The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.

To answer your three questions

  • Why is typedef used? To ease the reading of the code - especially for pointers to functions, or structure names.

  • The syntax looks odd (in the pointer to function declaration) That syntax is not obvious to read, at least when beginning. Using a typedef declaration instead eases the reading

  • Is a function pointer created to store the memory address of a function? Yes, a function pointer stores the address of a function. This has nothing to do with the typedef construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.

Example:

typedef int (*t_somefunc)(int,int);

int product(int u, int v) {
  return u*v;
}

t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456

Passing Variable through JavaScript from one html page to another page

Without reading your code but just your scenario, I would solve by using localStorage. Here's an example, I'll use prompt() for short.

On page1:

window.onload = function() {
   var getInput = prompt("Hey type something here: ");
   localStorage.setItem("storageName",getInput);
}

On page2:

window.onload = alert(localStorage.getItem("storageName"));

You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

You could use the add-on module for Jackson which handles Hibernate lazy-loading.

More info on https://github.com/FasterXML/jackson-datatype-hibernate wich support hibernate 3 and 4 separately.

How to check variable type at runtime in Go language

See type assertions here:

http://golang.org/ref/spec#Type_assertions

I'd assert a sensible type (string, uint64) etc only and keep it as loose as possible, performing a conversion to the native type last.

Print Html template in Angular 2 (ng-print in Angular 2)

That's how I've done it in angular2 (it is similar to that plunkered solution) In your HTML file:

<div id="print-section">
  // your html stuff that you want to print
</div>
<button (click)="print()">print</button>

and in your TS file :

print(): void {
    let printContents, popupWin;
    printContents = document.getElementById('print-section').innerHTML;
    popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    popupWin.document.open();
    popupWin.document.write(`
      <html>
        <head>
          <title>Print tab</title>
          <style>
          //........Customized style.......
          </style>
        </head>
    <body onload="window.print();window.close()">${printContents}</body>
      </html>`
    );
    popupWin.document.close();
}

UPDATE:

You can also shortcut the path and use merely ngx-print library for less inconsistent coding (mixing JS and TS) and more out-of-the-box controllable and secured printing cases.

How to select records without duplicate on just one field in SQL?

select Country_id,country_title from(
   select Country_id,country_title,row_number() over (partition by country_title 
   order by Country_id  ) rn from country)a
   where rn=1;

How to convert Javascript datetime to C# datetime?

UPDATE: From .NET Version 4.6 use the FromUnixTimeMilliseconds method of the DateTimeOffset structure instead:

DateTimeOffset.FromUnixTimeMilliseconds(1310522400000).DateTime

How can I build XML in C#?

In the past I have created my XML Schema, then used a tool to generate C# classes which will serialize to that schema. The XML Schema Definition Tool is one example

http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx

SQL Server insert if not exists best practice

Ok, this was asked 7 years ago, but I think the best solution here is to forego the new table entirely and just do this as a custom view. That way you're not duplicating data, there's no worry about unique data, and it doesn't touch the actual database structure. Something like this:

CREATE VIEW vw_competitions
  AS
  SELECT
   Id int
   CompetitionName nvarchar(75)
   CompetitionType nvarchar(50)
   OtherField1 int
   OtherField2 nvarchar(64)  --add the fields you want viewed from the Competition table
  FROM Competitions
GO

Other items can be added here like joins on other tables, WHERE clauses, etc. This is most likely the most elegant solution to this problem, as you now can just query the view:

SELECT *
FROM vw_competitions

...and add any WHERE, IN, or EXISTS clauses to the view query.

Mask for an Input to allow phone numbers?

Angular5 and 6:

angular 5 and 6 recommended way is to use @HostBindings and @HostListeners instead of the host property

remove host and add @HostListener

 @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event, false);
  }

  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event) {
    this.onInputChange(event.target.value, true);
  }

Working Online stackblitz Link: https://angular6-phone-mask.stackblitz.io

Stackblitz Code example: https://stackblitz.com/edit/angular6-phone-mask

Official documentation link https://angular.io/guide/attribute-directives#respond-to-user-initiated-events

Angular2 and 4:

Plunker >= RC.5

original

One way you could do it is using a directive that injects NgControl and manipulates the value

(for details see inline comments)

@Directive({
  selector: '[ngModel][phone]',
  host: {
    '(ngModelChange)': 'onInputChange($event)',
    '(keydown.backspace)': 'onInputChange($event.target.value, true)'
  }
})
export class PhoneMask {
  constructor(public model: NgControl) {}

  onInputChange(event, backspace) {
    // remove all mask characters (keep only numeric)
    var newVal = event.replace(/\D/g, '');
    // special handling of backspace necessary otherwise
    // deleting of non-numeric characters is not recognized
    // this laves room for improvement for example if you delete in the 
    // middle of the string
    if (backspace) {
      newVal = newVal.substring(0, newVal.length - 1);
    } 

    // don't show braces for empty value
    if (newVal.length == 0) {
      newVal = '';
    } 
    // don't show braces for empty groups at the end
    else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '($1)');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) ($2)');
    } else {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) ($2)-$3');
    }
    // set the new value
    this.model.valueAccessor.writeValue(newVal);       
  }
}
@Component({
  selector: 'my-app',
  providers: [],
  template: `
  <form [ngFormModel]="form">
    <input type="text" phone [(ngModel)]="data" ngControl="phone"> 
  </form>
  `,
  directives: [PhoneMask]
})
export class App {
  constructor(fb: FormBuilder) {
    this.form = fb.group({
      phone: ['']
    })
  }
}

Plunker example <= RC.5

what do <form action="#"> and <form method="post" action="#"> do?

Action normally specifies the file/page that the form is submitted to (using the method described in the method paramater (post, get etc.))

An action of # indicates that the form stays on the same page, simply suffixing the url with a #. Similar use occurs in anchors. <a href=#">Link</a> for example, will stay on the same page.

Thus, the form is submitted to the same page, which then processes the data etc.

Lost connection to MySQL server during query?

I encountered similar problems too. In my case it was solved by getting the cursor in this way:

cursor = self.conn.cursor(buffered=True)

Can someone explain mappedBy in JPA and Hibernate?

MappedBy signals hibernate that the key for the relationship is on the other side.

This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.

Google Maps how to Show city or an Area outline

i was looking for the same and found the answer,

solution is to use the styled map, on below link you can create your custom styles through wizard and test is at the same time google map style wizard

you can check all available options : here

here is my sample code which creates boundary for states and hide all the road and there labels.

    var styles = [
  {
    "featureType": "administrative.province",
    "elementType": "geometry.stroke",
    "stylers": [
      { "visibility": "on" },
      { "weight": 2.5 },
      { "color": "#24b0e2" }
    ]
  },{
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [
      { "visibility": "off" }
    ]
  },{
    "featureType": "administrative.locality",
    "stylers": [
      { "visibility": "off" }
    ]
  },{
    "featureType": "road",
    "elementType": "labels",
    "stylers": [
      { "visibility": "off" }
    ]
  }
];

  var  geocoder = new google.maps.Geocoder();
   geocoder.geocode({
       'address': "rajasthan"
   }, (results, status)=> {
     var mapOpts = {
       mapTypeId: google.maps.MapTypeId.ROADMAP,
       scaleControl: true,
       scrollwheel: false,
       styles:styles,
       center: results[0].geometry.location,
       zoom:6
     }
     map = new google.maps.Map(document.getElementById("map"), mapOpts);
   });

C# getting its own class name

For reference, if you have a type that inherits from another you can also use

this.GetType().BaseType.Name

Batch script: how to check for admin rights

Not only check but GETTING admin rights automatically
aka Automatic UAC for Win 7/8/8.1 ff.
: The following is a really cool one with one more feature: This batch snippet does not only check for admin rights, but gets them automatically! (and tests before, if living on an UAC capable OS.)

With this trick you don´t need longer to right klick on your batch file "with admin rights". If you have forgotten, to start it with elevated rights, UAC comes up automatically! Moreoever, at first it is tested, if the OS needs/provides UAC, so it behaves correct e.g. for Win 2000/XP until Win 8.1- tested.

@echo off
REM Quick test for Windows generation: UAC aware or not ; all OS before NT4 ignored for simplicity
SET NewOSWith_UAC=YES
VER | FINDSTR /IL "5." > NUL
IF %ERRORLEVEL% == 0 SET NewOSWith_UAC=NO
VER | FINDSTR /IL "4." > NUL
IF %ERRORLEVEL% == 0 SET NewOSWith_UAC=NO


REM Test if Admin
CALL NET SESSION >nul 2>&1
IF NOT %ERRORLEVEL% == 0 (

    if /i "%NewOSWith_UAC%"=="YES" (
        rem Start batch again with UAC
        echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
        echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
        "%temp%\getadmin.vbs"
        del "%temp%\getadmin.vbs"
        exit /B
    )

    rem Program will now start again automatically with admin rights! 
    rem pause
    goto :eof
)

The snippet merges some good batch patterns together, especially (1) the admin test in this thread by Ben Hooper and (2) the UAC activation read on BatchGotAdmin and cited on the batch site by robvanderwoude (respect). (3) For the OS identificaton by "VER | FINDSTR pattern" I just don't find the reference.)

(Concerning some very minor restrictions, when "NET SESSION" do not work as mentioned in another answer- feel free to insert another of those commands. For me running in Windows safe mode or special standard services down and such are not an important use cases- for some admins maybe they are.)

Get first row of dataframe in Python Pandas based on criteria

For the point that 'returns the value as soon as you find the first row/record that meets the requirements and NOT iterating other rows', the following code would work:

def pd_iter_func(df):
    for row in df.itertuples():
        # Define your criteria here
        if row.A > 4 and row.B > 3:
            return row

It is more efficient than Boolean Indexing when it comes to a large dataframe.

To make the function above more applicable, one can implements lambda functions:

def pd_iter_func(df: DataFrame, criteria: Callable[[NamedTuple], bool]) -> Optional[NamedTuple]:
    for row in df.itertuples():
        if criteria(row):
            return row

pd_iter_func(df, lambda row: row.A > 4 and row.B > 3)

As mentioned in the answer to the 'mirror' question, pandas.Series.idxmax would also be a nice choice.

def pd_idxmax_func(df, mask):
    return df.loc[mask.idxmax()]

pd_idxmax_func(df, (df.A > 4) & (df.B > 3))

How to convert int to float in python?

In Python 3 this is the default behavior, but if you aren't using that you can import division like so:

>>> from __future__ import division
>>> 144/314
0.4585987261146497

Alternatively you can cast one of the variables to a float when doing your division which will do the same thing

sum = 144
women_onboard = 314
proportion_womenclass3_survived = sum / float(np.size(women_onboard))

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset bootstrap page with button click using jQuery :

function resetForm(){
        var validator = $( "#form_ID" ).validate();
        validator.resetForm();
}

Using above code you also have change the field colour as red to normal.

If you want to reset only fielded value then :

$("#form_ID")[0].reset();

Merging 2 branches together in GIT

merge is used to bring two (or more) branches together.

a little example:

# on branch A:
# create new branch B
$ git checkout -b B
# hack hack
$ git commit -am "commit on branch B"

# create new branch C from A
$ git checkout -b C A
# hack hack
$ git commit -am "commit on branch C"

# go back to branch A
$ git checkout A
# hack hack
$ git commit -am "commit on branch A"

so now there are three separate branches (namely A B and C) with different heads

to get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:

# create an octopus merge
$ git merge B C

your history will then look something like this:

…-o-o-x-------A
      |\     /|
      | B---/ |
       \     /
        C---/

if you want to merge across repository/computer borders, have a look at git pull command, e.g. from the pc with branch A (this example will create two new commits):

# pull branch B
$ git pull ssh://host/… B
# pull branch C
$ git pull ssh://host/… C

jQuery Force set src attribute for iframe

$(".excel").click(function () {
    var t = $(this).closest(".tblGrid").attr("id");
    window.frames["Iframe" + t].document.location.href = pagename + "?tbl=" + t;
});

this is what i use, no jquery needed for this. in this particular scenario for each table i have with an excel export icon this forces the iframe attached to that table to load the same page with a variable in the Query String that the page looks for, and if found response writes out a stream with an excel mimetype and includes the data for that table.

Inner join with count() on three tables

As Frank pointed out, you need to use DISTINCT. Also, since you are using composite primary keys (which is perfectly fine, BTW) you need to make sure that you use the whole key in your joins:

SELECT
    P.pe_name,
    COUNT(DISTINCT O.ord_id) AS num_orders,
    COUNT(I.item_id) AS num_items
FROM
    People P
INNER JOIN Orders O ON
    O.pe_id = P.pe_id
INNER JOIN Items I ON
    I.ord_id = O.ord_id AND
    I.pe_id = O.pe_id
GROUP BY
    P.pe_name

Without I.ord_id = O.ord_id it was joining each item row to every order row for a person.

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How to serve up a JSON response using Go?

Other users commenting that the Content-Type is plain/text when encoding. You have to set the Content-Type first w.Header().Set, then the HTTP response code w.WriteHeader.

If you call w.WriteHeader first then call w.Header().Set after you will get plain/text.

An example handler might look like this;

func SomeHandler(w http.ResponseWriter, r *http.Request) {
    data := SomeStruct{}
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(data)
}

How to set up a PostgreSQL database in Django

Also make sure you have the PostgreSQL development package installed. On Ubuntu you need to do something like this:

$ sudo apt-get install libpq-dev

Graphviz: How to go from .dot to a graph?

Get the graphviz-2.24.msi Graphviz.org. Then get zgrviewer.

Zgrviewer requires java (probably 1.5+). You might have to set the paths to the Graphviz binaries in Zgrviewer's preferences.

File -> Open -> Open with dot -> SVG pipeline (standard) ... Pick your .dot file.

You can zoom in, export, all kinds of fun stuff.

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

Convert and format a Date in JSP

You can do that using the SimpleDateFormat class.

SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String dates=formatter.format(mydate);
//mydate is your date object

what is the unsigned datatype?

In C and C++

unsigned = unsigned int (Integer type)
signed   = signed int (Integer type)

An unsigned integer containing n bits can have a value between 0 and (2^n-1) , which is 2^n different values.

An unsigned integer is either positive or zero.

Signed integers are stored in a computer using 2's complement.

convert string array to string

string[] test = new string[2];

test[0] = "Hello ";
test[1] = "World!";

string.Join("", test);

How to multiply a BigDecimal by an integer in Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
        itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;
    }
}

When should I use File.separator and when File.pathSeparator?

java.io.File class contains four static separator variables. For better understanding, Let's understand with the help of some code

  1. separator: Platform dependent default name-separator character as String. For windows, it’s ‘\’ and for unix it’s ‘/’
  2. separatorChar: Same as separator but it’s char
  3. pathSeparator: Platform dependent variable for path-separator. For example PATH or CLASSPATH variable list of paths separated by ‘:’ in Unix systems and ‘;’ in Windows system
  4. pathSeparatorChar: Same as pathSeparator but it’s char

Note that all of these are final variables and system dependent.

Here is the java program to print these separator variables. FileSeparator.java

import java.io.File;

public class FileSeparator {

    public static void main(String[] args) {
        System.out.println("File.separator = "+File.separator);
        System.out.println("File.separatorChar = "+File.separatorChar);
        System.out.println("File.pathSeparator = "+File.pathSeparator);
        System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
    }

}

Output of above program on Unix system:

File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :

Output of the program on Windows system:

File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;

To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.

Here is the code snippet showing how to use separators correctly.

//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");

Rmi connection refused with localhost

it seems that you should set your command as an String[],for example:

String[] command = new String[]{"rmiregistry","2020"};
Runtime.getRuntime().exec(command);

it just like the style of main(String[] args).

Multiple conditions in WHILE loop

If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

How to update a menu item shown in the ActionBar?

In Kotlin 1.2 simply call:

invalidateOptionsMenu()

and the onCreateOptionsMenu function will be called again.

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

I had two incompatible dependencies.

The below dependencies caused the error.

compile 'com.google.android.gms:play-services-fitness:8.3.0'
compile 'com.google.android.gms:play-services-wearable:8.4.0'

By changing the fitness dependency to version 8.4.0 I was able to run the app.

compile 'com.google.android.gms:play-services-fitness:8.4.0'
compile 'com.google.android.gms:play-services-wearable:8.4.0'

UITableView, Separator color where to set?

Swift version:

override func viewDidLoad() {
    super.viewDidLoad()

    // Assign your color to this property, for example here we assign the red color.
    tableView.separatorColor = UIColor.redColor()
}

SQL Switch/Case in 'where' clause

Try this query, it's very easy and useful: Its ready to execute!

USE tempdb
GO

IF NOT OBJECT_ID('Tempdb..Contacts') IS NULL
    DROP TABLE Contacts

CREATE TABLE Contacts(ID INT, FirstName VARCHAR(100), LastName VARCHAR(100))
INSERT INTO Contacts (ID, FirstName, LastName)
SELECT 1, 'Omid', 'Karami'
UNION ALL
SELECT 2, 'Alen', 'Fars'
UNION ALL
SELECT 3, 'Sharon', 'b'
UNION ALL
SELECT 4, 'Poja', 'Kar'
UNION ALL
SELECT 5, 'Ryan', 'Lasr'
GO
 
DECLARE @FirstName VARCHAR(100)
SET @FirstName = 'Omid'
 
DECLARE @LastName VARCHAR(100)
SET @LastName = '' 
 
SELECT FirstName, LastName
FROM Contacts
WHERE  
    FirstName = CASE
    WHEN LEN(@FirstName) > 0 THEN  @FirstName 
    ELSE FirstName 
    END
AND
    LastName = CASE
    WHEN LEN(@LastName) > 0 THEN  @LastName 
    ELSE LastName
    END
GO

Angular Directive refresh on parameter change

angular.module('app').directive('conversation', function() {
    return {
        restrict: 'E',
        link: function ($scope, $elm, $attr) {
            $scope.$watch("some_prop", function (newValue, oldValue) {
                  var typeId = $attr.type-id;
                  // Your logic.
            });
        }
    };
}

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

I know it's for a long time ago but may be helpful to any other new comers,

I decided to pass user name,password and domain while requesting SSRS reports, so I created one class which implements IReportServerCredentials.

 public class ReportServerCredentials : IReportServerCredentials   
{
    #region  Class Members
        private string username;
        private string password;
        private string domain;
    #endregion

    #region Constructor
        public ReportServerCredentials()
        {}
        public ReportServerCredentials(string username)
        {
            this.Username = username;
        }
        public ReportServerCredentials(string username, string password)
        {
            this.Username = username;
            this.Password = password;
        }
        public ReportServerCredentials(string username, string password, string domain)
        {
            this.Username = username;
            this.Password = password;
            this.Domain = domain;
        }
    #endregion

    #region Properties
        public string Username
        {
            get { return this.username; }
            set { this.username = value; }
        }
        public string Password
        {
            get { return this.password; }
            set { this.password = value; }
        }
        public string Domain
        {
            get { return this.domain; }
            set { this.domain = value; }
        }
        public WindowsIdentity ImpersonationUser
        {
            get { return null; }
        }
        public ICredentials NetworkCredentials
        {
            get
            {
                return new NetworkCredential(Username, Password, Domain);
            }
        }
    #endregion

    bool IReportServerCredentials.GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string password, out string authority)
    {
        authCookie = null;
        userName = password = authority = null;
        return false;
    }
}

while calling SSRS Reprots, put following piece of code

 ReportViewer rptViewer = new ReportViewer();
 string RptUserName = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUser"]);
        string RptUserPassword = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUserPassword"]);
        string RptUserDomain = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportUserDomain"]);
        string SSRSReportURL = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportURL"]);
        string SSRSReportFolder = Convert.ToString(ConfigurationManager.AppSettings["SSRSReportFolder"]);

        IReportServerCredentials reportCredentials = new ReportServerCredentials(RptUserName, RptUserPassword, RptUserDomain);
        rptViewer.ServerReport.ReportServerCredentials = reportCredentials;
        rptViewer.ServerReport.ReportServerUrl = new Uri(SSRSReportURL);

SSRSReportUser,SSRSReportUserPassword,SSRSReportUserDomain,SSRSReportFolder are defined in web.config files.

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

drawCircle(int X, int Y, int Radius, ColorFill, Graphics gObj) 

Set background image in CSS using jquery

Try this:

<div class="rmz-srchbg">
    <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox">
    <input type="submit" value="&nbsp;" id="srchbtn" class="rmz-srchico">
    <br style="clear:both;">
</div>
<script>
$(function(){
   $('#globalsearchstr').on('focus mouseenter', function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
   });
});
</script>

SQL Server: How to check if CLR is enabled?

The accepted answer needs a little clarification. The row will be there if CLR is enabled or disabled. Value will be 1 if enabled, or 0 if disabled.

I use this script to enable on a server, if the option is disabled:

if not exists(
    SELECT value
    FROM sys.configurations
    WHERE name = 'clr enabled'
     and value = 1
)
begin
    exec sp_configure @configname=clr_enabled, @configvalue=1
    reconfigure
end

Angular-Material DateTime Picker Component?

Angular Material 10 now includes a new date range picker.

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

Example

HTML

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

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

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

Select2 doesn't work when embedded in a bootstrap modal

Based on @pymarco answer I wrote this solution, it's not perfect but solves the select2 focus problem and maintain tab sequence working inside modal

    $.fn.modal.Constructor.prototype.enforceFocus = function () {
        $(document)
        .off('focusin.bs.modal') // guard against infinite focus loop
        .on('focusin.bs.modal', $.proxy(function (e) {
            if (this.$element[0] !== e.target && !this.$element.has(e.target).length && !$(e.target).closest('.select2-dropdown').length) {
                this.$element.trigger('focus')
            }
        }, this))
    }

How to use OpenCV SimpleBlobDetector

// creation 
            cv::SimpleBlobDetector * blob_detector; 
            blob_detector = new SimpleBlobDetector(); 
            blob_detector->create("SimpleBlobDetector"); 
// change params - first move it to public!! 
            blob_detector->params.filterByArea = true; 
            blob_detector->params.minArea = 1; 
            blob_detector->params.maxArea = 32000; 
// or read / write them with file 
            FileStorage fs("test_fs.yml", FileStorage::WRITE); 
            FileNode fn = fs["features"]; 

            //blob_detector->read(fn); 
// detect 
            vector<KeyPoint> keypoints; 
            blob_detector->detect(img_text, keypoints); 
            fs.release(); 

I do know why, but params are protected. So I moved it in file features2d.hpp to be public:

  virtual void read( const FileNode& fn ); 
  virtual void write( FileStorage& fs ) const; 

public: 
Params params; 




protected: 
struct CV_EXPORTS Center 
  { 
      Point2d loc 

If you will not do this, the only way to change params is to create file (FileStorage fs("test_fs.yml", FileStorage::WRITE);), than open it in notepad, and edit. Or maybe there is another way, but I`m not aware of it.

How to import module when module name has a '-' dash or hyphen in it?

If you can't rename the original file, you could also use a symlink:

ln -s foo-bar.py foo_bar.py

Then you can just:

from foo_bar import *

setting request headers in selenium

Webdriver doesn't contain an API to do it. See issue 141 from Selenium tracker for more info. The title of the issue says that it's about response headers but it was decided that Selenium won't contain API for request headers in scope of this issue. Several issues about adding API to set request headers have been marked as duplicates: first, second, third.

Here are a couple of possibilities that I can propose:

  1. Use another driver/library instead of selenium
  2. Write a browser-specific plugin (or find an existing one) that allows you to add header for request.
  3. Use browsermob-proxy or some other proxy.

I'd go with option 3 in most of cases. It's not hard.

Note that Ghostdriver has an API for it but it's not supported by other drivers.

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

An alternative to the already provided ways is to simply filter on the column like so

df = df.where(F.col('columnNameHere').isNull())

This has the added benefit that you don't have to add another column to do the filtering and it's quick on larger data sets.

Adding a Button to a WPF DataGrid

First create a DataGridTemplateColumn to contain the button:

<DataGridTemplateColumn>
  <DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
      <Button Click="ShowHideDetails">Details</Button> 
    </DataTemplate> 
  </DataGridTemplateColumn.CellTemplate> 
</DataGridTemplateColumn>

When the button is clicked, update the containing DataGridRow's DetailsVisibility:

void ShowHideDetails(object sender, RoutedEventArgs e)
{
    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
    if (vis is DataGridRow)
    {
        var row = (DataGridRow)vis;
        row.DetailsVisibility = 
        row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        break;
    }
}