Programs & Examples On #Trailing

How to remove leading and trailing zeros in a string? Python

What about a basic

your_string.strip("0")

to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip instead (and .lstrip for only the leading ones).

More info in the doc.

You could use some list comprehension to get the sequences you want like so:

trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]

How do I remove trailing whitespace using a regular expression?

Regex to find trailing and leading whitespaces:

^[ \t]+|[ \t]+$

JAVA How to remove trailing zeros from a double

Use DecimalFormat

  double answer = 5.0;
   DecimalFormat df = new DecimalFormat("###.#");
  System.out.println(df.format(answer));

How can I remove a trailing newline?

rstrip doesn't do the same thing as chomp, on so many levels. Read http://perldoc.perl.org/functions/chomp.html and see that chomp is very complex indeed.

However, my main point is that chomp removes at most 1 line ending, whereas rstrip will remove as many as it can.

Here you can see rstrip removing all the newlines:

>>> 'foo\n\n'.rstrip(os.linesep)
'foo'

A much closer approximation of typical Perl chomp usage can be accomplished with re.sub, like this:

>>> re.sub(os.linesep + r'\Z','','foo\n\n')
'foo\n'

Remove Trailing Spaces and Update in Columns in SQL Server

If you are using SQL Server (starting with vNext) or Azure SQL Database then you can use the below query.

SELECT TRIM(ColumnName) from TableName;

For other SQL SERVER Database you can use the below query.

SELECT LTRIM(RTRIM(ColumnName)) from TableName

LTRIM - Removes spaces from the left

example: select LTRIM(' test ') as trim = 'test '

RTRIM - Removes spaces from the right

example: select RTRIM(' test ') as trim = ' test'

Horizontal Scroll Table in Bootstrap/CSS

Here is one possiblity for you if you are using Bootstrap 3

live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/

edit view: http://jsfiddle.net/panchroma/vPH8N/

I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive

ie:

<div class="table-responsive">
<table class="table">
...
</table>
</div>

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

How can I use the binary operator alongside the date filter?

<span class="gallery-date">{{gallery.date | date:'mediumDate' || "Date Empty"}}</span>

you also try:

<span class="gallery-date">{{ gallery.date == 'NULL' ? 'mediumDate' : "gallery.date"}}</span>

vim line numbers - how to have them on by default?

in home directory you will find a file called ".vimrc" in that file add this code "set nu" and save and exit and open new vi file and you will find line numbers on that.

What is the difference between lower bound and tight bound?

Θ-notation (theta notation) is called tight-bound because it's more precise than O-notation and Ω-notation (omega notation).

If I were lazy, I could say that binary search on a sorted array is O(n2), O(n3), and O(2n), and I would be technically correct in every case. That's because O-notation only specifies an upper bound, and binary search is bounded on the high side by all of those functions, just not very closely. These lazy estimates would be useless.

Θ-notation solves this problem by combining O-notation and Ω-notation. If I say that binary search is Θ(log n), that gives you more precise information. It tells you that the algorithm is bounded on both sides by the given function, so it will never be significantly faster or slower than stated.

How to start new activity on button click

Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);

How to check if smtp is working from commandline (Linux)

Not sure if this help or not but this is a command line tool which let you simply send test mails from a SMTP server priodically. http://code.google.com/p/woodpecker-tester/

Get last key-value pair in PHP array

"SPL-way":

$splArray = SplFixedArray::fromArray($array);
$last_item_with_preserved_index[$splArray->getSize()-1] = $splArray->offsetGet($splArray->getSize()-1);

Read more about SplFixedArray and why it's in some cases ( especially with big-index sizes array-data) more preferable than basic array here => The SplFixedArray class.

Get the Selected value from the Drop down box in PHP

Couldn't you just pass the a name attribute and wrap it in a form?

<form id="form" action="do_stuff.php" method="post">
    <select id="select_catalog" name="select_catalog_query">
    <?php <<<INSERT THE SELECT OPTION LOOP>>> ?>
    </select>
</form>

And then look for $_POST['select_catalog_query'] ?

NodeJS/express: Cache and 304 status code

I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)

<meta name="304workaround" content="2013-10-24 21:17:23">

Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...

How to get response body using HttpURLConnection, when code other than 2xx is returned?

Wrong method was used for errors, here is the working code:

BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}

Change bootstrap datepicker date format on select

for me with bootstrap 4 datetime picker (http://www.eyecon.ro/bootstrap-datepicker/) format worked only with upper case:

$('.datepicker').datetimepicker({
            format: 'DD/MM/YYYY'
        });

Which concurrent Queue implementation should I use in Java?

ConcurrentLinkedQueue means no locks are taken (i.e. no synchronized(this) or Lock.lock calls). It will use a CAS - Compare and Swap operation during modifications to see if the head/tail node is still the same as when it started. If so, the operation succeeds. If the head/tail node is different, it will spin around and try again.

LinkedBlockingQueue will take a lock before any modification. So your offer calls would block until they get the lock. You can use the offer overload that takes a TimeUnit to say you are only willing to wait X amount of time before abandoning the add (usually good for message type queues where the message is stale after X number of milliseconds).

Fairness means that the Lock implementation will keep the threads ordered. Meaning if Thread A enters and then Thread B enters, Thread A will get the lock first. With no fairness, it is undefined really what happens. It will most likely be the next thread that gets scheduled.

As for which one to use, it depends. I tend to use ConcurrentLinkedQueue because the time it takes my producers to get work to put onto the queue is diverse. I don't have a lot of producers producing at the exact same moment. But the consumer side is more complicated because poll won't go into a nice sleep state. You have to handle that yourself.

Expected response code 220 but got code "", with message "" in Laravel

i was facing this problem and i checked all the answers and nothing worked for me, but then i reset mail.php and didn't touch it and set the mail server from .env file and it worked perfectly, hope this will save the time for someone :).

Simulate a specific CURL in PostMan

As per the above answers, it works well.

If we paste curl requests with Authorization data in import, Postman will set all headers automatically. We only just pass row JSON data in the request body if needed or Upload images through form-data in the body.

This is just an example. Your API should be a different one (if your API allows)

curl -X POST 'https://verifyUser.abc.com/api/v1/verification' \
    -H 'secret: secret' \
    -H 'email: [email protected]' \
    -H 'accept: application/json, text/plain, */*' \
    -H 'authorizationtoken: bearer' \
    -F 'referenceFilePath= Add file path' \
    --compressed

Best way to make a shell script daemon?

See Bash Service Manager project: https://github.com/reduardo7/bash-service-manager

Implementation example

#!/usr/bin/env bash

export PID_FILE_PATH="/tmp/my-service.pid"
export LOG_FILE_PATH="/tmp/my-service.log"
export LOG_ERROR_FILE_PATH="/tmp/my-service.error.log"

. ./services.sh

run-script() {
  local action="$1" # Action

  while true; do
    echo "@@@ Running action '${action}'"
    echo foo
    echo bar >&2

    [ "$action" = "run" ] && return 0
    sleep 5
    [ "$action" = "debug" ] && exit 25
  done
}

before-start() {
  local action="$1" # Action

  echo "* Starting with $action"
}

after-finish() {
  local action="$1" # Action
  local serviceExitCode=$2 # Service exit code

  echo "* Finish with $action. Exit code: $serviceExitCode"
}

action="$1"
serviceName="Example Service"

serviceMenu "$action" "$serviceName" run-script "$workDir" before-start after-finish

Usage example

$ ./example-service
# Actions: [start|stop|restart|status|run|debug|tail(-[log|error])]

$ ./example-service start
# Starting Example Service service...

$ ./example-service status
# Serive Example Service is runnig with PID 5599

$ ./example-service stop
# Stopping Example Service...

$ ./example-service status
# Service Example Service is not running

g++ undefined reference to typeinfo

In the base class (an abstract base class) you declare a virtual destructor and as you cannot declare a destructor as a pure virtual function, either you have to define it right here in the abstract class, just a dummy definition like virtual ~base() { } will do, or in any of the derived class.

If you fail to do this, you will end up in an "undefined symbol" at link time. Since VMT has an entry for all the pure virtual functions with a matching NULL as it updates the table depending on the implementation in the derived class. But for the non-pure but virtual functions, it needs the definition at the link time so that it can update the VMT table.

Use c++filt to demangle the symbol. Like $c++filt _ZTIN10storageapi8BaseHostE will output something like "typeinfo for storageapi::BaseHost".

Python constructors and __init__

Why are constructors indeed called "Constructors" ?

The constructor (named __new__) creates and returns a new instance of the class. So the C.__new__ class method is the constructor for the class C.

The C.__init__ instance method is called on a specific instance, after it is created, to initialise it before being passed back to the caller. So that method is the initialiser for new instances of C.

How are they different from methods in a class?

As stated in the official documentation __init__ is called after the instance is created. Other methods do not receive this treatment.

What is their purpose?

The purpose of the constructor C.__new__ is to define custom behaviour during construction of a new C instance.

The purpose of the initialiser C.__init__ is to define custom initialisation of each instance of C after it is created.

For example Python allows you to do:

class Test(object):
    pass

t = Test()

t.x = 10   # here you're building your object t
print t.x

But if you want every instance of Test to have an attribute x equal to 10, you can put that code inside __init__:

class Test(object):
    def __init__(self):
        self.x = 10

t = Test()
print t.x

Every instance method (a method called on a specific instance of a class) receives the instance as its first argument. That argument is conventionally named self.

Class methods, such as the constructor __new__, instead receive the class as their first argument.

Now, if you want custom values for the x attribute all you have to do is pass that value as argument to __init__:

class Test(object):
    def __init__(self, x):
        self.x = x

t = Test(10)
print t.x
z = Test(20)
print t.x

I hope this will help you clear some doubts, and since you've already received good answers to the other questions I will stop here :)

Delete all objects in a list

To delete all objects in a list, you can directly write list = []

Here is example:

>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a = []
>>> a
[]

How to check version of a CocoaPods framework

pod --version used this to check the version of the last installed pod

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

I had the same problem. Unfortunately I was in wrong catalog level.

I tried to: git push -u origin master -> there was a error

Then I tried: git pull --rebase -> there still was a problem
Finally i change directory cd your_directory

Then I tried again ( git push) and it works!

Add new row to excel Table (VBA)

Tbl.ListRows.Add doesn't work for me and I believe lot others are facing the same problem. I use the following workaround:

    'First check if the last row is empty; if not, add a row
    If table.ListRows.count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.count).Range
        For col = 1 To lastRow.Columns.count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                lastRow.Cells(1, col).EntireRow.Insert
                'Cut last row and paste to second last
                lastRow.Cut Destination:=table.ListRows(table.ListRows.count - 1).Range
                Exit For
            End If
        Next col
    End If

    'Populate last row with the form data
    Set lastRow = table.ListRows(table.ListRows.count).Range
    Range("E7:E10").Copy
    lastRow.PasteSpecial Transpose:=True
    Range("E7").Select
    Application.CutCopyMode = False

Hope it helps someone out there.

How to hash a password

I use a hash and a salt for my password encryption (it's the same hash that Asp.Net Membership uses):

private string PasswordSalt
{
   get
   {
      var rng = new RNGCryptoServiceProvider();
      var buff = new byte[32];
      rng.GetBytes(buff);
      return Convert.ToBase64String(buff);
   }
}

private string EncodePassword(string password, string salt)
{
   byte[] bytes = Encoding.Unicode.GetBytes(password);
   byte[] src = Encoding.Unicode.GetBytes(salt);
   byte[] dst = new byte[src.Length + bytes.Length];
   Buffer.BlockCopy(src, 0, dst, 0, src.Length);
   Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
   HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
   byte[] inarray = algorithm.ComputeHash(dst);
   return Convert.ToBase64String(inarray);
}

Vue.js: Conditional class style binding

if you want to apply separate css classes for same element with conditions in Vue.js you can use the below given method.it worked in my scenario.

html

 <div class="Main" v-bind:class="{ Sub: page}"  >

in here, Main and Sub are two different class names for same div element. v-bind:class directive is used to bind the sub class in here. page is the property we use to update the classes when it's value changed.

js

data:{
page : true;
}

here we can apply a condition if we needed. so, if the page property becomes true element will go with Main and Sub claases css styles. but if false only Main class css styles will be applied.

Redirect all output to file in Bash

Credits to osexp2003 and j.a. …


Instead of putting:

&>> your_file.log

behind a line in:

crontab -e

I use:

#!/bin/bash
exec &>> your_file.log
…

at the beginning of a BASH script.

Advantage: You have the log definitions within your script. Good for Git etc.

SQL Server String or binary data would be truncated

I was using empty string '' on on table creation and then receiving error 'Msg 8152, String or binary data would be truncated' on subsequent update. This was happening due to the update value containing 6 characters and being larger than the column definition anticipated. I used "SPACE" to get around this only because I knew I would be updating in bulk following the initial data creation i.e. the column was not going to remain empty for long.

SO BIG CAVEAT HERE: This is not a particularly slick solution but is useful in the case where you are pulling together a data set e.g. for one-off intelligence requests where you are creating a table for data mining, applying some bulk processing/interpretation and storing before and after results for later comparison/mining. This is a frequent occurrence in my line of work.

You can initially populate using the SPACE keyword i.e.

    select 
           Table1.[column1]
          ,Table1.[column2]
          ,SPACE(10) as column_name
    into table_you_are_creating
    from Table1
    where ...

Subsequent updates to "column_name" of 10 characters or less (substitute as applicable) will then be allowed without causing truncate error. Again, I would only use this in scenarios similar to that described in my caveat.

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

How to Set OnClick attribute with value containing function in ie8?

You don't need to use setAttribute for that - This code works (IE8 also)

<div id="something" >Hello</div>
<script type="text/javascript" >
    (function() {
        document.getElementById("something").onclick = function() { 
            alert('hello'); 
        };
    })();
</script>

Filter spark DataFrame on string contains

You can use contains (this works with an arbitrary sequence):

df.filter($"foo".contains("bar"))

like (SQL like with SQL simple regular expression whith _ matching an arbitrary character and % matching an arbitrary sequence):

df.filter($"foo".like("bar"))

or rlike (like with Java regular expressions):

df.filter($"foo".rlike("bar"))

depending on your requirements. LIKE and RLIKE should work with SQL expressions as well.

How to ignore files/directories in TFS for avoiding them to go to central source repository?

I found the perfect way to Ignore files in TFS like SVN does.
First of all, select the file that you want to ignore (e.g. the Web.config).
Now go to the menu tab and select:

File Source control > Advanced > Exclude web.config from source control

... and boom; your file is permanently excluded from source control.

How to do a FULL OUTER JOIN in MySQL?

Modified shA.t's query for more clarity:

-- t1 left join t2
SELECT t1.value, t2.value
FROM t1 LEFT JOIN t2 ON t1.value = t2.value   

    UNION ALL -- include duplicates

-- t1 right exclude join t2 (records found only in t2)
SELECT t1.value, t2.value
FROM t1 RIGHT JOIN t2 ON t1.value = t2.value
WHERE t1.value IS NULL 

"elseif" syntax in JavaScript

In JavaScript's if-then-else there is technically no elseif branch.

But it works if you write it this way:

if (condition) {

} else if (other_condition) {

} else {

}

To make it obvious what is really happening you can expand the above code using an additional pair of { and }:

if (condition) {

} else {

   if (other_condition) {

   } else {

   }

}

In the first example we're using some implicit JS behavior about {} uses. We can omit these curly braces if there is only one statement inside. Which is the case in this construct, because the inner if-then-else only counts as one statment. The truth is that those are 2 nested if-statements. And not an if-statement with 2 branches, as it may appear on first sight.

This way it resembles the elseif that is present in other languages.

It is a question of style and preference which way you use it.

How do I create test and train samples from one dataframe with pandas?

There are many ways to create a train/test and even validation samples.

Case 1: classic way train_test_split without any options:

from sklearn.model_selection import train_test_split
train, test = train_test_split(df, test_size=0.3)

Case 2: case of a very small datasets (<500 rows): in order to get results for all your lines with this cross-validation. At the end, you will have one prediction for each line of your available training set.

from sklearn.model_selection import KFold
kf = KFold(n_splits=10, random_state=0)
y_hat_all = []
for train_index, test_index in kf.split(X, y):
    reg = RandomForestRegressor(n_estimators=50, random_state=0)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clf = reg.fit(X_train, y_train)
    y_hat = clf.predict(X_test)
    y_hat_all.append(y_hat)

Case 3a: Unbalanced datasets for classification purpose. Following the case 1, here is the equivalent solution:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.3)

Case 3b: Unbalanced datasets for classification purpose. Following the case 2, here is the equivalent solution:

from sklearn.model_selection import StratifiedKFold
kf = StratifiedKFold(n_splits=10, random_state=0)
y_hat_all = []
for train_index, test_index in kf.split(X, y):
    reg = RandomForestRegressor(n_estimators=50, random_state=0)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clf = reg.fit(X_train, y_train)
    y_hat = clf.predict(X_test)
    y_hat_all.append(y_hat)

Case 4: you need to create a train/test/validation sets on big data to tune hyperparameters (60% train, 20% test and 20% val).

from sklearn.model_selection import train_test_split
X_train, X_test_val, y_train, y_test_val = train_test_split(X, y, test_size=0.6)
X_test, X_val, y_test, y_val = train_test_split(X_test_val, y_test_val, stratify=y, test_size=0.5)

Remove ':hover' CSS behavior from element

I also had this problem, my solution was to have an element above the element i dont want a hover effect on:

_x000D_
_x000D_
.no-hover {_x000D_
  position: relative;_x000D_
  opacity: 0.65 !important;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.no-hover::before {_x000D_
  content: '';_x000D_
  background-color: transparent;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  z-index: 60;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<button class="btn btn-primary">hover</button>_x000D_
<span class="no-hover">_x000D_
  <button class="btn btn-primary ">no hover</button>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How does C compute sin() and other math functions?

They are typically implemented in software and will not use the corresponding hardware (that is, aseembly) calls in most cases. However, as Jason pointed out, these are implementation specific.

Note that these software routines are not part of the compiler sources, but will rather be found in the correspoding library such as the clib, or glibc for the GNU compiler. See http://www.gnu.org/software/libc/manual/html_mono/libc.html#Trig-Functions

If you want greater control, you should carefully evaluate what you need exactly. Some of the typical methods are interpolation of look-up tables, the assembly call (which is often slow), or other approximation schemes such as Newton-Raphson for square roots.

Retrieving a property of a JSON object by index?

Here you can access "set2" property following:

    var obj = {
        "set1": [1, 2, 3],
        "set2": [4, 5, 6, 7, 8],
        "set3": [9, 10, 11, 12]
    };

    var output = Object.keys(obj)[1];

Object.keys return all the keys of provided object as Array..

How to get index in Handlebars each helper?

Arrays:

{{#each array}}
    {{@index}}: {{this}}
{{/each}}

If you have arrays of objects... you can iterate through the children:

{{#each array}}
    //each this = { key: value, key: value, ...}
    {{#each this}}
        //each key=@key and value=this of child object 
        {{@key}}: {{this}}
        //Or get index number of parent array looping
        {{@../index}}
    {{/each}}
{{/each}}

Objects:

{{#each object}}
    {{@key}}: {{this}}
{{/each}} 

If you have nested objects you can access the key of parent object with {{@../key}}

click command in selenium webdriver does not work

If you know for sure that the element is present, you could try this to simulate the click - if .Click() isn't working

driver.findElement(By.name("submit")).sendKeys(Keys.RETURN);

or

driver.findElement(By.name("submit")).sendKeys(Keys.ENTER);

How to sort a Collection<T>?

If your collections object is a list, I would use the sort method, as proposed in the other answers.

However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:

TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);

Server is already running in Rails

Remove the file: C:/Sites/folder/Pids/Server.pids

Explanation In UNIX land at least we usually track the process id (pid) in a file like server.pid. I think this is doing the same thing here. That file was probably left over from a crash.

Google API for location, based on user IP address

Google already appends location data to all requests coming into GAE (see Request Header documentation for go, java, php and python). You should be interested X-AppEngine-Country, X-AppEngine-Region, X-AppEngine-City and X-AppEngine-CityLatLong headers.

An example looks like this:

X-AppEngine-Country:US
X-AppEngine-Region:ca
X-AppEngine-City:norwalk
X-AppEngine-CityLatLong:33.902237,-118.081733

How to input a path with a white space?

You can escape the "space" char by putting a \ right before it.

Copy struct to struct in C

Also a good example.....

struct point{int x,y;};
typedef struct point point_t;
typedef struct
{
    struct point ne,se,sw,nw;
}rect_t;
rect_t temp;


int main()
{
//rotate
    RotateRect(&temp);
    return 0;
}

void RotateRect(rect_t *givenRect)
{
    point_t temp_point;
    /*Copy struct data from struct to struct within a struct*/
    temp_point = givenRect->sw;
    givenRect->sw = givenRect->se;
    givenRect->se = givenRect->ne;
    givenRect->ne = givenRect->nw;
    givenRect->nw = temp_point;
}

Save file Javascript with file name

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

Here a compatibility table for downloadattribute: http://caniuse.com/download

What does "The following object is masked from 'package:xxx'" mean?

The message means that both the packages have functions with the same names. In this particular case, the testthat and assertive packages contain five functions with the same name.

When two functions have the same name, which one gets called?

R will look through the search path to find functions, and will use the first one that it finds.

search()
 ##  [1] ".GlobalEnv"        "package:assertive" "package:testthat" 
 ##  [4] "tools:rstudio"     "package:stats"     "package:graphics" 
 ##  [7] "package:grDevices" "package:utils"     "package:datasets" 
 ## [10] "package:methods"   "Autoloads"         "package:base"

In this case, since assertive was loaded after testthat, it appears earlier in the search path, so the functions in that package will be used.

is_true
## function (x, .xname = get_name_in_parent(x)) 
## {
##     x <- coerce_to(x, "logical", .xname)
##     call_and_name(function(x) {
##         ok <- x & !is.na(x)
##         set_cause(ok, ifelse(is.na(x), "missing", "false"))
##     }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>

The functions in testthat are not accessible in the usual way; that is, they have been masked.

What if I want to use one of the masked functions?

You can explicitly provide a package name when you call a function, using the double colon operator, ::. For example:

testthat::is_true
## function () 
## {
##     function(x) expect_true(x)
## }
## <environment: namespace:testthat>

How do I suppress the message?

If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE to library.

library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time

Alternatively, suppress the message with suppressPackageStartupMessages:

library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output

Impact of R's Startup Procedures on Function Masking

If you have altered some of R's startup configuration options (see ?Startup) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup should solve most mysteries.

For example, the documentation there says:

Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.

Which implies that when 3rd party packages are loaded via files like .Rprofile you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.

How do I list all the masked functions?

First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.

library(dplyr)
envs <- search() %>% setNames(., .)

For each environment, get the exported functions (and other variables).

fns <- lapply(envs, ls)

Turn this into a data frame, for easy use with dplyr.

fns_by_env <- data_frame(
  env = rep.int(names(fns), lengths(fns)),
  fn  = unlist(fns)
)

Find cases where the object appears more than once.

fns_by_env %>% 
  group_by(fn) %>% 
  tally() %>% 
  filter(n > 1) %>% 
  inner_join(fns_by_env)

To test this, try loading some packages with known conflicts (e.g., Hmisc, AnnotationDbi).

How do I prevent name conflict bugs?

The conflicted package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.

library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
##  * Hmisc::units
##  * base::units

c++ exception : throwing std::string

Though this question is rather old and has already been answered, I just want to add a note on how to do proper exception handling in C++11:

Use std::nested_exception and std::throw_with_nested

Using these, in my opinion, leads to cleaner exception design and makes it unnecessary to create an exception class hierarchy.

Note that this enables you to get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging. It is described on StackOverflow here and here, how to write a proper exception handler which will rethrow nested exceptions.

Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

jQuery: How to get the event object in an event handler function without passing it as an argument?

If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:

Markup:

  <a href="#" id="link1" >click</a>

Javascript:

  $(document).ready(function(){
      $("#link1").click(clickWithEvent);  //Bind the click event to the link
  });
  function clickWithEvent(evt){
     myFunc('p1', 'p2', 'p3');
     function myFunc(p1,p2,p3){  //Defined as local function, but has access to evt
        alert(evt.type);        
     }
  }

Since the event ob

Are static methods inherited in Java?

B.display() works because static declaration makes the method/member to belong to the class, and not any particular class instance (aka Object). You can read more about it here.

Another thing to note is that you cannot override a static method, you can have your sub class declare a static method with the same signature, but its behavior may be different than what you'd expect. This is probably the reason why it is not considered inherited. You can check out the problematic scenario and the explanation here.

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

How to set a default value with Html.TextBoxFor?

This work for me

@Html.TextBoxFor(model => model.Age, htmlAttributes: new { @Value = "" })

How to validate a file upload field using Javascript/jquery

My function will check if the user has selected the file or not and you can also check whether you want to allow that file extension or not.

Try this:

<input type="file" name="fileUpload" onchange="validate_fileupload(this.value);">

function validate_fileupload(fileName)
{
    var allowed_extensions = new Array("jpg","png","gif");
    var file_extension = fileName.split('.').pop().toLowerCase(); // split function will split the filename by dot(.), and pop function will pop the last element from the array which will give you the extension as well. If there will be no extension then it will return the filename.

    for(var i = 0; i <= allowed_extensions.length; i++)
    {
        if(allowed_extensions[i]==file_extension)
        {
            return true; // valid file extension
        }
    }

    return false;
}

javascript scroll event for iPhone/iPad?

Since iOS 8 came out, this problem does not exist any more. The scroll event is now fired smoothly in iOS Safari as well.

So, if you register the scroll event handler and check window.pageYOffset inside that event handler, everything works just fine.

Get the position of a div/span tag

You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top, left, right and/or bottom properties...

var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;

If using jQuery, you can use the more succinct code...

var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;

Use child_process.execSync but keep output in console

Simply:

 try {
    const cmd = 'git rev-parse --is-inside-work-tree';
    execSync(cmd).toString();
 } catch (error) {
    console.log(`Status Code: ${error.status} with '${error.message}'`;
 }

Ref: https://stackoverflow.com/a/43077917/104085

// nodejs
var execSync = require('child_process').execSync;

// typescript
const { execSync } = require("child_process");

 try {
    const cmd = 'git rev-parse --is-inside-work-tree';
    execSync(cmd).toString();
 } catch (error) {
    error.status;  // 0 : successful exit, but here in exception it has to be greater than 0
    error.message; // Holds the message you typically want.
    error.stderr;  // Holds the stderr output. Use `.toString()`.
    error.stdout;  // Holds the stdout output. Use `.toString()`.
 }

enter image description here

enter image description here

When command runs successful: enter image description here

How to get the body's content of an iframe in Javascript?

The exact question is how to do it with pure JavaScript not with jQuery.

But I always use the solution that can be found in jQuery's source code. It's just one line of native JavaScript.

For me it's the best, easy readable and even afaik the shortest way to get the iframes content.

First get your iframe

var iframe = document.getElementById('id_description_iframe');

// or
var iframe = document.querySelector('#id_description_iframe');

And then use jQuery's solution

var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

It works even in the Internet Explorer which does this trick during the contentWindow property of the iframe object. Most other browsers uses the contentDocument property and that is the reason why we proof this property first in this OR condition. If it is not set try contentWindow.document.

Select elements in iframe

Then you can usually use getElementById() or even querySelectorAll() to select the DOM-Element from the iframeDocument:

if (!iframeDocument) {
    throw "iframe couldn't be found in DOM.";
}

var iframeContent = iframeDocument.getElementById('frameBody');

// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');

Call functions in the iframe

Get just the window element from iframe to call some global functions, variables or whole libraries (e.g. jQuery):

var iframeWindow = iframe.contentWindow;

// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');

// or
iframeContent = iframeWindow.$('#frameBody');

// or even use any other global variable
iframeWindow.myVar = window.myVar;

// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);

Note

All this is possible if you observe the same-origin policy.

How can I remove a character from a string using JavaScript?

The following function worked best for my case:

public static cut(value: string, cutStart: number, cutEnd: number): string {
    return value.substring(0, cutStart) + value.substring(cutEnd + 1, value.length);
}

Counting unique values in a column in pandas dataframe like in Qlik?

Or get the number of unique values for each column:

df.nunique()

dID    3
hID    5
mID    3
uID    5
dtype: int64

New in pandas 0.20.0 pd.DataFrame.agg

df.agg(['count', 'size', 'nunique'])

         dID  hID  mID  uID
count      8    8    8    8
size       8    8    8    8
nunique    3    5    3    5

You've always been able to do an agg within a groupby. I used stack at the end because I like the presentation better.

df.groupby('mID').agg(['count', 'size', 'nunique']).stack()


             dID  hID  uID
mID                       
A   count      5    5    5
    size       5    5    5
    nunique    3    5    5
B   count      2    2    2
    size       2    2    2
    nunique    2    2    2
C   count      1    1    1
    size       1    1    1
    nunique    1    1    1

How to overcome the CORS issue in ReactJS

You can set up a express proxy server using http-proxy-middleware to bypass CORS:

const express = require('express');
const proxy = require('http-proxy-middleware');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();

app.use(express.static(__dirname));
app.use('/proxy', proxy({
    pathRewrite: {
       '^/proxy/': '/'
    },
    target: 'https://server.com',
    secure: false
}));

app.get('*', (req, res) => {
   res.sendFile(path.resolve(__dirname, 'index.html'));
});

app.listen(port);
console.log('Server started');

From your react app all requests should be sent to /proxy endpoint and they will be redirected to the intended server.

const URL = `/proxy/${PATH}`;
return axios.get(URL);

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

I encountered this problem in Laravel 5.8, what I did was to do composer require for each library and all where installed correctly.

Like so:

instead of adding it to the composer.json file or specifying a version:

composer require msurguy/honeypot: dev-master

I instead did without specifying any version:

composer require msurguy/honeypot

I hope it helps, thanks

How do I convert a IPython Notebook into a Python file via commandline?

The following example turns an Iron Python Notebook called a_notebook.ipynb into a python script called a_python_script.py leaving out the cells tagged with the keyword remove, which I add manually to the cells that I don't want to end up in the script, leaving out visualizations and other steps that once I am done with the notebook I don't need to be executed by the script.

import nbformat as nbf
from nbconvert.exporters import PythonExporter
from nbconvert.preprocessors import TagRemovePreprocessor

with open("a_notebook.ipynb", 'r', encoding='utf-8') as f:
    the_notebook_nodes = nbf.read(f, as_version = 4)

trp = TagRemovePreprocessor()

trp.remove_cell_tags = ("remove",)

pexp = PythonExporter()

pexp.register_preprocessor(trp, enabled= True)

the_python_script, meta = pexp.from_notebook_node(the_notebook_nodes)

with open("a_python_script.py", 'w') as f:
    f.writelines(the_python_script)

How to draw checkbox or tick mark in GitHub Markdown table?

Try adding a - before the [] or [x]. That's an - followed by a blank space .

Below is an example from Github blog.

### Solar System Exploration, 1950s – 1960s

- [ ] Mercury
- [x] Venus
- [x] Earth (Orbit/Moon)
- [x] Mars
- [ ] Jupiter
- [ ] Saturn
- [ ] Uranus
- [ ] Neptune
- [ ] Comet Haley

It appears like below:

Resultant Image

Here's how one could do the same in a table:

| Task           | Time required | Assigned to   | Current Status | Finished | 
|----------------|---------------|---------------|----------------|-----------|
| Calendar Cache | > 5 hours  |  | in progress | - [x] ok?
| Object Cache   | > 5 hours  |  | in progress | [x] item1<br/>[ ] item2
| Object Cache   | > 5 hours  |  | in progress | <ul><li>- [x] item1</li><li>- [ ] item2</li></ul>
| Object Cache   | > 5 hours  |  | in progress | <ul><li>[x] item1</li><li>[ ] item2</li></ul>


- [x] works
- [x] works too

Here's how it looks:

enter image description here

differences in application/json and application/x-www-form-urlencoded

The first case is telling the web server that you are posting JSON data as in:

{ Name : 'John Smith', Age: 23}

The second option is telling the web server that you will be encoding the parameters in the URL as in:

Name=John+Smith&Age=23

Waiting till the async task finish its work

In your AsyncTask add one ProgressDialog like:

private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);

you can setMessage in onPreExecute() method like:

this.dialog.setMessage("Processing..."); 
this.dialog.show();

and in your onPostExecute(Void result) method dismiss your ProgressDialog.

How can I find where I will be redirected using cURL?

Lot's of regex here, despite the fact i really like them this way might be more stable to me:

$resultCurl=curl_exec($curl); //get curl result
//Optional line if you want to store the http status code
$headerHttpCode=curl_getinfo($curl,CURLINFO_HTTP_CODE);

//let's use dom and xpath
$dom = new \DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($resultCurl, LIBXML_HTML_NODEFDTD);
libxml_use_internal_errors(false);
$xpath = new \DOMXPath($dom);
$head=$xpath->query("/html/body/p/a/@href");

$newUrl=$head[0]->nodeValue;

The location part is a link in the HTML sent by apache. So Xpath is perfect to recover it.

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

Websockets use TCP protocol.

WebRTC is mainly UDP.

Thus main reason of using WebRTC instead of Websocket is latency. With websocket streaming you will have either high latency or choppy playback with low latency. With WebRTC you may achive low-latency and smooth playback which is crucial stuff for VoIP communications.

Just try to test these technology with a network loss, i.e. 2%. You will see high delays in the Websocket stream.

How does OkHttp get Json string?

I hope you managed to obtain the json data from the json string.

Well I think this will be of help

try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
    .url(urls[0])
    .build();
Response responses = null;

try {
    responses = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}   

String jsonData = responses.body().string();

JSONObject Jobject = new JSONObject(jsonData);
JSONArray Jarray = Jobject.getJSONArray("employees");

//define the strings that will temporary store the data
String fname,lname;

//get the length of the json array
int limit = Jarray.length()

//datastore array of size limit
String dataStore[] = new String[limit];

for (int i = 0; i < limit; i++) {
    JSONObject object     = Jarray.getJSONObject(i);

    fname = object.getString("firstName");
    lname = object.getString("lastName");

    Log.d("JSON DATA", fname + " ## " + lname);

    //store the data into the array
    dataStore[i] = fname + " ## " + lname;
}

//prove that the data was stored in the array      
 for (String content ; dataStore ) {
        Log.d("ARRAY CONTENT", content);
    }

Remember to use AsyncTask or SyncAdapter(IntentService), to prevent getting a NetworkOnMainThreadException

Also import the okhttp library in your build.gradle

compile 'com.squareup.okhttp:okhttp:2.4.0'

Why doesn't Python have multiline comments?

Assume that they were just considered unnecessary. Since it's so easy to just type #a comment, multiline comments can just consist of many single line comments.

For HTML, on the other hand, there's more of a need for multiliners. It's harder to keep typing <!--comments like this-->.

Git:nothing added to commit but untracked files present

Also instead of adding each file manually, we could do something like:

git add --all

OR

git add -A

This will also remove any files not present or deleted (Tracked files in the current working directory which are now absent).

If you only want to add files which are tracked and have changed, you would want to do

git add -u

What is the difference between git add . & git add --all?

Select count(*) from result query

This counts the rows of the inner query:

select count(*) from (
    select count(SID) 
    from Test 
    where Date = '2012-12-10' 
    group by SID
) t

However, in this case the effect of that is the same as this:

select count(distinct SID) from Test where Date = '2012-12-10'

Foreach value from POST from form

If your post keys have to be parsed and the keys are sequences with data, you can try this:

Post data example: Storeitem|14=data14

foreach($_POST as $key => $value){
    $key=Filterdata($key); $value=Filterdata($value);
    echo($key."=".$value."<br>");
}

then you can use strpos to isolate the end of the key separating the number from the key.

How to generate access token using refresh token through google drive API?

POST /oauth2/v4/token

Host: www.googleapis.com

Headers

Content-length: 163

content-type: application/x-www-form-urlencoded

RequestBody

client_secret=************&grant_type=refresh_token&refresh_token=sasasdsa1312dsfsdf&client_id=************

Check if image exists on server using JavaScript?

You can just check if the image loads or not by using the built in events that is provided for all images.

The onload and onerror events will tell you if the image loaded successfully or if an error occured :

var image = new Image();

image.onload = function() {
    // image exists and is loaded
    document.body.appendChild(image);
}
image.onerror = function() {
    // image did not load

    var err = new Image();
    err.src = '/error.png';

    document.body.appendChild(err);
}

image.src = "../imgs/6.jpg";

php.ini: which one?

You can find what is the php.ini file used:

  • By add phpinfo() in a php page and display the page (like the picture under)
  • From the shell, enter: php -i

Next, you can find the information in the Loaded Configuration file (so here it's /user/local/etc/php/php.ini)

Sometimes, you have indicated (none), in this case you just have to put your custom php.ini that you can find here: http://git.php.net/?p=php-src.git;a=blob;f=php.ini-production;hb=HEAD

I hope this answer will help.

Display all post meta keys and meta values of the same post ID in wordpress

As of Jan 2020 and WordPress v5.3.2, I confirm the following works fine.

It will include the field keys with their equivalent underscore keys as well, but I guess if you properly "enum" your keys in your code, that should be no problem:

$meta_values   = get_post_meta( get_the_ID() );
$example_field = meta_values['example_field_key'][0];

//OR if you do enum style 
//(emulation of a class with a list of *const* as enum does not exist in PHP per se)
$example_field = meta_values[PostTypeEnum::FIELD_EXAMPLE_KEY][0]; 

As the print_r(meta_values); gives:

Array
(
    [_edit_lock] => Array
        (
            [0] => 1579542560:1
        )

    [_edit_last] => Array
        (
            [0] => 1
        )

    [example_field] => Array
        (
            [0] => 13
        )
)

Hope that helps someone, go make a ruckus!

Accessing localhost (xampp) from another computer over LAN network - how to?

Sometimes your firewall can be the problem. Make sure you've disabled your antivirus firewall monitoring. It worked for me.

TypeError: 'undefined' is not an object

I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?

You could check in the following way (extra = and making length a truthy evaluation)

if (typeof(sub.from) !== 'undefined' && sub.from.length) {

[update]

I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:

for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
            mainid = sub.from[i]['id'];
            var sub = afcHelper_Submissions[mainid]; // <== re setting sub

My guess is that the error is not on the if statement but on the for(i... statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).

Converting XDocument to XmlDocument and vice versa

You can use the built in xDocument.CreateReader() and an XmlNodeReader to convert back and forth.

Putting that into an Extension method to make it easier to work with.

using System;
using System.Xml;
using System.Xml.Linq;

namespace MyTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {

            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");

            var xDocument = xmlDocument.ToXDocument();
            var newXmlDocument = xDocument.ToXmlDocument();
            Console.ReadLine();
        }
    }

    public static class DocumentExtensions
    {
        public static XmlDocument ToXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new XmlDocument();
            using(var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }
            return xmlDocument;
        }

        public static XDocument ToXDocument(this XmlDocument xmlDocument)
        {
            using (var nodeReader = new XmlNodeReader(xmlDocument))
            {
                nodeReader.MoveToContent();
                return XDocument.Load(nodeReader);
            }
        }
    }
}

Sources:

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

How to use a TRIM function in SQL Server

You are missing two closing parentheses...and I am not sure an ampersand works as a string concatenation operator. Try '+'

SELECT dbo.COL_V_Cost_GEMS_Detail.TNG_SYS_NR AS [EHP Code], 
dbo.COL_TBL_VCOURSE.TNG_NA AS [Course Title], 
LTRIM(RTRIM(FCT_TYP_CD)) + ') AND (' + LTRIM(RTRIM(DEP_TYP_ID)) + ')' AS [Course Owner]

Alarm Manager Example

Alarm Manager:

Add To XML Layout (*init these view on create in main activity)

  <TimePicker
    android:id="@+id/timepicker"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="2"></TimePicker>

  <Button
    android:id="@+id/btn_start"
    android:text="start Alarm"
    android:onClick="start_alarm_event"
    android:layout_width="match_parent"
    android:layout_height="52dp" />

Add To Manifest (Inside application tag && outside activity)

 <receiver android:name=".AlarmBroadcastManager"
        android:enabled="true"
        android:exported="true"/>

Create AlarmBroadcastManager Class(inherit it from BroadcastReceiver)

 public class AlarmBroadcastManager extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
      MediaPlayer mediaPlayer=MediaPlayer.create(context,Settings.System.DEFAULT_RINGTONE_URI);
      mediaPlayer.start();
    }
 }

In Main Activity (Add these Functions):

 @RequiresApi(api = Build.VERSION_CODES.M)
 public  void start_alarm_event(View view){
    Calendar calendar=Calendar.getInstance();
    calendar.set(
    calendar.get(Calendar.YEAR),
    calendar.get(Calendar.MONTH),
    calendar.get(Calendar.DAY_OF_MONTH),
    timePicker.getHour(),
    timePicker.getMinute(),
    0
    );
    setAlarm(calendar.getTimeInMillis());
 }

 public void setAlarm(long timeInMillis){
    AlarmManager alarmManager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent=new Intent(this,AlarmBroadcastManager.class);
    PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,timeInMillis,AlarmManager.INTERVAL_DAY,pendingIntent);
    Toast.makeText(getApplicationContext(),"Alarm is Set",Toast.LENGTH_SHORT).show();


 }

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I was facing the similar type of issue: Code Snippet :

<c:forEach items="${orderList}" var="xx"> ${xx.id} <br>
</c:forEach>

There was a space after orderlist like this : "${orderList} " because of which the xx variable was getting coverted into String and was not able to call xx.id.

So make sure about space. They play crucial role sometimes. :p

jQuery.click() vs onClick

Seperation of concerns is key here, and so the event binding is the generally accepted method. This is basically what a lot of the existing answers have said.

However don't throw away the idea of declarative markup too quickly. It has it's place, and with frameworks like Angularjs, is the centerpiece.

There needs to be an understanding that the whole <div id="myDiv" onClick="divFunction()">Some Content</div> was shamed so heavily because it was abused by some developers. So it reached the point of sacrilegious proportions, much like tables. Some developers actually avoid tables for tabular data. It's the perfect example of people acting without understanding.

Although I like the idea of keeping my behaviour seperate from my views. I see no issue with the markup declaring what it does (not how it does it, that's behaviour). It might be in the form of an actual onClick attribute, or a custom attribute, much like bootstraps javascript components.

This way, by glancing just at the markup, you can see what is does, instead of trying to reverse lookup javascript event binders.

So, as a third alternative to the above, using data attributes to declarativly announce the behaviour within the markup. Behaviour is kept out of the view, but at a glance you can see what is happening.

Bootstrap example:

<button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button>

Source: http://getbootstrap.com/javascript/#popovers

Note The main disadvantage with the second example is the pollution of global namespace. This can be circumvented by either using the third alternative above, or frameworks like Angular and their ng-click attributes with automatically scope.

jQuery: go to URL with target="_blank"

If you want to create the popup window through jQuery then you'll need to use a plugin. This one seems like it will do what you want:

http://rip747.github.com/popupwindow/

Alternately, you can always use JavaScript's window.open function.

Note that with either approach, the new window must be opened in response to user input/action (so for instance, a click on a link or button). Otherwise the browser's popup blocker will just block the popup.

How to change status bar color in Flutter?

What you want is Themes. They're important for a lot more than the AppBar color.

https://flutter.io/cookbook/design/themes/

Could not find any resources appropriate for the specified culture or the neutral culture

Sibi Elangos's answer alone was not sufficient for me, so I had to:

  • Right click on your ResourceFile
  • Change the "Build Action" property
  • Compile to "Embedded Resource"
  • Build and deploy

This will generate an App_GlobalResources in your /bin folder, now copy that folder also to the root of the web application

How to handle-escape both single and double quotes in an SQL-Update statement

When SET QUOTED_IDENTIFIER is OFF, literal strings in expressions can be delimited by single or double quotation marks.

If a literal string is delimited by double quotation marks, the string can contain embedded single quotation marks, such as apostrophes.

Set System.Drawing.Color values

The Color structure is immutable (as all structures should really be), meaning that the values of its properties cannot be changed once that particular instance has been created.

Instead, you need to create a new instance of the structure with the property values that you want. Since you want to create a color using its component RGB values, you need to use the FromArgb method:

Color myColor = Color.FromArgb(100, 150, 75);

What is the HTML tabindex attribute?

The is used to define a sequence that users follow when they use the Tab key to navigate through a page. By default, the natural tabbing order will match the source order in the markup.

The tabindex content attribute allows authors to control whether an element is supposed to be focusable, whether it is supposed to be reachable using sequential focus navigation, and what is to be the relative order of the element for the purposes of sequential focus navigation. The name "tab index" comes from the common use of the "tab" key to navigate through the focusable elements. The term "tabbing" refers to moving forward through the focusable elements that can be reached using sequential focus navigation.
W3C Recommendation: HTML5
Section 7.4.1 Sequential focus navigation and the tabindex attribute

The tabindex starts at 0 or any positive whole number and increments upward. It's common to see the value 0 avoided because in older versions of Mozilla and IE, the tabindex would start at 1, move on to 2, and only after 2 would it go to 0 and then 3. The maximum integer value for tabindex is 32767. If elements have the same tabindex then the tabindex will match the source order in the markup. A negative value will remove the element from the tab index so it will never be focused.

If an element is assigned a tabindex of -1 it will remove the element and it will never be focusable but focus can be given to the element programmatically using element.focus().

If you specify the tabindex attribute with no value or an empty value it will be ignored.

If the disabled attribute is set on an element which has a tabindex, the element will be ignored.


If a tabindex is set anywhere within the page regardless of where it is in relation to the rest of the code (it could be in the footer, content area, where-ever) if there is a defined tabindex then the tab order will start at the element which is explicitly assigned the lowest tabindex value above 0. It will then cycle through the elements defined and only after the explicit tabindex elements have been tabbed through, will it return to the beginning of the document and follow the natural tab order.


In the HTML4 spec only the following elements support the tabindex attribute: , , , , , , and . But the HTML5 spec, with accessibility in mind, allows all elements to be assigned tabindex.

--

For example

<ul tabindex="-1">
  <li tabindex="1"></li>
  <li tabindex="2"></li>
  <li tabindex="3"></li>
</ul>

is the same as

<ul tabindex="-1">
  <li tabindex="1"></li>
  <li tabindex="1"></li>
  <li tabindex="1"></li>
</ul>

because regardless of the fact that they are all assigned tabindex="1", they will still follow the same order, the first one is first, and the last one is last. This is also the same..

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

because you do not need to explicitly define the tabIndex if it's default behavior. A div by default will not be focusable, the anchor tags will.

How do I center an anchor element in CSS?

Try

margin: 0 auto;
display:table

Hope that helps somebody out.

Property 'value' does not exist on type 'EventTarget'

Here is one more way to specify event.target:

_x000D_
_x000D_
import { Component, EventEmitter, Output } from '@angular/core';_x000D_
_x000D_
@Component({_x000D_
    selector: 'text-editor',_x000D_
    template: `<textarea (keyup)="emitWordCount($event)"></textarea>`_x000D_
})_x000D_
export class TextEditorComponent {_x000D_
_x000D_
   @Output() countUpdate = new EventEmitter<number>();_x000D_
_x000D_
    emitWordCount({ target = {} as HTMLTextAreaElement }) { // <- right there_x000D_
_x000D_
        this.countUpdate.emit(_x000D_
          // using it directly without `event`_x000D_
            (target.value.match(/\S+/g) || []).length);_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

How to refresh page on back button click?

Try this... not tested. I hope it will work for you.

Make a new php file. You can use the back and forward buttons and the number/timestamp on the page always updates.

<?php
header("Cache-Control: no-store, must-revalidate, max-age=0");
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
echo time();
?>
<a href="http://google.com">aaaaaaaaaaaaa</a>

Or

found another solution

The onload event should be fired when the user hits the back button. Elements not created via JavaScript will retain their values. I suggest keeping a backup of the data used in dynamically created element within an INPUT TYPE="hidden" set to display:none then onload using the value of the input to rebuild the dynamic elements to the way they were.

<input type="hidden" id="refreshed" value="no">
<script type="text/javascript">
onload=function(){
var e=document.getElementById("refreshed");
if(e.value=="no")e.value="yes";
else{e.value="no";location.reload();}
}

Replace multiple characters in one replace call

You can also pass a RegExp object to the replace method like

var regexUnderscore = new RegExp("_", "g"); //indicates global match
var regexHash = new RegExp("#", "g");

string.replace(regexHash, "").replace(regexUnderscore, " ");

Javascript RegExp

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

Now there is a problem, if you have package-lock.json with npm 5+. You have to remove it before use of npm install --production.

How do I define global variables in CoffeeScript?

You can pass -b option when you compile code via coffee-script under node.js. The compiled code will be the same as on coffeescript.org.

How to export a CSV to Excel using Powershell

This is a slight variation that worked better for me.

$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"

$xl = new-object -comobject excel.application
$xl.visible = $false
$Workbook = $xl.workbooks.open($CSV)
$Worksheets = $Workbooks.worksheets

$Workbook.SaveAs($XLS,1)
$Workbook.Saved = $True

$xl.Quit()

Bitwise operation and usage

Bit representations of integers are often used in scientific computing to represent arrays of true-false information because a bitwise operation is much faster than iterating through an array of booleans. (Higher level languages may use the idea of a bit array.)

A nice and fairly simple example of this is the general solution to the game of Nim. Take a look at the Python code on the Wikipedia page. It makes heavy use of bitwise exclusive or, ^.

How to round up integer division and have int result in Java?

If you want to calculate a divided by b rounded up you can use (a+(-a%b))/b

React - Component Full Screen (with height 100%)

While this may not be the ideal answer but try this:

style={{top:'0', bottom:'0', left:'0', right:'0', position: 'absolute'}}

It keeps the size attached to borders which is not what you want but gives you somewhat same effect.

How to fix the session_register() deprecated issue?

I wrote myself a little wrapper, so I don't have to rewrite all of my code from the past decades, which emulates register_globals and the missing session functions.

I've picked up some ideas from different sources and put some own stuff to get a replacement for missing register_globals and missing session functions, so I don't have to rewrite all of my code from the past decades. The code also works with multidimensional arrays and builds globals from a session.

To get the code to work use auto_prepend_file on php.ini to specify the file containing the code below. E.g.: auto_prepend_file = /srv/www/php/.auto_prepend.php.inc

You should have runkit extension from PECL installed and the following entries on your php.ini:

extension_dir = <your extension dir>
extension = runkit.so
runkit.internal_override = On

.auto_prepend.php.inc:

<?php
//Fix for removed session functions
if (!function_exists('session_register'))
{
    function session_register()
    {
        $register_vars = func_get_args();
        foreach ($register_vars as $var_name)
        {
            $_SESSION[$var_name] = $GLOBALS[$var_name];
            if (!ini_get('register_globals'))
            {   $GLOBALS[$var_name] = &$_SESSION[$var_name]; }
        }
    }

    function session_is_registered($var_name)
    {   return isset($_SESSION[$var_name]); }

    function session_unregister($var_name)
    {   unset($_SESSION[$var_name]); }
}

//Fix for removed function register_globals
if (!isset($PXM_REG_GLOB))
{
    $PXM_REG_GLOB=1;
    if (!ini_get('register_globals'))
    {
        if (isset($_REQUEST))   { extract($_REQUEST); }
        if (isset($_SERVER))        { extract($_SERVER); }

        //$_SESSION globals must be registred with call of session_start()
        // Best option - Catch session_start call - Runkit extension from PECL must be present
        if (extension_loaded("runkit"))
        {
            if (!function_exists('session_start_default'))
            {   runkit_function_rename("session_start", "session_start_default"); }
            if (!function_exists('session_start'))
            {
                function session_start($options=null)
                {
                    $return=session_start_default($options);
                    if (isset($_SESSION))
                    {
                        $var_names=array_keys($_SESSION);
                        foreach($var_names as $var_name)
                        {   $GLOBALS[$var_name]=&$_SESSION[$var_name]; }
                    }
                    return $return;
                }
            }
        }
        // Second best option - Will always extract $_SESSION if session cookie is present.
        elseif ($_COOKIE["PHPSESSID"])
        {
            session_start();
            if (isset($_SESSION))
            {
                $var_names=array_keys($_SESSION);
                foreach($var_names as $var_name)
                {   $GLOBALS[$var_name]=&$_SESSION[$var_name]; }
            }
        }
    }
}
?>

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

I had the same, there was an empty new line character at the beginning. That solved it:

int i = result.indexOf("{");
result = result.substring(i);
JSONObject json = new JSONObject(result.trim()); 
System.out.println(json.toString(4));  

How can I replace the deprecated set_magic_quotes_runtime in php?

Check if it's on first. That should get rid of the warning and it'll ensure that if your code is run on older versions of PHP that magic quotes are indeed off.

Don't just remove that line of code as suggested by others unless you can be 100% sure that the code will never be run on anything before PHP 5.3.

<?php
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
    // Deactivate
    set_magic_quotes_runtime(false);
}
?>

get_magic_quotes_runtime is NOT deprecated in PHP 5.3.
Source: http://us2.php.net/get_magic_quotes_runtime/

Handle JSON Decode Error when nothing returned

If you don't mind importing the json module, then the best way to handle it is through json.JSONDecodeError (or json.decoder.JSONDecodeError as they are the same) as using default errors like ValueError could catch also other exceptions not necessarily connected to the json decode one.

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want

//EDIT (Oct 2020):

As @Jacob Lee noted in the comment, there could be the basic common TypeError raised when the JSON object is not a str, bytes, or bytearray. Your question is about JSONDecodeError, but still it is worth mentioning here as a note; to handle also this situation, but differentiate between different issues, the following could be used:

from json.decoder import JSONDecodeError


try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except JSONDecodeError as e:
    # do whatever you want
except TypeError as e:
    # do whatever you want in this case

force css grid container to fill full screen of device

If you take advantage of width: 100vw; and height: 100vh;, the object with these styles applied will stretch to the full width and height of the device.

Also note, there are times padding and margins can get added to your view, by browsers and the like. I added a * global no padding and margins so you can see the difference. Keep this in mind.

_x000D_
_x000D_
*{_x000D_
  box-sizing: border-box;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
  display: grid;_x000D_
  border-style: solid;_x000D_
  border-color: red;_x000D_
  grid-template-columns: repeat(3, 1fr);_x000D_
  grid-template-rows: repeat(3, 1fr);_x000D_
  grid-gap: 10px;_x000D_
  width: 100vw;_x000D_
  height: 100vh;_x000D_
}_x000D_
.one {_x000D_
  border-style: solid;_x000D_
  border-color: blue;_x000D_
  grid-column: 1 / 3;_x000D_
  grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
  border-style: solid;_x000D_
  border-color: yellow;_x000D_
  grid-column: 2 / 4;_x000D_
  grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
  border-style: solid;_x000D_
  border-color: violet;_x000D_
  grid-row: 2 / 5;_x000D_
  grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
  border-style: solid;_x000D_
  border-color: aqua;_x000D_
  grid-column: 3;_x000D_
  grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
  border-style: solid;_x000D_
  border-color: green;_x000D_
  grid-column: 2;_x000D_
  grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
  border-style: solid;_x000D_
  border-color: purple;_x000D_
  grid-column: 3;_x000D_
  grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
  <div class="one">One</div>_x000D_
  <div class="two">Two</div>_x000D_
  <div class="three">Three</div>_x000D_
  <div class="four">Four</div>_x000D_
  <div class="five">Five</div>_x000D_
  <div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Copy array by value

Here are few more way to copy:

_x000D_
_x000D_
const array = [1,2,3,4];_x000D_
_x000D_
const arrayCopy1 = Object.values(array);_x000D_
const arrayCopy2 = Object.assign([], array);_x000D_
const arrayCopy3 = array.map(i => i);_x000D_
const arrayCopy4 = Array.of(...array );
_x000D_
_x000D_
_x000D_

.NET unique object identifier

RuntimeHelpers.GetHashCode() may help (MSDN).

Selecting multiple columns in a Pandas dataframe

I've seen several answers on that, but one remained unclear to me. How would you select those columns of interest?

The answer to that is that if you have them gathered in a list, you can just reference the columns using the list.

Example

print(extracted_features.shape)
print(extracted_features)

(63,)
['f000004' 'f000005' 'f000006' 'f000014' 'f000039' 'f000040' 'f000043'
 'f000047' 'f000048' 'f000049' 'f000050' 'f000051' 'f000052' 'f000053'
 'f000054' 'f000055' 'f000056' 'f000057' 'f000058' 'f000059' 'f000060'
 'f000061' 'f000062' 'f000063' 'f000064' 'f000065' 'f000066' 'f000067'
 'f000068' 'f000069' 'f000070' 'f000071' 'f000072' 'f000073' 'f000074'
 'f000075' 'f000076' 'f000077' 'f000078' 'f000079' 'f000080' 'f000081'
 'f000082' 'f000083' 'f000084' 'f000085' 'f000086' 'f000087' 'f000088'
 'f000089' 'f000090' 'f000091' 'f000092' 'f000093' 'f000094' 'f000095'
 'f000096' 'f000097' 'f000098' 'f000099' 'f000100' 'f000101' 'f000103']

I have the following list/NumPy array extracted_features, specifying 63 columns. The original dataset has 103 columns, and I would like to extract exactly those, then I would use

dataset[extracted_features]

And you will end up with this

Enter image description here

This something you would use quite often in machine learning (more specifically, in feature selection). I would like to discuss other ways too, but I think that has already been covered by other Stack Overflower users.

How to make Excel VBA variables available to multiple macros?

Create a "module" object and declare variables in there. Unlike class-objects that have to be instantiated each time, the module objects are always available. Therefore, a public variable, function, or property in a "module" will be available to all the other objects in the VBA project, macro, Excel formula, or even within a MS Access JET-SQL query def.

/etc/apt/sources.list" E212: Can't open file for writing

Try to connect as root and then edit file. This works for me

How do I create a dynamic key to be added to a JavaScript object variable

Associative Arrays in JavaScript don't really work the same as they do in other languages. for each statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push method:

jsArr = []; 

for (var i = 1; i <= 10; i++) { 
    jsArr.push('example ' + 1); 
} 

Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].

execute function after complete page load

If you can use jQuery, look at load. You could then set your function to run after your element finishes loading.

For example, consider a page with a simple image:

<img src="book.png" alt="Book" id="book" />

The event handler can be bound to the image:

$('#book').load(function() {
  // Handler for .load() called.
});

If you need all elements on the current window to load, you can use

$(window).load(function () {
  // run code
});

If you cannot use jQuery, the plain Javascript code is essentially the same amount of (if not less) code:

window.onload = function() {
  // run code
};

How do I get list of methods in a Python class?

Python 3.x answer without external libraries

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]

dunder-excluded result:

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]

Return None if Dictionary key is not available

You should use the get() method from the dict class

d = {}
r = d.get('missing_key', None)

This will result in r == None. If the key isn't found in the dictionary, the get function returns the second argument.

How do I make calls to a REST API using C#?

A solution in ASP.NET Core:

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace WebApp
{
    public static class HttpHelper
    {
        // In my case this is https://localhost:44366/
        private static readonly string apiBasicUri = ConfigurationManager.AppSettings["apiBasicUri"];

        public static async Task Post<T>(string url, T contentValue)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiBasicUri);
                var content = new StringContent(JsonConvert.SerializeObject(contentValue), Encoding.UTF8, "application/json");
                var result = await client.PostAsync(url, content);
                result.EnsureSuccessStatusCode();
            }
        }

        public static async Task Put<T>(string url, T stringValue)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiBasicUri);
                var content = new StringContent(JsonConvert.SerializeObject(stringValue), Encoding.UTF8, "application/json");
                var result = await client.PutAsync(url, content);
                result.EnsureSuccessStatusCode();
            }
        }

        public static async Task<T> Get<T>(string url)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiBasicUri);
                var result = await client.GetAsync(url);
                result.EnsureSuccessStatusCode();
                string resultContentString = await result.Content.ReadAsStringAsync();
                T resultContent = JsonConvert.DeserializeObject<T>(resultContentString);
                return resultContent;
            }
        }

        public static async Task Delete(string url)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(apiBasicUri);
                var result = await client.DeleteAsync(url);
                result.EnsureSuccessStatusCode();
            }
        }
    }
}

To post, use something like this:

await HttpHelper.Post<Setting>($"/api/values/{id}", setting);

Example for delete:

await HttpHelper.Delete($"/api/values/{id}");

Example to get a list:

List<ClaimTerm> claimTerms = await HttpHelper.Get<List<ClaimTerm>>("/api/values/");

Example to get only one:

ClaimTerm processedClaimImage = await HttpHelper.Get<ClaimTerm>($"/api/values/{id}");

how to iterate through dictionary in a dictionary in django template?

If you pass a variable data (dictionary type) as context to a template, then you code should be:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

// The answer that I was looking for when searching
public void Answer()
{
    IEnumerable<YourClass> first = this.GetFirstIEnumerableList();
    // Assign to empty list so we can use later
    IEnumerable<YourClass> second = new List<YourClass>();

    if (IwantToUseSecondList)
    {
        second = this.GetSecondIEnumerableList();  
    }
    IEnumerable<SchemapassgruppData> concatedList = first.Concat(second);
}

Java: Enum parameter in method

You can use an enum in said parameters like this:

public enum Alignment { LEFT, RIGHT }
private static String drawCellValue(
int maxCellLength, String cellValue, Alignment align) {}

then you can use either a switch or if statement to actually do something with said parameter.

switch(align) {
case LEFT: //something
case RIGHT: //something
default: //something
}

if(align == Alignment.RIGHT) { /*code*/}

Using await outside of an async function

As of Node.js 14.3.0 the top-level await is supported.

Required flag: --experimental-top-level-await.

Further details: https://v8.dev/features/top-level-await

SELECT INTO a table variable in T-SQL

You can also use common table expressions to store temporary datasets. They are more elegant and adhoc friendly:

WITH userData (name, oldlocation)
AS
(
  SELECT name, location 
  FROM   myTable    INNER JOIN 
         otherTable ON ...
  WHERE  age>30
)
SELECT * 
FROM   userData -- you can also reuse the recordset in subqueries and joins

How to handle click event in Button Column in Datagridview?

Assuming for example DataGridView has columns as given below and its data bound items are of type PrimalPallet you can use solution given below.

enter image description here

private void dataGridView1_CellContentClick( object sender, DataGridViewCellEventArgs e )
{
    if ( e.RowIndex >= 0 )
    {
        if ( e.ColumnIndex == this.colDelete.Index )
        {
            var pallet = this.dataGridView1.Rows[ e.RowIndex ].DataBoundItem as PrimalPallet;
            this.DeletePalletByID( pallet.ID );
        }
        else if ( e.ColumnIndex == this.colEdit.Index )
        {
            var pallet = this.dataGridView1.Rows[ e.RowIndex ].DataBoundItem as PrimalPallet;
            // etc.
        }
    }
}

It's safer to access columns directly rather than using dataGridView1.Columns["MyColumnName"] and there is no need to parse sender to the DataGridView as it's not needed.

Can we cast a generic object to a custom object type in javascript?

No.

But if you're looking to treat your person1 object as if it were a Person, you can call methods on Person's prototype on person1 with call:

Person.prototype.getFullNamePublic = function(){
    return this.lastName + ' ' + this.firstName;
}
Person.prototype.getFullNamePublic.call(person1);

Though this obviously won't work for privileged methods created inside of the Person constructor—like your getFullName method.

Load local javascript file in chrome for testing?

For security reasons, modern browsers won't load resource from locally running HTML files (files using file:// protocol in the address bar).

The easiest way to get a modern browser to load and run JavaScript files in local HTML files is to run a local web server.

If you don't want to go through the trouble of setting up a Node or Apache web server just to test your JavaScript, then I'd suggest you install Visual Studio Code and the Live Server extension.

Visual Studio Code

Visual Studio code is a source code editor for pretty much any programming language under the sun. It has built-in support for JavaScript, HTML, CSS, TypeScript, and almost any kind of language used for Web development.

Install Visual Studio Code

You can get the Visual Studio Code editor for your platform from https://code.visualstudio.com/. It supports Windows, Linux, and Mac. I think it also works on your Surface Pro if that's your thing.

Add the Live Code Extension

After installing VS Code, you can add the Live Code code extension using the Extension panel (Ctrl+Shift+X in Windows) in Visual Studio Code.

Live Server Extension

After adding the extension, you should see a "Go Live" button in the bottom-right corner of the Visual Studio Code IDE (as shown in the above screenshot).

Open in Code

Open the root folder where your HTML and JavaScript files exist in Visual Studio Code and click the "Go Live" button. Optionally, you can right-click the HTML file in the Explorer (Ctrl+Shift+E) and select Open with Live Server from the pop-up menu that appears.

Open with Live Server

This should create a locally running web server and open the file or folder in your web browser. If your file paths are correct, your JavaScript files should also load and run correctly.

Troubleshooting

If for some reason, the page doesn't load in your favorite browser, check that the address and port number are correct. If the Live Server is running, it should display the port number in the bottom-right corner of the Visual Studio IDE. Make sure the address in your browser says http://127.0.0.1:<PORT>/index.html where <PORT> has the same number as shown in the status bar in Visual Studio Code.

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

Uncomment this line (in /conf/logging.properties)

org.apache.jasper.compiler.TldLocationsCache.level = FINE

Work's for me in tomcat 7.0.53!

VBA equivalent to Excel's mod function

Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.

In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0

They are certainly not equivalent!

Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123

MySQL - Operand should contain 1 column(s)

Another place this error can happen in is assigning a value that has a comma outside of a string. For example:

SET totalvalue = (IFNULL(i.subtotal,0) + IFNULL(i.tax,0),0)

Syntax for if/else condition in SCSS mixin

You could try this:

$width:auto;
@mixin clearfix($width) {

   @if $width == 'auto' {

    // if width is not passed, or empty do this

   } @else {
        display: inline-block;
        width: $width;
   }
}

I'm not sure of your intended result, but setting a default value should return false.

Define an <img>'s src attribute in CSS

CSS is not used to define values to DOM element attributes, javascript would be more suitable for this.

How to clear the interpreter console?

Here's the definitive solution that merges all other answers. Features:

  1. You can copy-paste the code into your shell or script.
  2. You can use it as you like:

    >>> clear()
    >>> -clear
    >>> clear  # <- but this will only work on a shell
    
  3. You can import it as a module:

    >>> from clear import clear
    >>> -clear
    
  4. You can call it as a script:

    $ python clear.py
    
  5. It is truly multiplatform; if it can't recognize your system
    (ce, nt, dos or posix) it will fall back to printing blank lines.


You can download the [full] file here: https://gist.github.com/3130325
Or if you are just looking for the code:

class clear:
 def __call__(self):
  import os
  if os.name==('ce','nt','dos'): os.system('cls')
  elif os.name=='posix': os.system('clear')
  else: print('\n'*120)
 def __neg__(self): self()
 def __repr__(self):
  self();return ''

clear=clear()

Printing an int list in a single line python3

Yes that is possible in Python 3, just use * before the variable like:

print(*list)

This will print the list separated by spaces.

(where * is the unpacking operator that turns a list into positional arguments, print(*[1,2,3]) is the same as print(1,2,3), see also What does the star operator mean, in a function call?)

Merge PDF files with PHP

myokyawhtun's solution worked best for me (using PHP 5.4)

You will still get an error though - I resolved using the following:

Line 269 of fpdf_tpl.php - changed the function parameters to:

function Image($file, $x=null, $y=null, $w=0, $h=0, $type='', $link='',$align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0) { 

I also made this same change on line 898 of fpdf.php

Swift: declare an empty dictionary

It is very handy for finding your way

var dict:Dictionary = [:]

How do I get the position selected in a RecyclerView?

I think the most correct way to get item position is

View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override public void onClick(View v) {
      View view = v;
      View parent = (View) v.getParent();
      while (!(parent instanceof RecyclerView)){
        view=parent;
        parent = (View) parent.getParent();
      }
      int position = recyclerView.getChildAdapterPosition(view);
}

Because view, you click not always the root view of your row layout. If view is not a root one (e.g buttons), you will get Class cast exception. Thus at first we need to find the view, which is the a dirrect child of you reciclerview. Then, find position using recyclerView.getChildAdapterPosition(view);

How store a range from excel into a Range variable?

What is currentWorksheet? It works if you use the built-in ActiveSheet.

dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

Calculating time difference between 2 dates in minutes

ROUND(time_to_sec((TIMEDIFF(NOW(), "2015-06-10 20:15:00"))) / 60);

Are Git forks actually Git clones?

Fork, in the GitHub context, doesn't extend Git.
It only allows clone on the server side.

When you clone a GitHub repository on your local workstation, you cannot contribute back to the upstream repository unless you are explicitly declared as "contributor". That's because your clone is a separate instance of that project. If you want to contribute to the project, you can use forking to do it, in the following way:

  • clone that GitHub repository on your GitHub account (that is the "fork" part, a clone on the server side)
  • contribute commits to that GitHub repository (it is in your own GitHub account, so you have every right to push to it)
  • signal any interesting contribution back to the original GitHub repository (that is the "pull request" part by way of the changes you made on your own GitHub repository)

Check also "Collaborative GitHub Workflow".

If you want to keep a link with the original repository (also called upstream), you need to add a remote referring that original repository.
See "What is the difference between origin and upstream on GitHub?"

fork and upstream

And with Git 2.20 (Q4 2018) and more, fetching from fork is more efficient, with delta islands.

Syntax behind sorted(key=lambda: ...)

key is a function that will be called to transform the collection's items before they are compared. The parameter passed to key must be something that is callable.

The use of lambda creates an anonymous function (which is callable). In the case of sorted the callable only takes one parameters. Python's lambda is pretty simple. It can only do and return one thing really.

The syntax of lambda is the word lambda followed by the list of parameter names then a single block of code. The parameter list and code block are delineated by colon. This is similar to other constructs in python as well such as while, for, if and so on. They are all statements that typically have a code block. Lambda is just another instance of a statement with a code block.

We can compare the use of lambda with that of def to create a function.

adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2

lambda just gives us a way of doing this without assigning a name. Which makes it great for using as a parameter to a function.

variable is used twice here because on the left hand of the colon it is the name of a parameter and on the right hand side it is being used in the code block to compute something.

Can I find events bound on an element with jQuery?

You can now simply get a list of event listeners bound to an object by using the javascript function getEventListeners().

For example type the following in the dev tools console:

// Get all event listners bound to the document object
getEventListeners(document);

jQuery UI autocomplete with JSON

You need to transform the object you are getting back into an array in the format that jQueryUI expects.

You can use $.map to transform the dealers object into that array.

$('#dealerName').autocomplete({
    source: function (request, response) {
        $.getJSON("/example/location/example.json?term=" + request.term, function (data) {
            response($.map(data.dealers, function (value, key) {
                return {
                    label: value,
                    value: key
                };
            }));
        });
    },
    minLength: 2,
    delay: 100
});

Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label and value properties that $.map's callback function return.

Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:

  • Is an array of objects that have a label property, a value property, or both, or
  • Is a simple array of strings

In other words, if you can format the data like this:

[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]

or this:

["dealer 5", "dealer 6"]

Then your JavaScript becomes much simpler:

$('#dealerName').autocomplete({
    source: "/example/location/example.json"
});

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

krosenvold's answer inspired the following script which does the following:

  • get the dd dump via ssh from a remote server (as gz file)
  • unzip the dump
  • convert it to vmware

the script is restartable and checks the existence of the intermediate files. It also uses pv and qemu-img -p to show the progress of each step.

In my environment 2 x Ubuntu 12.04 LTS the steps took:

  • 3 hours to get a 47 GByte disk dump of a 60 GByte partition
  • 20 minutes to unpack to a 60 GByte dd file
  • 45 minutes to create the vmware file
#!/bin/bash
# get a dd disk dump and convert it to vmware
#  see http://stackoverflow.com/questions/454899/how-to-convert-flat-raw-disk-image-to-vmdk-for-virtualbox-or-vmplayer
#  Author: wf  2014-10-1919

#
# get a dd dump from the given host's given disk and create a compressed
#   image at the given target 
#
#  1: host e.g. somehost.somedomain
#  2: disk e.g. sda
#  3: target e.g. image.gz
#
# http://unix.stackexchange.com/questions/132797/how-to-use-ssh-to-make-a-dd-copy-of-disk-a-from-host-b-and-save-on-disk-b
getdump() {
  local l_host="$1"
  local l_disk="$2"
  local l_target="$3"
  echo "getting disk dump of $l_disk from $l_host"
  ssh $l_host sudo fdisk -l  | egrep "^/dev/$l_disk"
  if [ $? -ne 0 ]
  then
    echo "device $l_disk does not exist on host $l_host" 1>&2
    exit 1
  else
    if [ ! -f $l_target ]
    then
      ssh $l_host "sudo dd if=/dev/$disk bs=1M | gzip -1 -" | pv | dd of=$l_target
    else
      echo "$l_target already exists"
    fi
  fi
}

#
# optionally install command from package if it is not available yet
# 1: command
# 2: package
#
opt_install() {
  l_command="$1"
  l_package="$2"
  echo "checking that $l_command from package $l_package  is installed ..."
  which $l_command
  if [ $? -ne 0 ]
  then
    echo "installing $l_package to make $l_command available ..."
    sudo apt-get install $l_package 
  fi
}

#
# convert the given image to vmware
#  1: the dd dump image
#  2: the vmware image file to convert to
#
vmware_convert() {
  local l_ddimage="$1"
  local l_vmwareimage="$2"
  echo "converting dd image $l_image to vmware $l_vmwareimage"
  #  convert to VMware disk format showing progess
  # see http://manpages.ubuntu.com/manpages/precise/man1/qemu-img.1.html
  qemu-img convert -p -O vmdk "$l_ddimage" "$l_vmwareimage"
}

#
# show usage
#
usage() {
  echo "usage: $0 host device"
  echo "      host: the host to get the disk dump from e.g. frodo.lotr.org"  
  echo "            you need ssh and sudo privileges on that host"
  echo "
  echo "    device: the disk to dump from e.g. sda"
  echo ""
  echo "  examples:
  echo "       $0 frodo.lotr.org sda"
  echo "       $0 gandalf.lotr.org sdb"
  echo ""
  echo "  the needed packages pv and qemu-utils will be installed if not available"
  echo "  you need local sudo rights for this to work"
  exit 1
}

# check arguments
if [ $# -lt 2 ]
then
  usage
fi

# get the command line parameters
host="$1"
disk="$2"

# calculate the names of the image files
ts=`date "+%Y-%m-%d"`
# prefix of all images
#   .gz the zipped dd
#   .dd the disk dump file
#   .vmware - the vmware disk file
image="${host}_${disk}_image_$ts"

echo "$0 $host/$disk ->  $image"

# first check/install necessary packages
opt_install qemu-img qemu-utils
opt_install pv pv

# check if dd files was already loaded
#  we don't want to start this tedious process twice if avoidable
if [ ! -f $image.gz ]
then
  getdump $host $disk $image.gz
else
  echo "$image.gz already downloaded"
fi

# check if the dd file was already uncompressed
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.dd ]
then
  echo "uncompressing $image.gz"
  zcat $image.gz | pv -cN zcat > $image.dd
else
  echo "image $image.dd already uncompressed"
fi
# check if the vmdk file was already converted
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.vmdk ]
then
  vmware_convert $image.dd $image.vmdk
else
  echo "vmware image $image.vmdk already converted"
fi

How to force a list to be vertical using html css

Try putting display: block in the <li> tags instead of the <ul>

Postgres ERROR: could not open file for reading: Permission denied

Another way to do this, if you have pgAdmin and are comfortable using the GUI is to go the table in the schema and right click on the table you wish to import the file to and select "Import" browse your computer for the file, select the type your file is, the columns you want the data to be imputed into, and then select import.

That was done using pgAdmin III and the 9.4 version of PostgreSQL

VS2010 command prompt gives error: Cannot determine the location of the VS Common Tools folder

This same problem just started occurring for me and I was able to "fix" it by updating the vcvars32.bat file located in the C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\ folder (by default). Add the following after the first line:

@SET VSINSTALLDIR=c:\Program Files\Microsoft Visual Studio 10.0\
@SET VCINSTALLDIR=c:\Program Files\Microsoft Visual Studio 10.0\VC\
@SET FrameworkDir32=c:\Windows\Microsoft.NET\Framework\
@SET FrameworkVersion32=v4.0.30319
@SET Framework35Version=v3.5

And then comment out the following lines:

:: @call :GetVSCommonToolsDir
:: @if "%VS100COMNTOOLS%"=="" goto error_no_VS100COMNTOOLSDIR
:: @call "%VS100COMNTOOLS%VCVarsQueryRegistry.bat" 32bit No64bit

Found this here. Note that I say fix in quotes because I haven't checked to make sure that all the appropriate variables are set properly; that said, at a cursory glance it does appear to be valid.

Note that you'll have to edit the vcvars32.bat file in an elevated text editor (ie, Run as Admin) to be able to save the file in Vista and Windows 7.

How to install VS2015 Community Edition offline

You can download the ISO from https://beta.visualstudio.com/downloads/ (even if it has "beta" in the URL you'll have the latest stable version. Currently update 3)

VS2015 Community download

How to add buttons at top of map fragment API v2 layout

Maybe a simpler solution is to set an overlay in front of your map using FrameLayout or RelativeLayout and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapActivity" >

    <fragment xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scrollbars="vertical"  
        class="com.google.android.gms.maps.SupportMapFragment"/>

    <RadioGroup 
        android:id="@+id/radio_group_list_selector"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:orientation="horizontal" 
        android:background="#80000000"
        android:padding="4dp" >

        <RadioButton
            android:id="@+id/radioPopular"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:text="@string/Popular"
            android:gravity="center_horizontal|center_vertical"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioAZ"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/AZ"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />

        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioCategory"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/Category"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton2"
            android:textColor="@color/textcolor_radiobutton" />
        <View
            android:id="@+id/VerticalLine"
            android:layout_width="1dip"
            android:layout_height="match_parent"
            android:background="#aaa" />

        <RadioButton
            android:id="@+id/radioNearBy"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/NearBy"
            android:layout_weight="1"
            android:background="@drawable/shape_radiobutton3"
            android:textColor="@color/textcolor_radiobutton" />
    </RadioGroup>
</FrameLayout>

How to print an unsigned char in C?

The range of char is 127 to -128. If you assign 212, ch stores -44 (212-128-128) not 212.So if you try to print a negative number as unsigned you get (MAX value of unsigned int)-abs(number) which in this case is 4294967252

So if you want to store 212 as it is in ch the only thing you can do is declare ch as

unsigned char ch;

now the range of ch is 0 to 255.

nodejs send html file to client

Try your code like this:

var app = express();
app.get('/test', function(req, res) {
    res.sendFile('views/test.html', {root: __dirname })
});
  1. Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.

  2. You don't need the app.engine line, as that is handled internally by express.

Map and Reduce in .NET

Since I never can remember that LINQ calls it Where, Select and Aggregate instead of Filter, Map and Reduce so I created a few extension methods you can use:

IEnumerable<string> myStrings = new List<string>() { "1", "2", "3", "4", "5" };
IEnumerable<int> convertedToInts = myStrings.Map(s => int.Parse(s));
IEnumerable<int> filteredInts = convertedToInts.Filter(i => i <= 3); // Keep 1,2,3
int sumOfAllInts = filteredInts.Reduce((sum, i) => sum + i); // Sum up all ints
Assert.Equal(6, sumOfAllInts); // 1+2+3 is 6

Here are the 3 methods (from https://github.com/cs-util-com/cscore/blob/master/CsCore/PlainNetClassLib/src/Plugins/CsCore/com/csutil/collections/IEnumerableExtensions.cs ):

public static IEnumerable<R> Map<T, R>(this IEnumerable<T> self, Func<T, R> selector) {
    return self.Select(selector);
}

public static T Reduce<T>(this IEnumerable<T> self, Func<T, T, T> func) {
    return self.Aggregate(func);
}

public static IEnumerable<T> Filter<T>(this IEnumerable<T> self, Func<T, bool> predicate) {
    return self.Where(predicate);
}

Some more details from https://github.com/cs-util-com/cscore#ienumerable-extensions :

enter image description here

Textarea onchange detection

Try this one. It's simple, and since it's 2016 I am sure it will work on most browsers.

<textarea id="text" cols="50" rows="5" onkeyup="check()" maxlength="15"></textarea> 
<div><span id="spn"></span> characters left</div>

function check(){
    var string = document.getElementById("url").value
    var left = 15 - string.length;
    document.getElementById("spn").innerHTML = left;
}

How do I export a project in the Android studio?

From the menu:

Build|Generate Signed APK

or

Build|Build APK

(the latter if you don't need a signed one to publish to the Play Store)

Convert a string to integer with decimal in Python

How about this?

>>> s = '23.45678'
>>> int(float(s))
23

Or...

>>> int(Decimal(s))
23

Or...

>>> int(s.split('.')[0])
23

I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.

How to configure Git post commit hook

As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:

#!/usr/bin/python

import sys
from subprocess import call

if __name__ == '__main__':
    for line in sys.stdin.xreadlines():
        old, new, ref = line.strip().split(' ')
        if ref == 'refs/heads/master':
            print "=============================================="
            print "Pushing to master. Triggering jenkins.        "
            print "=============================================="
            sys.stdout.flush()
            call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])

In this case I trigger jenkins jobs only when pushing to master and not other branches.

How to keep a git branch in sync with master

concept47's approach is the right way to do it, but I'd advise to merge with the --no-ff option in order to keep your commit history clear.

git checkout develop
git pull --rebase
git checkout NewFeatureBranch
git merge --no-ff master

In Firebase, is there a way to get the number of children of a node without loading all the node data?

The code snippet you gave does indeed load the entire set of data and then counts it client-side, which can be very slow for large amounts of data.

Firebase doesn't currently have a way to count children without loading data, but we do plan to add it.

For now, one solution would be to maintain a counter of the number of children and update it every time you add a new child. You could use a transaction to count items, like in this code tracking upvodes:

var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
  return (current_value || 0) + 1;
});

For more info, see https://www.firebase.com/docs/transactions.html

UPDATE: Firebase recently released Cloud Functions. With Cloud Functions, you don't need to create your own Server. You can simply write JavaScript functions and upload it to Firebase. Firebase will be responsible for triggering functions whenever an event occurs.

If you want to count upvotes for example, you should create a structure similar to this one:

{
  "posts" : {
    "-JRHTHaIs-jNPLXOQivY" : {
      "upvotes_count":5,
      "upvotes" : {
      "userX" : true,
      "userY" : true,
      "userZ" : true,
      ...
    }
    }
  }
}

And then write a javascript function to increase the upvotes_count when there is a new write to the upvotes node.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.countlikes = functions.database.ref('/posts/$postid/upvotes').onWrite(event => {
  return event.data.ref.parent.child('upvotes_count').set(event.data.numChildren());
});

You can read the Documentation to know how to Get Started with Cloud Functions.

Also, another example of counting posts is here: https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js

Update January 2018

The firebase docs have changed so instead of event we now have change and context.

The given example throws an error complaining that event.data is undefined. This pattern seems to work better:

exports.countPrescriptions = functions.database.ref(`/prescriptions`).onWrite((change, context) => {
    const data = change.after.val();
    const count = Object.keys(data).length;
    return change.after.ref.child('_count').set(count);
});

```

How to convert XML to JSON in Python?

Jacob Smullyan wrote a utility called pesterfish which uses effbot's ElementTree to convert XML to JSON.

How to resolve "Input string was not in a correct format." error?

If using TextBox2.Text as the source for a numeric value, it must first be checked to see if a value exists, and then converted to integer.

If the text box is blank when Convert.ToInt32 is called, you will receive the System.FormatException. Suggest trying:

protected void SetImageWidth()
{
   try{
      Image1.Width = Convert.ToInt32(TextBox1.Text);
   }
   catch(System.FormatException)
   {
      Image1.Width = 100; // or other default value as appropriate in context.
   }
}

Tips for using Vim as a Java IDE?

Some tips:

  • Make sure you use vim (vi improved). Linux and some versions of UNIX symlink vi to vim.
  • You can get code completion with eclim
  • Or you can get vi functionality within Eclipse with viPlugin
  • Syntax highlighting is great with vim
  • Vim has good support for writing little macros like running ant/maven builds

Have fun :-)

What is the 'dynamic' type in C# 4.0 used for?

The dynamic keyword was added, together with many other new features of C# 4.0, to make it simpler to talk to code that lives in or comes from other runtimes, that has different APIs.

Take an example.

If you have a COM object, like the Word.Application object, and want to open a document, the method to do that comes with no less than 15 parameters, most of which are optional.

To call this method, you would need something like this (I'm simplifying, this is not actual code):

object missing = System.Reflection.Missing.Value;
object fileName = "C:\\test.docx";
object readOnly = true;
wordApplication.Documents.Open(ref fileName, ref missing, ref readOnly,
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing);

Note all those arguments? You need to pass those since C# before version 4.0 did not have a notion of optional arguments. In C# 4.0, COM APIs have been made easier to work with by introducing:

  1. Optional arguments
  2. Making ref optional for COM APIs
  3. Named arguments

The new syntax for the above call would be:

wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);

See how much easier it looks, how much more readable it becomes?

Let's break that apart:

                                    named argument, can skip the rest
                                                   |
                                                   v
wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);
                                 ^                         ^
                                 |                         |
                               notice no ref keyword, can pass
                               actual parameter values instead

The magic is that the C# compiler will now inject the necessary code, and work with new classes in the runtime, to do almost the exact same thing that you did before, but the syntax has been hidden from you, now you can focus on the what, and not so much on the how. Anders Hejlsberg is fond of saying that you have to invoke different "incantations", which is a sort of pun on the magic of the whole thing, where you typically have to wave your hand(s) and say some magic words in the right order to get a certain type of spell going. The old API way of talking to COM objects was a lot of that, you needed to jump through a lot of hoops in order to coax the compiler to compile the code for you.

Things break down in C# before version 4.0 even more if you try to talk to a COM object that you don't have an interface or class for, all you have is an IDispatch reference.

If you don't know what it is, IDispatch is basically reflection for COM objects. With an IDispatch interface you can ask the object "what is the id number for the method known as Save", and build up arrays of a certain type containing the argument values, and finally call an Invoke method on the IDispatch interface to call the method, passing all the information you've managed to scrounge together.

The above Save method could look like this (this is definitely not the right code):

string[] methodNames = new[] { "Open" };
Guid IID = ...
int methodId = wordApplication.GetIDsOfNames(IID, methodNames, methodNames.Length, lcid, dispid);
SafeArray args = new SafeArray(new[] { fileName, missing, missing, .... });
wordApplication.Invoke(methodId, ... args, ...);

All this for just opening a document.

VB had optional arguments and support for most of this out of the box a long time ago, so this C# code:

wordApplication.Documents.Open(@"C:\Test.docx", ReadOnly: true);

is basically just C# catching up to VB in terms of expressiveness, but doing it the right way, by making it extendable, and not just for COM. Of course this is also available for VB.NET or any other language built on top of the .NET runtime.

You can find more information about the IDispatch interface on Wikipedia: IDispatch if you want to read more about it. It's really gory stuff.

However, what if you wanted to talk to a Python object? There's a different API for that than the one used for COM objects, and since Python objects are dynamic in nature as well, you need to resort to reflection magic to find the right methods to call, their parameters, etc. but not the .NET reflection, something written for Python, pretty much like the IDispatch code above, just altogether different.

And for Ruby? A different API still.

JavaScript? Same deal, different API for that as well.

The dynamic keyword consists of two things:

  1. The new keyword in C#, dynamic
  2. A set of runtime classes that knows how to deal with the different types of objects, that implement a specific API that the dynamic keyword requires, and maps the calls to the right way of doing things. The API is even documented, so if you have objects that comes from a runtime not covered, you can add it.

The dynamic keyword is not, however, meant to replace any existing .NET-only code. Sure, you can do it, but it was not added for that reason, and the authors of the C# programming language with Anders Hejlsberg in the front, has been most adamant that they still regard C# as a strongly typed language, and will not sacrifice that principle.

This means that although you can write code like this:

dynamic x = 10;
dynamic y = 3.14;
dynamic z = "test";
dynamic k = true;
dynamic l = x + y * z - k;

and have it compile, it was not meant as a sort of magic-lets-figure-out-what-you-meant-at-runtime type of system.

The whole purpose was to make it easier to talk to other types of objects.

There's plenty of material on the internet about the keyword, proponents, opponents, discussions, rants, praise, etc.

I suggest you start with the following links and then google for more:

Getting rid of bullet points from <ul>

There must be something else.

Because:

   ul#otis {
     list-style-type: none;
   }

should just work.

Perhaps there is some CSS rule which overwrites it.

Use your DOM inspector to find out.

How to convert 'binary string' to normal string in Python3?

Please, see oficial encode() and decode() documentation from codecs library. utf-8 is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1 or utf_32.

How to get a responsive button in bootstrap 3

For anyone who may be interested, another approach is using @media queries to scale the buttons on different viewport widths..

Demo: http://bootply.com/93706

This Activity already has an action bar supplied by the window decor

I got this error due to a custome attribute inside, removing it fixed the issue.

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
..
        <item name="searchBarBgColor">#383838</item>  --> remove this line
    </style>

Version of Apache installed on a Debian machine

This works for my Debian:

$ /usr/sbin/apache2 -v

Kotlin: How to get and set a text to TextView in Android using Kotlin?

findViewById(R.id.android_text) does not need typecasting.

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

The minimum required:

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MessageSender {

    public static void sendHardCoded() throws AddressException, MessagingException {
        String to = "[email protected]";
        final String from = "[email protected]";

        Properties properties = new Properties();
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

        Session session = Session.getInstance(properties,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(from, "BeNice");
                    }
                });

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject("Hello");
        message.setText("What's up?");

        Transport.send(message);
    }

}

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

My solution was under Manage Nuget Packages for Solution... -- I had umpteen updates to do for quite a few packages.

Let me back up a half step and say that I screwed myself over because I moved the solution and projects from one folder to another... so things were already out of whack compared to where the projects thought things out to be. Everything moved over just fine, but apparently Nuget becomes confused unless you use a different approach than I did.

Back to the solution... I simply went to Manage Nuget Packages for Solution... >> Updates >> Microsoft and .NET and hit the Update All button.

Everything was back to normal and happy.

How to send email via Django?

Late, but:

In addition to the DEFAULT_FROM_EMAIL fix others have mentioned, and allowing less-secure apps to access the account, I had to navigate to https://accounts.google.com/DisplayUnlockCaptcha while signed in as the account in question to get Django to finally authenticate.

I went to that URL through a SSH tunnel to the web server to make sure the IP address was the same; I'm not totally sure if that's necessary but it can't hurt. You can do that like so: ssh -D 8080 -fN <username>@<host>, then set your web browser to use localhost:8080 as a SOCKS proxy.

Where does flask look for image files?

Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg in your static directory? If you move it to your static directory and update your HTML as such:

<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">

It should work.

Also, it is worth noting, there is a better way to structure this.

File structure:

app.py
static
   |----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
   |----index.html

app.py

from flask import Flask, render_template, url_for
app = Flask(__name__)

@app.route('/index', methods=['GET', 'POST'])
def lionel(): 
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

templates/index.html

<html>
  <head>

  </head>
  <body>
    <h1>Hi Lionel Messi</h1>

  <img src="{{url_for('static', filename='ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg')}}" />

  </body>

</html>

Doing it this way ensures that you are not hard-coding a URL path for your static assets.

How can I create a correlation matrix in R?

There are other ways to achieve this here: (Plot correlation matrix into a graph), but I like your version with the correlations in the boxes. Is there a way to add the variable names to the x and y column instead of just those index numbers? For me, that would make this a perfect solution. Thanks!

edit: I was trying to comment on the post by [Marc in the box], but I clearly don't know what I'm doing. However, I did manage to answer this question for myself.

if d is the matrix (or the original data frame) and the column names are what you want, then the following works:

axis(1, 1:dim(d)[2], colnames(d), las=2)
axis(2, 1:dim(d)[2], colnames(d), las=2)

las=0 would flip the names back to their normal position, mine were long, so I used las=2 to make them perpendicular to the axis.

edit2: to suppress the image() function printing numbers on the grid (otherwise they overlap your variable labels), add xaxt='n', e.g.:

image(x=seq(dim(x)[2]), y=seq(dim(y)[2]), z=COR, col=rev(heat.colors(20)), xlab="x column", ylab="y column", xaxt='n')

How to find children of nodes using BeautifulSoup

"How to find all a which are children of <li class=test> but not any others?"

Given the HTML below (I added another <a> to show te difference between select and select_one):

<div>
  <li class="test">
    <a>link1</a>
    <ul>
      <li>
        <a>link2</a>
      </li>
    </ul>
    <a>link3</a>
  </li>
</div>

The solution is to use child combinator (>) that is placed between two CSS selectors:

>>> soup.select('li.test > a')
[<a>link1</a>, <a>link3</a>]

In case you want to find only the first child:

>>> soup.select_one('li.test > a')
<a>link1</a>

data.frame rows to a list

Another alternative using library(purrr) (that seems to be a bit quicker on large data.frames)

flatten(by_row(xy.df, ..f = function(x) flatten_chr(x), .labels = FALSE))

Javascript return number of days,hours,minutes,seconds between two dates

my solution is not as clear as that, but I put it as another example

_x000D_
_x000D_
console.log(duration('2019-07-17T18:35:25.235Z', '2019-07-20T00:37:28.839Z'));_x000D_
_x000D_
function duration(t0, t1){_x000D_
    let d = (new Date(t1)) - (new Date(t0));_x000D_
    let weekdays     = Math.floor(d/1000/60/60/24/7);_x000D_
    let days         = Math.floor(d/1000/60/60/24 - weekdays*7);_x000D_
    let hours        = Math.floor(d/1000/60/60    - weekdays*7*24            - days*24);_x000D_
    let minutes      = Math.floor(d/1000/60       - weekdays*7*24*60         - days*24*60         - hours*60);_x000D_
    let seconds      = Math.floor(d/1000          - weekdays*7*24*60*60      - days*24*60*60      - hours*60*60      - minutes*60);_x000D_
    let milliseconds = Math.floor(d               - weekdays*7*24*60*60*1000 - days*24*60*60*1000 - hours*60*60*1000 - minutes*60*1000 - seconds*1000);_x000D_
    let t = {};_x000D_
    ['weekdays', 'days', 'hours', 'minutes', 'seconds', 'milliseconds'].forEach(q=>{ if (eval(q)>0) { t[q] = eval(q); } });_x000D_
    return t;_x000D_
}
_x000D_
_x000D_
_x000D_

How to retrieve unique count of a field using Kibana + Elastic Search

Create "topN" query on "clientip" and then histogram with count on "clientip" and set "topN" query as source. Then you will see count of different ips per time.

SQL JOIN, GROUP BY on three tables to get totals

First of all, shouldn't there be a CustomerId in the Invoices table? As it is, You can't perform this query for Invoices that have no payments on them as yet. If there are no payments on an invoice, that invoice will not even show up in the ouput of the query, even though it's an outer join...

Also, When a customer makes a payment, how do you know what Invoice to attach it to ? If the only way is by the InvoiceId on the stub that arrives with the payment, then you are (perhaps inappropriately) associating Invoices with the customer that paid them, rather than with the customer that ordered them... . (Sometimes an invoice can be paid by someone other than the customer who ordered the services)

List<Map<String, String>> vs List<? extends Map<String, String>>

You cannot assign expressions with types such as List<NavigableMap<String,String>> to the first.

(If you want to know why you can't assign List<String> to List<Object> see a zillion other questions on SO.)

JQuery Find #ID, RemoveClass and AddClass

.....

$("#testID #testID2").removeClass("test2").addClass("test3");

Because you have assigned an id to img too, you can simply do this too:

$("#testID2").removeClass("test2").addClass("test3");

And finally, you can do this too:

$("#testID img").removeClass("test2").addClass("test3");

How to identify object types in java

Use value instanceof YourClass

The APR based Apache Tomcat Native library was not found on the java.library.path

Regarding the original question asked in the title ...

  • sudo apt-get install libtcnative-1

  • or if you are on RHEL Linux yum install tomcat-native

The documentation states you need http://tomcat.apache.org/native-doc/

  • sudo apt-get install libapr1.0-dev libssl-dev
  • or RHEL yum install apr-devel openssl-devel

Calculating a directory's size using Python?

When size of the sub-directories is computed, it should update its parent's folder size and this will go on till it reaches the root parent.

The following function computes the size of the folder and all its sub-folders.

import os

def folder_size(path):
    parent = {}  # path to parent path mapper
    folder_size = {}  # storing the size of directories
    folder = os.path.realpath(path)

    for root, _, filenames in os.walk(folder):
        if root == folder:
            parent[root] = -1  # the root folder will not have any parent
            folder_size[root] = 0.0  # intializing the size to 0

        elif root not in parent:
            immediate_parent_path = os.path.dirname(root)  # extract the immediate parent of the subdirectory
            parent[root] = immediate_parent_path  # store the parent of the subdirectory
            folder_size[root] = 0.0  # initialize the size to 0

        total_size = 0
        for filename in filenames:
            filepath = os.path.join(root, filename)
            total_size += os.stat(filepath).st_size  # computing the size of the files under the directory
        folder_size[root] = total_size  # store the updated size

        temp_path = root  # for subdirectories, we need to update the size of the parent till the root parent
        while parent[temp_path] != -1:
            folder_size[parent[temp_path]] += total_size
            temp_path = parent[temp_path]

    return folder_size[folder]/1000000.0

Difference between string object and string literal

In the first case, there are two objects created.

In the second case, it's just one.

Although both ways str is referring to "abc".

Correct way to pause a Python program

I assume you want to pause without input.

Use:

time.sleep(seconds)

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

I originally asked this question I was looking for a Chrome (or FireFox) solution, but I stumbled across this feature in Internet Explorer developer tools. Pretty much what I'm looking for (except for the javascript)

Element Source with Style

Result:

Element Source with Style result

Ansible: Store command's stdout in new variable?

You have to store the content as a fact:

- set_fact:
    string_to_echo: "{{ command_output.stdout }}"

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

Here is the script I use in a Dockerfile based on windows/servercore to achieve complete PowerShellGallery setup through Artifactory mirrors (require access to GitHub releases too)

ARG ONEGET_PACKAGEMANAGEMENT="https://artifactory/artifactory/github-releases/OneGet/oneget/releases/download/1.4/PackageManagement.zip"
ARG ONEGET_ZIPFILE="C:/PackageManagement.zip"
 
RUN $ProviderPath = 'C:/Program Files/PackageManagement/ProviderAssemblies/nuget/2.8.5.208/'; `
    Invoke-WebRequest -Uri ${Env:ONEGET_PACKAGEMANAGEMENT} -OutFile ${Env:ONEGET_ZIPFILE}; `
    Expand-Archive ${Env:ONEGET_ZIPFILE} -DestinationPath "C:/" -Force; `
    New-Item -ItemType "directory" -Path $ProviderPath -Force; `
    Move-Item -Path "C:/PackageManagement/fullclr/Microsoft.PackageManagement.NuGetProvider.dll" -Destination $ProviderPath -Force; `
    Remove-Item -Recurse -Force -Path "C:/PackageManagement",${Env:ONEGET_ZIPFILE}; `
    Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.208 -Force; `
    Register-PSRepository -Name "artifactory-powershellgallery-remote" -SourceLocation "https://artifactory/artifactory/api/nuget/powershellgallery-remote"; `
    Unregister-PSRepository -Name PSGallery;

How do JavaScript closures work?

This is an attempt to clear up several (possible) misunderstandings about closures that appear in some of the other answers.

  • A closure is not only created when you return an inner function. In fact, the enclosing function does not need to return at all in order for its closure to be created. You might instead assign your inner function to a variable in an outer scope, or pass it as an argument to another function where it could be called immediately or any time later. Therefore, the closure of the enclosing function is probably created as soon as the enclosing function is called since any inner function has access to that closure whenever the inner function is called, before or after the enclosing function returns.
  • A closure does not reference a copy of the old values of variables in its scope. The variables themselves are part of the closure, and so the value seen when accessing one of those variables is the latest value at the time it is accessed. This is why inner functions created inside of loops can be tricky, since each one has access to the same outer variables rather than grabbing a copy of the variables at the time the function is created or called.
  • The "variables" in a closure include any named functions declared within the function. They also include arguments of the function. A closure also has access to its containing closure's variables, all the way up to the global scope.
  • Closures use memory, but they don't cause memory leaks since JavaScript by itself cleans up its own circular structures that are not referenced. Internet Explorer memory leaks involving closures are created when it fails to disconnect DOM attribute values that reference closures, thus maintaining references to possibly circular structures.

Querying Windows Active Directory server using ldapsearch from command line

The short answer is "yes". A sample ldapsearch command to query an Active Directory server is:

ldapsearch \
    -x -h ldapserver.mydomain.com \
    -D "[email protected]" \
    -W \
    -b "cn=users,dc=mydomain,dc=com" \
    -s sub "(cn=*)" cn mail sn

This would connect to an AD server at hostname ldapserver.mydomain.com as user [email protected], prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com subtree.

See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.

Excel VBA App stops spontaneously with message "Code execution has been halted"

I have had this problem also using excel 2007 with a foobar.xlsm (macro enabled ) workbook which would get the "Code execution has been interrupted" by simply trying to close the workbook on the red X in the right corner with no macros running at all, or any "initialize" form, workbook, or workheet macros either. The options I got were "End" or "Continue", Debug was always greyed out. I did as a previous poster suggested Control Panel->Programs and Features-> right click "Microsoft Office Proffesional 2007" (in my case) ->change->repair.

This resolved the problem for me. I might add this happened soon after a MS update and I also found an addin in Excel called "Team Foundation" from Microsoft which I certainly didnt install voluntarily

React prevent event bubbling in nested components on click

I had issues getting event.stopPropagation() working. If you do too, try moving it to the top of your click handler function, that was what I needed to do to stop the event from bubbling. Example function:

  toggleFilter(e) {
    e.stopPropagation(); // If moved to the end of the function, will not work
    let target = e.target;
    let i = 10; // Sanity breaker

    while(true) {
      if (--i === 0) { return; }
      if (target.classList.contains("filter")) {
        target.classList.toggle("active");
        break;
      }
      target = target.parentNode;
    }
  }

Test a string for a substring

if "ABCD" in "xxxxABCDyyyy":
    # whatever

How to Alter a table for Identity Specification is identity SQL Server

You don't set value to default in a table. You should clear the option "Default value or Binding" first.

Export to xls using angularjs

$scope.ExportExcel= function () { //function define in html tag                          

                        //export to excel file
                        var tab_text = '<table border="1px" style="font-size:20px" ">';
                        var textRange;
                        var j = 0;
                        var tab = document.getElementById('TableExcel'); // id of table
                        var lines = tab.rows.length;

                        // the first headline of the table
                        if (lines > 0) {
                            tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
                        }

                        // table data lines, loop starting from 1
                        for (j = 1 ; j < lines; j++) {
                            tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</tr>";                                
                        }

                        tab_text = tab_text + "</table>";
                        tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");          //remove if u want links in your table
                        tab_text = tab_text.replace(/<img[^>]*>/gi, "");             // remove if u want images in your table
                        tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

                        // console.log(tab_text); // aktivate so see the result (press F12 in browser)               
                        var fileName = 'report.xls'                            
                        var exceldata = new Blob([tab_text], { type: "application/vnd.ms-excel;charset=utf-8" }) 

                        if (window.navigator.msSaveBlob) { // IE 10+
                            window.navigator.msSaveOrOpenBlob(exceldata, fileName);
                            //$scope.DataNullEventDetails = true;
                        } else {
                            var link = document.createElement('a'); //create link download file
                            link.href = window.URL.createObjectURL(exceldata); // set url for link download
                            link.setAttribute('download', fileName); //set attribute for link created
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                        }

                    }

        //html of button 

Is there a numpy builtin to reject outliers from a list

I would like to provide two methods in this answer, solution based on "z score" and solution based on "IQR".

The code provided in this answer works on both single dim numpy array and multiple numpy array.

Let's import some modules firstly.

import collections
import numpy as np
import scipy.stats as stat
from scipy.stats import iqr

z score based method

This method will test if the number falls outside the three standard deviations. Based on this rule, if the value is outlier, the method will return true, if not, return false.

def sd_outlier(x, axis = None, bar = 3, side = 'both'):
    assert side in ['gt', 'lt', 'both'], 'Side should be `gt`, `lt` or `both`.'

    d_z = stat.zscore(x, axis = axis)

    if side == 'gt':
        return d_z > bar
    elif side == 'lt':
        return d_z < -bar
    elif side == 'both':
        return np.abs(d_z) > bar

IQR based method

This method will test if the value is less than q1 - 1.5 * iqr or greater than q3 + 1.5 * iqr, which is similar to SPSS's plot method.

def q1(x, axis = None):
    return np.percentile(x, 25, axis = axis)

def q3(x, axis = None):
    return np.percentile(x, 75, axis = axis)

def iqr_outlier(x, axis = None, bar = 1.5, side = 'both'):
    assert side in ['gt', 'lt', 'both'], 'Side should be `gt`, `lt` or `both`.'

    d_iqr = iqr(x, axis = axis)
    d_q1 = q1(x, axis = axis)
    d_q3 = q3(x, axis = axis)
    iqr_distance = np.multiply(d_iqr, bar)

    stat_shape = list(x.shape)

    if isinstance(axis, collections.Iterable):
        for single_axis in axis:
            stat_shape[single_axis] = 1
    else:
        stat_shape[axis] = 1

    if side in ['gt', 'both']:
        upper_range = d_q3 + iqr_distance
        upper_outlier = np.greater(x - upper_range.reshape(stat_shape), 0)
    if side in ['lt', 'both']:
        lower_range = d_q1 - iqr_distance
        lower_outlier = np.less(x - lower_range.reshape(stat_shape), 0)

    if side == 'gt':
        return upper_outlier
    if side == 'lt':
        return lower_outlier
    if side == 'both':
        return np.logical_or(upper_outlier, lower_outlier)

Finally, if you want to filter out the outliers, use a numpy selector.

Have a nice day.

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

Try this:

PM> Enable-migrations -force
PM> Add-migration MigrationName
PM> Update-database -force

Why can't I make a vector of references?

The component type of containers like vectors must be assignable. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g. vector<const int> is not allowed.

How to inject window into a service?

I used OpaqueToken for 'Window' string:

import {unimplemented} from '@angular/core/src/facade/exceptions';
import {OpaqueToken, Provider} from '@angular/core/index';

function _window(): any {
    return window;
}

export const WINDOW: OpaqueToken = new OpaqueToken('WindowToken');

export abstract class WindowRef {
    get nativeWindow(): any {
        return unimplemented();
    }
}

export class BrowserWindowRef extends WindowRef {
    constructor() {
        super();
    }
    get nativeWindow(): any {
        return _window();
    }
}


export const WINDOW_PROVIDERS = [
    new Provider(WindowRef, { useClass: BrowserWindowRef }),
    new Provider(WINDOW, { useFactory: _window, deps: [] }),
];

And used just to import WINDOW_PROVIDERS in bootstrap in Angular 2.0.0-rc-4.

But with the release of Angular 2.0.0-rc.5 I need to create a separate module:

import { NgModule } from '@angular/core';
import { WINDOW_PROVIDERS } from './window';

@NgModule({
    providers: [WINDOW_PROVIDERS]
})
export class WindowModule { }

and just defined in the imports property of my main app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { WindowModule } from './other/window.module';

import { AppComponent } from './app.component';

@NgModule({
    imports: [ BrowserModule, WindowModule ],
    declarations: [ ... ],
    providers: [ ... ],
    bootstrap: [ AppComponent ]
})
export class AppModule {}

Resizing an Image without losing any quality

See if you like the image resizing quality of this open source ASP.NET module. There's a live demo, so you can mess around with it yourself. It yields results that are (to me) impossible to distinguish from Photoshop output. It also has similar file sizes - MS did a good job on their JPEG encoder.

Excel VBA If cell.Value =... then

You can use the Like operator with a wildcard to determine whether a given substring exists in a string, for example:

If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If

In this example the * character in "*Word1*" is a wildcard character which matches zero or more characters.

NOTE: The Like operator is case-sensitive, so "Word1" Like "word1" is false, more information can be found on this MSDN page.

Can't find System.Windows.Media namespace?

For Visual Studio 2017

Find "References" in Solution explorer

Right click "References"

Choose "Add Reference..."

Find "Presentation.Core" list and check checkbox

Click OK

Unicode via CSS :before

In CSS, FontAwesome unicode works only when the correct font family is declared (version 4 or less):

font-family: "FontAwesome";
content: "\f066";

Update - Version 5 has different names:

Free

font-family: "Font Awesome 5 Free"

Pro

font-family: "Font Awesome 5 Pro"

Brands

font-family: "Font Awesome 5 Brands"

See this related answer: https://stackoverflow.com/a/48004111/2575724

As per comment (BuddyZ) some more info here https://fontawesome.com/how-to-use/on-the-desktop/setup/getting-started

Argparse: Required arguments listed under "optional arguments"?

One more time, building off of @RalphyZ

This one doesn't break the exposed API.

from argparse import ArgumentParser, SUPPRESS
# Disable default help
parser = ArgumentParser(add_help=False)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')

# Add back help 
optional.add_argument(
    '-h',
    '--help',
    action='help',
    default=SUPPRESS,
    help='show this help message and exit'
)
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')

Which will show the same as above and should survive future versions:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
           [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  -h, --help                    show this help message and exit
  --optional_arg OPTIONAL_ARG