Programs & Examples On #Wii

Video game device developed by Nintendo.

Best HTTP Authorization header type for JWT

Short answer

The Bearer authentication scheme is what you are looking for.

Long answer

Is it related to bears?

Errr... No :)

According to the Oxford Dictionaries, here's the definition of bearer:

bearer /'b??r?/
noun

  1. A person or thing that carries or holds something.

  2. A person who presents a cheque or other order to pay money.

The first definition includes the following synonyms: messenger, agent, conveyor, emissary, carrier, provider.

And here's the definition of bearer token according to the RFC 6750:

1.2. Terminology

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer authentication scheme is registered in IANA and originally defined in the RFC 6750 for the OAuth 2.0 authorization framework, but nothing stops you from using the Bearer scheme for access tokens in applications that don't use OAuth 2.0.

Stick to the standards as much as you can and don't create your own authentication schemes.


An access token must be sent in the Authorization request header using the Bearer authentication scheme:

2.1. Authorization Request Header Field

When sending the access token in the Authorization request header field defined by HTTP/1.1, the client uses the Bearer authentication scheme to transmit the access token.

For example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM

[...]

Clients SHOULD make authenticated requests with a bearer token using the Authorization request header field with the Bearer HTTP authorization scheme. [...]

In case of invalid or missing token, the Bearer scheme should be included in the WWW-Authenticate response header:

3. The WWW-Authenticate Response Header Field

If the protected resource request does not include authentication credentials or does not contain an access token that enables access to the protected resource, the resource server MUST include the HTTP WWW-Authenticate response header field [...].

All challenges defined by this specification MUST use the auth-scheme value Bearer. This scheme MUST be followed by one or more auth-param values. [...].

For example, in response to a protected resource request without authentication:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

And in response to a protected resource request with an authentication attempt using an expired access token:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                         error="invalid_token",
                         error_description="The access token expired"

What is secret key for JWT based authentication and how to generate it?

You can write your own generator. The secret key is essentially a byte array. Make sure that the string that you convert to a byte array is base64 encoded.

In Java, you could do something like this.

String key = "random_secret_key";
String base64Key = DatatypeConverter.printBase64Binary(key.getBytes());
byte[] secretBytes = DatatypeConverter.parseBase64Binary(base64Key);

Change the Blank Cells to "NA"

A more eye-friendly solution using dplyr would be

require(dplyr)

## fake blank cells
iris[1,1]=""

## define a helper function
empty_as_na <- function(x){
    if("factor" %in% class(x)) x <- as.character(x) ## since ifelse wont work with factors
    ifelse(as.character(x)!="", x, NA)
}

## transform all columns
iris %>% mutate_each(funs(empty_as_na)) 

To apply the correction to just a subset of columns you can specify columns of interest using dplyr's column matching syntax. Example:mutate_each(funs(empty_as_na), matches("Width"), Species)

In case you table contains dates you should consider using a more typesafe version of ifelse

How can I change the width and height of slides on Slick Carousel?

I found good solution myself. Since slick slider is still used nowadays i'll post my approach.

@RuivBoas answer is partly correct. - It can change the width of the slide but it can break the slider. Why?

Slick slider may exceed browser width. Actual container width is set to value that can accomodate all it's slides.

The best solution for setting slide width is to use width of the actual browser window. It works best with responsive design.

For example 2 slides with absorbed width

CSS

.slick-slide {
    width: 50vw;
    // for absorbing width from @Ken Wheeler answer
    box-sizing: border-box;
}

JS

$(document).on('ready', function () {
            $("#container").slick({
                variableWidth: true,
                slidesToShow: 2,
                slidesToScroll: 2
            });
        });

HTML markup

<div id="container">
    <div><img/></div>
    <div><img/></div>
    <div><img/></div>
</div>

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

This looks like a Bootstrap issue...

Currently, here's a workaround : add .col-xs-12 to your responsive image.

Bootply

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

Add a new line to the end of a JtextArea

Instead of using JTextArea.setText(String text), use JTextArea.append(String text).

Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.

This will add text on to the end of your JTextArea.

Another option would be to use getText() to get the text from the JTextArea, then manipulate the String (add or remove or change the String), then use setText(String text) to set the text of the JTextArea to be the new String.

What does %>% mean in R

The infix operator %>% is not part of base R, but is in fact defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.

What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris gets passed to head():

library(magrittr)
iris %>% head()
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Thus, iris %>% head() is equivalent to head(iris).

Often, %>% is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris is passed to head(), then the result of that is passed to summary().

iris %>% head() %>% summary()

Thus iris %>% head() %>% summary() is equivalent to summary(head(iris)). Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.

What does on_delete do on Django models?

Let's say you have two models, one named Person and another one named Companies.

By definition, one person can create more than one company.

Considering a company can have one and only one person, we want that when a person is deleted that all the companies associated with that person also be deleted.

So, we start by creating a Person model, like this

class Person(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.id+self.name

Then, the Companies model can look like this

class Companies(models.Model):
    title = models.CharField(max_length=20)
    description=models.CharField(max_length=10)
    person= models.ForeignKey(Person,related_name='persons',on_delete=models.CASCADE)

Notice the usage of on_delete=models.CASCADE in the model Companies. That is to delete all companies when the person that owns it (instance of class Person) is deleted.

How to reset form body in bootstrap modal box?

You can make a JavaScript function to do that:

$.clearInput = function () {
        $('form').find('input[type=text], input[type=password], input[type=number], input[type=email], textarea').val('');
};

and then you can call that function each time your modal is hidden:

$('#Your_Modal').on('hidden', function () {
        $.clearInput();
});

How to add footnotes to GitHub-flavoured Markdown?

I used a variant of Mateo's solution. I'm using this in Rmd files written in github flavored markdown (gfm) for a Jekyll powered website but the same Rmd files are being used to produce pdfs in various contexts. The Rmd files are math heavy and the math is displayed with MathJax on the website. So I needed a solution that works with gfm that is processed via Jekyll, works with pandoc->pdflatex, and is compatible with MathJax.

snippet from Rmd file (which is gfm)

Here is a paragraph with an footnote <span id="a1">[[1]](#f1)</span>.

Footnotes
=========

1. <span id="f1"></span> This is a footnote. [$\hookleftarrow$](#a1)

$\hookleftarrow$ is latex, which works for me since I always have MathJax enabled. I use that to make sure it shows up correctly in my pdfs. I put my footnotes in square brackets because superscript is confusing if I am putting a footnote on some inline math.

Here it is in action: https://eeholmes.github.io/posts/2016-5-18-FI-recursion-1/

These notes can be put anywhere in the Rmd. I am putting in a list at the end so they are technically endnotes.

How to remove all .svn directories from my application directories

Alternatively, if you want to export a copy without modifying the working copy, you can use rsync:

rsync -a --exclude .svn path/to/working/copy path/to/export

Switch statement multiple cases in JavaScript

Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found, so you could write it like:

switch (varName)
{
   case "afshin":
   case "saeed":
   case "larry": 
       alert('Hey');
       break;

   default: 
       alert('Default case');
}

In Node.js, how do I "include" functions from my other files?

I was also looking for a NodeJS 'include' function and I checked the solution proposed by Udo G - see message https://stackoverflow.com/a/8744519/2979590. His code doesn't work with my included JS files. Finally I solved the problem like that:

var fs = require("fs");

function read(f) {
  return fs.readFileSync(f).toString();
}
function include(f) {
  eval.apply(global, [read(f)]);
}

include('somefile_with_some_declarations.js');

Sure, that helps.

Error: TypeError: $(...).dialog is not a function

if some reason two versions of jQuery are loaded (which is not recommended), calling $.noConflict(true) from the second version will return the globally scoped jQuery variables to those of the first version.

Some times it could be issue with older version (or not stable version) of JQuery files

Solution use $.noConflict();

<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
   $("#opener").click(function() {
            $("#dialog1").dialog('open');
    });
});
// Code that uses other library's $ can follow here.
</script>

Edit and replay XHR chrome/firefox etc?

No need to install 3rd party extensions!

There exists the javascript-snippet, which you can add as browser-bookmark and then activate on any site to track & modify the requests. It looks like:

enter image description here

For further instructions, review the github page.

How do you represent a JSON array of strings?

Basically yes, JSON is just a javascript literal representation of your value so what you said is correct.

You can find a pretty clear and good explanation of JSON notation on http://json.org/

Android Studio: Application Installation Failed

I solve this problem by: Enable Instant Run

Settings>Build, Execution, Deployment>Instant Run

Add / remove input field dynamically with jQuery

Jquery Code

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

HTML CODE

<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

{"a":"\u00e1"} and {"a":"á"} are different ways to write the same JSON document; The JSON decoder will decode the unicode escape.

In php 5.4+, php's json_encode does have the JSON_UNESCAPED_UNICODE option for plain output. On older php versions, you can roll out your own JSON encoder that does not encode non-ASCII characters, or use Pear's JSON encoder and remove line 349 to 433.

What is the yield keyword used for in C#?

Iteration. It creates a state machine "under the covers" that remembers where you were on each additional cycle of the function and picks up from there.

iOS: Compare two dates

According to Apple documentation of NSDate compare:

Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.

- (NSComparisonResult)compare:(NSDate *)anotherDate

Parameters anotherDate

The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.

Return Value

If:

The receiver and anotherDate are exactly equal to each other, NSOrderedSame

The receiver is later in time than anotherDate, NSOrderedDescending

The receiver is earlier in time than anotherDate, NSOrderedAscending

In other words:

if ([date1 compare:date2] == NSOrderedSame) ...

Note that it might be easier in your particular case to read and write this :

if ([date2 isEqualToDate:date2]) ...

See Apple Documentation about this one.

What characters are allowed in an email address?

You can start from wikipedia article:

  • Uppercase and lowercase English letters (a-z, A-Z)
  • Digits 0 to 9
  • Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  • Character . (dot, period, full stop) provided that it is not the first or last character, and provided also that it does not appear two or more times consecutively.

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

Excel VBA Check if directory exists error

To check for the existence of a directory using Dir, you need to specify vbDirectory as the second argument, as in something like:

If Dir("C:\2013 Recieved Schedules" & "\" & client, vbDirectory) = "" Then

Note that, with vbDirectory, Dir will return a non-empty string if the specified path already exists as a directory or as a file (provided the file doesn't have any of the read-only, hidden, or system attributes). You could use GetAttr to be certain it's a directory and not a file.

What is FCM token in Firebase?

I have an update about "Firebase Cloud Messaging token" which I could get an information.

I really wanted to know about that change so just sent a mail to Support team. The Firebase Cloud Messaging token will get back to Server key soon again. There will be nothing to change. We can see Server key again after soon.

How to get row count in an Excel file using POI library?

There are two Things you can do

use

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();

or

int noOfColumns = sh.getRow(0).getLastCellNum();

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)

  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

This problem is due to:

  • an old version of pip (6.1.1) being installed for Python 2.7
  • multiple copies of Python 2.7 installed on the Trusty Beta image
  • a different location for Python 2.7 being used for sudo

It's all a bit complicated and better explained here https://github.com/travis-ci/travis-ci/issues/4989.

My solution was to install with user travis instead of sudo:

- pip2.7 install --upgrade --user travis pip setuptools wheel virtualenv

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

TCPDF ERROR: Some data has already been output, can't send PDF file

For those who are still facing this issue try adding:

libxml_use_internal_errors(true);

before the loadHtml call and add

libxml_use_internal_errors(false);

after the call.

This solved it for me.

How can I save a screenshot directly to a file in Windows?

Might I suggest WinSnap http://www.ntwind.com/software/winsnap/download-free-version.html. It provides an autosave option and capture the alt+printscreen and other key combinations to capture screen, windows, dialog, etc.

Select info from table where row has max date

Using an in can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:

SELECT *
  FROM (SELECT msisdn
              ,callid
              ,Change_color
              ,play_file_name
              ,date_played
          FROM insert_log
         WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
        ORDER BY callid ASC) t1
       JOIN (SELECT MAX(date_played) AS date_played
               FROM insert_log GROUP BY callid) t2
         ON t1.date_played = t2.date_played

php return 500 error but no error log

If you still have 500 error and no logs you can try to execute from command line:

php -f file.php

it will not work exactly like in a browser (from server) but if there is syntax error in your code, you will see error message in console.

Simplest way to detect keypresses in javascript

With plain Javascript, the simplest is:

document.onkeypress = function (e) {
    e = e || window.event;
    // use e.keyCode
};

But with this, you can only bind one handler for the event.

In addition, you could use the following to be able to potentially bind multiple handlers to the same event:

addEvent(document, "keypress", function (e) {
    e = e || window.event;
    // use e.keyCode
});

function addEvent(element, eventName, callback) {
    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    } else {
        element["on" + eventName] = callback;
    }
}

In either case, keyCode isn't consistent across browsers, so there's more to check for and figure out. Notice the e = e || window.event - that's a normal problem with Internet Explorer, putting the event in window.event instead of passing it to the callback.

References:

With jQuery:

$(document).on("keypress", function (e) {
    // use e.which
});

Reference:

Other than jQuery being a "large" library, jQuery really helps with inconsistencies between browsers, especially with window events...and that can't be denied. Hopefully it's obvious that the jQuery code I provided for your example is much more elegant and shorter, yet accomplishes what you want in a consistent way. You should be able to trust that e (the event) and e.which (the key code, for knowing which key was pressed) are accurate. In plain Javascript, it's a little harder to know unless you do everything that the jQuery library internally does.

Note there is a keydown event, that is different than keypress. You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown

As for suggesting what to use, I would definitely suggest using jQuery if you're up for learning the framework. At the same time, I would say that you should learn Javascript's syntax, methods, features, and how to interact with the DOM. Once you understand how it works and what's happening, you should be more comfortable working with jQuery. To me, jQuery makes things more consistent and is more concise. In the end, it's Javascript, and wraps the language.

Another example of jQuery being very useful is with AJAX. Browsers are inconsistent with how AJAX requests are handled, so jQuery abstracts that so you don't have to worry.

Here's something that might help decide:

Change the spacing of tick marks on the axis of a plot?

There are at least two ways for achieving this in base graph (my examples are for the x-axis, but work the same for the y-axis):

  1. Use par(xaxp = c(x1, x2, n)) or plot(..., xaxp = c(x1, x2, n)) to define the position (x1 & x2) of the extreme tick marks and the number of intervals between the tick marks (n). Accordingly, n+1 is the number of tick marks drawn. (This works only if you use no logarithmic scale, for the behavior with logarithmic scales see ?par.)

  2. You can suppress the drawing of the axis altogether and add the tick marks later with axis().
    To suppress the drawing of the axis use plot(... , xaxt = "n").
    Then call axis() with side, at, and labels: axis(side = 1, at = v1, labels = v2). With side referring to the side of the axis (1 = x-axis, 2 = y-axis), v1 being a vector containing the position of the ticks (e.g., c(1, 3, 5) if your axis ranges from 0 to 6 and you want three marks), and v2 a vector containing the labels for the specified tick marks (must be of same length as v1, e.g., c("group a", "group b", "group c")). See ?axis and my updated answer to a post on stats.stackexchange for an example of this method.

Angular 2.0 and Modal Dialog

  • Angular 2 and up
  • Bootstrap css (animation is preserved)
  • NO JQuery
  • NO bootstrap.js
  • Supports custom modal content (just like accepted answer)
  • Recently added support for multiple modals on top of each other.

`

@Component({
  selector: 'app-component',
  template: `
  <button type="button" (click)="modal.show()">test</button>
  <app-modal #modal>
    <div class="app-modal-header">
      header
    </div>
    <div class="app-modal-body">
      Whatever content you like, form fields, anything
    </div>
    <div class="app-modal-footer">
      <button type="button" class="btn btn-default" (click)="modal.hide()">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
    </div>
  </app-modal>
  `
})
export class AppComponent {
}

@Component({
  selector: 'app-modal',
  template: `
  <div (click)="onContainerClicked($event)" class="modal fade" tabindex="-1" [ngClass]="{'in': visibleAnimate}"
       [ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <ng-content select=".app-modal-header"></ng-content>
        </div>
        <div class="modal-body">
          <ng-content select=".app-modal-body"></ng-content>
        </div>
        <div class="modal-footer">
          <ng-content select=".app-modal-footer"></ng-content>
        </div>
      </div>
    </div>
  </div>
  `
})
export class ModalComponent {

  public visible = false;
  public visibleAnimate = false;

  public show(): void {
    this.visible = true;
    setTimeout(() => this.visibleAnimate = true, 100);
  }

  public hide(): void {
    this.visibleAnimate = false;
    setTimeout(() => this.visible = false, 300);
  }

  public onContainerClicked(event: MouseEvent): void {
    if ((<HTMLElement>event.target).classList.contains('modal')) {
      this.hide();
    }
  }
}

To show the backdrop, you'll need something like this CSS:

.modal {
  background: rgba(0,0,0,0.6);
}

The example now allows for multiple modals at the same time. (see the onContainerClicked() method).

For Bootstrap 4 css users, you need to make 1 minor change (because a css class name was updated from Bootstrap 3). This line: [ngClass]="{'in': visibleAnimate}" should be changed to: [ngClass]="{'show': visibleAnimate}"

To demonstrate, here is a plunkr

How to rotate x-axis tick labels in Pandas barplot

You can use set_xticklabels()

ax.set_xticklabels(df['Names'], rotation=90, ha='right')

How to select a node of treeview programmatically in c#?

TreeViewItem tempItem = new TreeViewItem();
TreeViewItem tempItem1 = new TreeViewItem(); 
tempItem =  (TreeViewItem) treeView1.Items.GetItemAt(0);    // Selecting the first of the top level nodes
tempItem1 = (TreeViewItem)tempItem.Items.GetItemAt(0);      // Selecting the first child of the first first level node
SelectedCategoryHeaderString = tempItem.Header.ToString();  // gets the header for the first top level node
SelectedCategoryHeaderString = tempItem1.Header.ToString(); // gets the header for the first child node of the first top level node
tempItem.IsExpanded = true;         //  will expand the first node

Prime numbers between 1 to 100 in C Programming Language

#include<stdio.h>
main()
{
    int i,j,k;
    for(i=2;i<=100;i++)
    {
        k=0;
        for(j=2;j<=i;j++)
        {
            if(i%j==0)
            k++;
        }
        if(k==1)
        printf("%d\t",i);
    }
}

DateTimePicker: pick both date and time

I'm afraid the DateTimePicker control doesn't have the ability to do those things. It's a pretty basic (and frustrating!) control. Your best option may be to find a third-party control that does what you want.

For the option of typing the date and time manually, you could build a custom component with a TextBox/DateTimePicker combination to accomplish this, and it might work reasonably well, if third-party controls are not an option.

What is an optional value in Swift?

Optional value allows you to show absence of value. Little bit like NULL in SQL or NSNull in Objective-C. I guess this will be an improvement as you can use this even for "primitive" types.

// Reimplement the Swift standard library's optional type
enum OptionalValue<T> {
    case None
    case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/gb/jEUH0.l

T-SQL How to select only Second row from a table?

No need of row number functions if field ID is unique.

SELECT TOP 1 *
FROM (
  SELECT TOP 2 * 
  FROM yourTable
  ORDER BY ID
) z
ORDER BY ID DESC

Android translate animation - permanently move View to new position using AnimationListener

I usually prefer to work with deltas in translate animation, since it avoids a lot of confusion.

Try this out, see if it works for you:

TranslateAnimation anim = new TranslateAnimation(0, amountToMoveRight, 0, amountToMoveDown);
anim.setDuration(1000);

anim.setAnimationListener(new TranslateAnimation.AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation) { }

    @Override
    public void onAnimationRepeat(Animation animation) { }

    @Override
    public void onAnimationEnd(Animation animation) 
    {
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
        params.topMargin += amountToMoveDown;
        params.leftMargin += amountToMoveRight;
        view.setLayoutParams(params);
    }
});

view.startAnimation(anim);

Make sure to make amountToMoveRight / amountToMoveDown final

Hope this helps :)

Latex - Change margins of only a few pages

I had the same problem in a beamer presentation. For me worked using the columns environment:

\begin{frame}
  \begin{columns}
    \column{1.2\textwidth}
    \begin{figure}
      \subfigure{\includegraphics[width=.49\textwidth]{1.png}}
      \subfigure{\includegraphics[width=.49\textwidth]{2.png}}
    \end{figure}
   \end{columns}
\end{frame}

disable a hyperlink using jQuery

Append a class containing pointer-events:non

.active a{ //css
text-decoration: underline;
background-color: #fff;
pointer-events: none;}


$(this).addClass('active');

recursively use scp but excluding some folders

You can specify GLOBIGNORE and use the pattern *

GLOBIGNORE='ignore1:ignore2' scp -r source/* remoteurl:remoteDir

You may wish to have general rules which you combine or override by using export GLOBIGNORE, but for ad-hoc usage simply the above will do. The : character is used as delimiter for multiple values.

CORS - How do 'preflight' an httprequest?

Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:

  • jQuery sent its XHR request using only limited headers; only 'Origin' was sent.
  • No preflight request was needed.
  • The server only had to detect such a request, and add the "Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN'] header, after detecting that this was a cross-origin XHR.

PHP Code sample:

if (!empty($_SERVER['HTTP_ORIGIN'])) {
    // Uh oh, this XHR comes from outer space...
    // Use this opportunity to filter out referers that shouldn't be allowed to see this request
    if (!preg_match('@\.partner\.domain\.net$@'))
        die("End of the road if you're not my business partner.");

    // otherwise oblige
    header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
    // local request, no need to send a specific header for CORS
}

In particular, don't add an exit; as no preflight is needed.

how to pass parameter from @Url.Action to controller function

you can pass it this way :

Url.Action("CreatePerson", "Person", new RouteValueDictionary(new { id = id }));

OR can also pass this way

Url.Action("CreatePerson", "Person", new { id = id });

flutter remove back button on appbar

  appBar: new AppBar(title: new Text("SmartDocs SPAY"),backgroundColor: Colors.blueAccent, automaticallyImplyLeading:false,
        leading: new Container(),
      ),

It is working Fine

Oracle : how to subtract two dates and get minutes of the result

I can handle this way:

select to_number(to_char(sysdate,'MI')) - to_number(to_char(*YOUR_DATA_VALUE*,'MI')),max(exp_time)  from ...

Or if you want to the hour just change the MI;

select to_number(to_char(sysdate,'HH24')) - to_number(to_char(*YOUR_DATA_VALUE*,'HH24')),max(exp_time)  from ...

the others don't work for me. Good luck.

hardcoded string "row three", should use @string resource

It is not good practice to hard code strings into your layout files. You should add them to a string resource file and then reference them from your layout.

This allows you to update every occurrence of the word "Yellow" in all layouts at the same time by just editing your strings.xml file.

It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language.

example: XML file saved at res/values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="yellow">Yellow</string>
</resources>

This layout XML applies a string to a View:

<TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="@string/yellow" />

Similarly colors should be stored in colors.xml and then referenced by using @color/color_name

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="Black">#000000</color>
</resources>

Break when a value changes using the Visual Studio debugger

Update in 2019:

This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.

https://blogs.msdn.microsoft.com/visualstudio/2019/02/12/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/

Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!

Catching "Maximum request length exceeded"

You can solve this by increasing the maximum request length and execution time out in your web.config:

-Please Clarify the maximum execution time out grater then 1200

<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <httpRuntime maxRequestLength="102400" executionTimeout="1200" /> </system.web> </configuration>

Slack clean all messages (~8K) in a channel

Here is a great chrome extension to bulk delete your slack channel/group/im messages - https://slackext.com/deleter , where you can filter the messages by star, time range, or users. BTW, it also supports load all messages in recent version, then you can load your ~8k messages as you need.

Javascript: console.log to html

I come a bit late with a more advanced version of Arun P Johny's answer. His solution doesn't handle multiple console.log() arguments and doesn't give an access to the original function.

Here's my version:

_x000D_
_x000D_
(function (logger) {_x000D_
    console.old = console.log;_x000D_
    console.log = function () {_x000D_
        var output = "", arg, i;_x000D_
_x000D_
        for (i = 0; i < arguments.length; i++) {_x000D_
            arg = arguments[i];_x000D_
            output += "<span class=\"log-" + (typeof arg) + "\">";_x000D_
_x000D_
            if (_x000D_
                typeof arg === "object" &&_x000D_
                typeof JSON === "object" &&_x000D_
                typeof JSON.stringify === "function"_x000D_
            ) {_x000D_
                output += JSON.stringify(arg);   _x000D_
            } else {_x000D_
                output += arg;   _x000D_
            }_x000D_
_x000D_
            output += "</span>&nbsp;";_x000D_
        }_x000D_
_x000D_
        logger.innerHTML += output + "<br>";_x000D_
        console.old.apply(undefined, arguments);_x000D_
    };_x000D_
})(document.getElementById("logger"));_x000D_
_x000D_
// Testing_x000D_
console.log("Hi!", {a:3, b:6}, 42, true);_x000D_
console.log("Multiple", "arguments", "here");_x000D_
console.log(null, undefined);_x000D_
console.old("Eyy, that's the old and boring one.");
_x000D_
body {background: #333;}_x000D_
.log-boolean,_x000D_
.log-undefined {color: magenta;}_x000D_
.log-object,_x000D_
.log-string {color: orange;}_x000D_
.log-number {color: cyan;}
_x000D_
<pre id="logger"></pre>
_x000D_
_x000D_
_x000D_

I took it a tiny bit further and added a class to each log so you can color it. It outputs all arguments as seen in the Chrome console. You also have access to the old log via console.old().

Here's a minified version of the script above to paste inline, just for you:

<script>
    !function(o){console.old=console.log,console.log=function(){var n,e,t="";for(e=0;e<arguments.length;e++)t+='<span class="log-'+typeof(n=arguments[e])+'">',"object"==typeof n&&"object"==typeof JSON&&"function"==typeof JSON.stringify?t+=JSON.stringify(n):t+=n,t+="</span>&nbsp;";o.innerHTML+=t+"<br>",console.old.apply(void 0,arguments)}}
    (document.body);
</script>

Replace document.body in the parentheses with whatever element you wish to log into.

How to run Ruby code from terminal?

If Ruby is installed, then

ruby yourfile.rb

where yourfile.rb is the file containing the ruby code.

Or

irb

to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

Displaying a webcam feed using OpenCV and Python

Try the following. It is simple, but I haven't figured out a graceful way to exit yet.

import cv2.cv as cv
import time

cv.NamedWindow("camera", 0)

capture = cv.CaptureFromCAM(0)

while True:
    img = cv.QueryFrame(capture)
    cv.ShowImage("camera", img)
    if cv.WaitKey(10) == 27:
        break
cv.DestroyAllWindows()

What's the best practice to round a float to 2 decimals?

Let's test 3 methods:
1)

public static double round1(double value, int scale) {
    return Math.round(value * Math.pow(10, scale)) / Math.pow(10, scale);
}

2)

public static float round2(float number, int scale) {
    int pow = 10;
    for (int i = 1; i < scale; i++)
        pow *= 10;
    float tmp = number * pow;
    return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}

3)

public static float round3(float d, int decimalPlace) {
    return BigDecimal.valueOf(d).setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).floatValue();
}



Number is 0.23453f
We'll test 100,000 iterations each method.

Results:
Time 1 - 18 ms
Time 2 - 1 ms
Time 3 - 378 ms


Tested on laptop
Intel i3-3310M CPU 2.4GHz

Call an activity method from a fragment

For Kotlin try it out

class DataForm : Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        Tasks(this).getData()
    }

    fun getResponse(response: String) {
        // code
    }
}

class Tasks(private val context: Any) {
    fun getData() {

        val getContext = (context as DataForm).activity
        val getFragment = (context as DataForm)

        val responseListener = Response.Listener<String> { response ->
            getFragment.getResponse(response)
        }

        val errorListener = Response.ErrorListener { error ->
            error.printStackTrace();
        }

        val stringRequest = StringRequest(Request.Method.GET, url, responseListener, errorListener)
        Volley.newRequestQueue(getContext).add(stringRequest)
    }
}

How to change the remote repository for a git submodule?

You should just be able to edit the .gitmodules file to update the URL and then run git submodule sync --recursive to reflect that change to the superproject and your working copy.

Then you need to go to the .git/modules/path_to_submodule dir and change its config file to update git path.

If repo history is different then you need to checkout new branch manually:

git submodule sync --recursive
cd <submodule_dir> 

git fetch
git checkout origin/master
git branch master -f
git checkout master

Installing Java on OS X 10.9 (Mavericks)

This error means Java is not properly installed .

1) brew cask install java (No need to install cask separately it comes with brew)

2) java -version

java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)

P.S - What is brew-cask ? Homebrew-Cask extends Homebrew , and solves the hassle of executing an extra command - “To install, drag this icon…” after installing a Application using Homebrew.

N.B - This problem is not specific to Mavericks , you will get it almost all the OS X, including EL Capitan.

Where can I set environment variables that crontab will use?

Instead of

0  *  *  *  *  sh /my/script.sh

Use bash -l -c

0  *  *  *  *  bash -l -c 'sh /my/script.sh'

Including another class in SCSS

Another option could be using an Attribute Selector:

[class^="your-class-name"]{
  //your style here
}

Whereas every class starting with "your-class-name" uses this style.

So in your case, you could do it like so:

[class^="class"]{
  display: inline-block;
  //some other properties
  &:hover{
   color: darken(#FFFFFF, 10%);
 }  
}

.class-b{
  //specifically for class b
  width: 100px;
  &:hover{
     color: darken(#FFFFFF, 20%);
  }
}

More about Attribute Selectors on w3Schools

Why boolean in Java takes only true or false? Why not 1 or 0 also?

Being specific about this keeps you away from the whole TRUE in VB is -1 and in other langauges true is just NON ZERO. Keeping the boolean field as true or false keeps java outside of this argument.

Extract string between two strings in java

Your pattern is fine. But you shouldn't be split()ting it away, you should find() it. Following code gives the output you are looking for:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

Error:java: javacTask: source release 8 requires target release 1.8

If you are working with Android-studio 1.3, Follow the below steps -

Go to File - Project Structure

Under modules- app-Properties tab, choose Source Compatibility -1.8 and

Target Compatibility - 1.8.

And you are good to go.

How do I convert a long to a string in C++?

Check out std::stringstream.

How to format html table with inline styles to look like a rendered Excel table?

This is quick-and-dirty (and not formally valid HTML5), but it seems to work -- and it is inline as per the question:

<table border='1' style='border-collapse:collapse'>

No further styling of <tr>/<td> tags is required (for a basic table grid).

How can I get the status code from an http error in Axios?

I am using this interceptors to get the error response.

const HttpClient = axios.create({
  baseURL: env.baseUrl,
});

HttpClient.interceptors.response.use((response) => {
  return response;
}, (error) => {
  return Promise.resolve({ error });
});

What are the differences between ArrayList and Vector?

ArrayList is newer and 20-30% faster.

If you don't need something explitly apparent in Vector, use ArrayList

Perform debounce in React.js

Using ES6 CLASS and React 15.x.x & lodash.debounce Im using React's refs here since event losses the this bind internally.

_x000D_
_x000D_
class UserInput extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.state = {_x000D_
      userInput: ""_x000D_
    };_x000D_
    this.updateInput = _.debounce(this.updateInput, 500);_x000D_
  }_x000D_
_x000D_
_x000D_
  updateInput(userInput) {_x000D_
    this.setState({_x000D_
      userInput_x000D_
    });_x000D_
    //OrderActions.updateValue(userInput);//do some server stuff_x000D_
  }_x000D_
_x000D_
_x000D_
  render() {_x000D_
    return ( <div>_x000D_
      <p> User typed: {_x000D_
        this.state.userInput_x000D_
      } </p>_x000D_
      <input ref = "userValue" onChange = {() => this.updateInput(this.refs.userValue.value) } type = "text" / >_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render( <_x000D_
  UserInput / > ,_x000D_
  document.getElementById('root')_x000D_
);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

I ran into this error while trying to click some element (or its overlay, I didn't care), and the other answers didn't work for me. I fixed it by using the elementFromPoint DOM API to find the element that Selenium wanted me to click on instead:

element_i_care_about = something()
loc = element_i_care_about.location
element_to_click = driver.execute_script(
    "return document.elementFromPoint(arguments[0], arguments[1]);",
    loc['x'],
    loc['y'])
element_to_click.click()

I've also had situations where an element was moving, for example because an element above it on the page was doing an animated expand or collapse. In that case, this Expected Condition class helped. You give it the elements that are animated, not the ones you want to click. This version only works for jQuery animations.

class elements_not_to_be_animated(object):
    def __init__(self, locator):
        self.locator = locator

    def __call__(self, driver):
        try:
            elements = EC._find_elements(driver, self.locator)
            # :animated is an artificial jQuery selector for things that are
            # currently animated by jQuery.
            return driver.execute_script(
                'return !jQuery(arguments[0]).filter(":animated").length;',
                elements)
        except StaleElementReferenceException:
            return False

mysqli_select_db() expects parameter 1 to be mysqli, string given

Your arguments are in the wrong order. The connection comes first according to the docs

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>

Can you style an html radio button to look like a checkbox?

Simple and neat with fontawesome

input[type=radio] {
    -moz-appearance: none;
    -webkit-appearance: none;
    -o-appearance: none;
    outline: none;
    content: none;
    margin-left: 5px;
}

input[type=radio]:before {
    font-family: "FontAwesome";
    content: "\f00c";
    font-size: 25px;
    color: transparent !important;
    background: #fff;
    width: 25px;
    height: 25px;
    border: 2px solid black;
    margin-right: 5px;
}

input[type=radio]:checked:before {
    color: black !important;
}

How do I configure git to ignore some files locally?

Both --assume-unchanged and --skip-worktree are NOT A CORRECT WAY to ignore files locally... Kindly check this answer and the notes in the documentation of git update-index. Files that for any reason keep changing frequently (and/or change from a clone to another) and their changes should not be committed, then these files SHOULD NOT be tracked in the first place.

However, the are two proper ways to ignore files locally (both work with untracked files). Either to put files names in .git/info/exclude file which is the local alternative of .gitignore but specific to the current clone. Or to use a global .gitignore (which should be properly used only for common auxiliary files e.g. pyz, pycache, etc) and the file will be ignored in any git repo in your machine.

To make the above as kind of automated (adding to exclude or global .gitignore), you can use the following commands (add to your bash-profile):

  • Per clone local exclude (Note that you should be in the root of the repository when calling the command because of using the relative path), change ##FILE-NAME## to .git/info/exclude
  • Global .gitignore, first make global .gitignore here then change ##FILE-NAME## to ~/.gitignore

Linux

alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
  GITFILETOUNIGNORE=${1//\//\\\/}
  sed -i "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
  unset GITFILETOUNIGNORE
}

MacOS (you need the .bak for sed inplace modifications (i.e. you are forced to add a file extension to inplace sed. i.e. make a backup before replacing something), therefore to delete the .bak file I added rm filename.bak)

alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
  GITFILETOUNIGNORE=${1//\//\\\/}
  sed -i.bak "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
  rm ##FILE-NAME##.bak
  unset GITFILETOUNIGNORE
}

Then you can do:

git-ignore example_file.txt
git-unignore example_file.txt

How to duplicate sys.stdout to a log file?

The print statement will call the write() method of any object you assign to sys.stdout.

I would spin up a small class to write to two places at once...

import sys

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open("log.dat", "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)  

sys.stdout = Logger()

Now the print statement will both echo to the screen and append to your log file:

# prints "1 2" to <stdout> AND log.dat
print "%d %d" % (1,2)

This is obviously quick-and-dirty. Some notes:

  • You probably ought to parametize the log filename.
  • You should probably revert sys.stdout to <stdout> if you won't be logging for the duration of the program.
  • You may want the ability to write to multiple log files at once, or handle different log levels, etc.

These are all straightforward enough that I'm comfortable leaving them as exercises for the reader. The key insight here is that print just calls a "file-like object" that's assigned to sys.stdout.

DataTable, How to conditionally delete rows

You could query the dataset and then loop the selected rows to set them as delete.

var rows = dt.Select("col1 > 5");
foreach (var row in rows)
    row.Delete();

... and you could also create some extension methods to make it easier ...

myTable.Delete("col1 > 5");

public static DataTable Delete(this DataTable table, string filter)
{
    table.Select(filter).Delete();
    return table;
}
public static void Delete(this IEnumerable<DataRow> rows)
{
    foreach (var row in rows)
        row.Delete();
}

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

To even do better boolean mapping to Y/N, add to your hibernate configuration:

<!-- when using type="yes_no" for booleans, the line below allow booleans in HQL expressions: -->
<property name="hibernate.query.substitutions">true 'Y', false 'N'</property>

Now you can use booleans in HQL, for example:

"FROM " + SomeDomainClass.class.getName() + " somedomainclass " +
"WHERE somedomainclass.someboolean = false"

How do I set a ViewModel on a window in XAML using DataContext property?

In addition to the solution that other people provided (which are good, and correct), there is a way to specify the ViewModel in XAML, yet still separate the specific ViewModel from the View. Separating them is useful for when you want to write isolated test cases.

In App.xaml:

<Application
    x:Class="BuildAssistantUI.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:BuildAssistantUI.ViewModels"
    StartupUri="MainWindow.xaml"
    >
    <Application.Resources>
        <local:MainViewModel x:Key="MainViewModel" />
    </Application.Resources>
</Application>

In MainWindow.xaml:

<Window x:Class="BuildAssistantUI.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{StaticResource MainViewModel}"
    />

git is not installed or not in the PATH

Go to Environmental Variables you will find this in Computer Properties->Advance system Setting->Environmental Variables -> Path

Add the path of your git installed int the system. eg: "C:\Program Files\Git\cmd"

Save it. Good to go now!!

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

This Might be Late Answer. but, I hope its save someone time:

If you are using com.google.android.gms:play-services-maps:16.0.0 or below and your app is targeting API level 28 (Android 9.0) or above, you must include the following declaration within the element of AndroidManifest.xml

<application
        ...
        ...
        android:usesCleartextTraffic="true"
        android:requestLegacyExternalStorage="true">

       <uses-library
            android:name="org.apache.http.legacy"
            android:required="false" />

</application>

Note: android:requestLegacyExternalStorage="true" required for Android 10+ to access storage R/W

Android 6.0 introduced the useCleartextTraffic attribute under application element in android manifest. The default value in Android P is “false”. Setting this to true indicates that the app intends to use clear network traffic.

If your app opts out of scoped storage when running on Android 10 devices, it's recommended that you continue to set requestLegacyExternalStorage to true in your app's manifest file. That way, your app can continue to behave as expected on devices that run Android 10

PHP Get Highest Value from Array

Don't sort the array to get the largest value.

Get the max value:

$value = max($array);

Get the corresponding key:

$key = array_search($value, $array);

Make a table fill the entire window

That is because, of course, there is no ACTUAL page height. Keep in mind that you scroll throughout the contents of a page vertically not horizontally, creating a limited width but unlimited height. What the selected answer did was to make the table take up the visible area and stay there no matter what(absolute positioning).So theoretically what you were trying to do was impossible

Custom HTTP headers : naming conventions

Modifying, or more correctly, adding additional HTTP headers is a great code debugging tool if nothing else.

When a URL request returns a redirect or an image there is no html "page" to temporarily write the results of debug code to - at least not one that is visible in a browser.

One approach is to write the data to a local log file and view that file later. Another is to temporarily add HTTP headers reflecting the data and variables being debugged.

I regularly add extra HTTP headers like X-fubar-somevar: or X-testing-someresult: to test things out - and have found a lot of bugs that would have otherwise been very difficult to trace.

javascript set cookie with expire time

Your browser may be configured to accept only session cookies; if this is your case, any expiry time is transformed into session by your browser, you can change this setting of your browser or try another browser without such a configuration

Twitter Bootstrap button click to toggle expand/collapse text section above button

Based on the doc

<div class="row">
    <div class="span4 collapse-group">
        <h2>Heading</h2>
        <p class="collapse">Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
        <p><a class="btn" href="#">View details &raquo;</a></p>
    </div>
</div>
$('.row .btn').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    var $collapse = $this.closest('.collapse-group').find('.collapse');
    $collapse.collapse('toggle');
});

Working demo.

For-loop vs while loop in R

And about timing:

fn1 <- function (N) {
    for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
    i=1
    while (i <= N) {
        y <- i*i
        i <- i + 1
    }
}

system.time(fn1(60000))
# user  system elapsed 
# 0.06    0.00    0.07 
system.time(fn2(60000))
# user  system elapsed 
# 0.12    0.00    0.13

And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.

Calling a phone number in swift

If your phone number contains spaces, remove them first! Then you can use the accepted answer's solution.

let numbersOnly = busPhone.replacingOccurrences(of: " ", with: "")

if let url = URL(string: "tel://\(numbersOnly)"), UIApplication.shared.canOpenURL(url) {
    if #available(iOS 10, *) {
        UIApplication.shared.open(url)
    } else {
        UIApplication.shared.openURL(url)
    }
}

How can I get the height and width of an uiimage?

let heightInPoints = image.size.height
let heightInPixels = heightInPoints * image.scale

let widthInPoints = image.size.width
let widthInPixels = widthInPoints * image.scale

How to retrieve checkboxes values in jQuery

If you want to insert the value of any checkbox immediately as it is being checked then this should work for you:

$(":checkbox").click(function(){
  $("#id").text(this.value)
})

How to set 24-hours format for date on java?

Try below code

    String dateStr = "Jul 27, 2011 8:35:29 PM";
    DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
    DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
    Date date = null;
    try {
       date = readFormat.parse( dateStr );
    } catch ( ParseException e ) {
        e.printStackTrace();
    }

    String formattedDate = "";
    if( date != null ) {
    formattedDate = writeFormat.format( date );
    }

    System.out.println(formattedDate);

Good Luck!!!

Check for various formats.

How to create a Restful web service with input parameters?

You can. Try something like this:

@Path("/todo/{varX}/{varY}")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("varX") String varX,
    @PathParam("varY") String varY) {
        Todo todo = new Todo();
        todo.setSummary(varX);
        todo.setDescription(varY);
        return todo;
}

Then call your service with this URL;
http://localhost:8088/JerseyJAXB/rest/todo/summary/description

How to display multiple images in one figure correctly?

Here is my approach that you may try:

import numpy as np
import matplotlib.pyplot as plt

w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
    img = np.random.randint(10, size=(h,w))
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
plt.show()

The resulting image:

output_image

(Original answer date: Oct 7 '17 at 4:20)

Edit 1

Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-

  1. access to individual axes of subplots
  2. possibility to plot more features on selected axes/subplot

New code:

import numpy as np
import matplotlib.pyplot as plt

w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5

# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# ax enables access to manipulate each of subplots
ax = []

for i in range(columns*rows):
    img = np.random.randint(10, size=(h,w))
    # create subplot and append to ax
    ax.append( fig.add_subplot(rows, columns, i+1) )
    ax[-1].set_title("ax:"+str(i))  # set title
    plt.imshow(img, alpha=0.25)

# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)

plt.show()  # finally, render the plot

The resulting plot:

enter image description here

Edit 2

In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index], which is more suitable for manipulation of array of many sub-plots.

import matplotlib.pyplot as plt
import numpy as np

# settings
h, w = 10, 10        # for raster image
nrows, ncols = 5, 4  # array of sub-plots
figsize = [6, 8]     # figure size, inches

# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)

# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
    # i runs from 0 to (nrows*ncols-1)
    # axi is equivalent with ax[rowid][colid]
    img = np.random.randint(10, size=(h,w))
    axi.imshow(img, alpha=0.25)
    # get indices of row/column
    rowid = i // ncols
    colid = i % ncols
    # write row/col indices as axes' title for identification
    axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))

# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)

plt.tight_layout(True)
plt.show()

The resulting plot:

plot3

APK signing error : Failed to read key from keystore

Check your keystore file for first, in you example you creating file with name my-release-key.keystore. If its correct and really present in folder Users/bournewang/Documents/Project check alias, in your example it is -alias alias_name, but in config you specified alias mike

How can I hide a checkbox in html?

Try setting the checkbox's opacity to 0. If you want the checkbox to be out of flow try position:absolute and offset the checkbox by a large number.

HTML

<label class="checkbox"><input type="checkbox" value="valueofcheckbox" checked="checked" style="opacity:0; position:absolute; left:9999px;">Option Text</label>

Returning a boolean from a Bash function

I encountered a point (not explictly yet mentioned?) which I was stumbling over. That is, not how to return the boolean, but rather how to correctly evaluate it!

I was trying to say if [ myfunc ]; then ..., but that's simply wrong. You must not use the brackets! if myfunc; then ... is the way to do it.

As at @Bruno and others reiterated, true and false are commands, not values! That's very important to understanding booleans in shell scripts.

In this post, I explained and demoed using boolean variables: https://stackoverflow.com/a/55174008/3220983 . I strongly suggest checking that out, because it's so closely related.

Here, I'll provide some examples of returning and evaluating booleans from functions:

This:

test(){ false; }                                               
if test; then echo "it is"; fi                                 

Produces no echo output. (i.e. false returns false)

test(){ true; }                                                
if test; then echo "it is"; fi                                 

Produces:

it is                                                        

(i.e. true returns true)

And

test(){ x=1; }                                                
if test; then echo "it is"; fi                                 

Produces:

it is                                                                           

Because 0 (i.e. true) was returned implicitly.

Now, this is what was screwing me up...

test(){ true; }                                                
if [ test ]; then echo "it is"; fi                             

Produces:

it is                                                                           

AND

test(){ false; }                                                
if [ test ]; then echo "it is"; fi                             

ALSO produces:

it is                                                                           

Using the brackets here produced a false positive! (I infer the "outer" command result is 0.)

The major take away from my post is: don't use brackets to evaluate a boolean function (or variable) like you would for a typical equality check e.g. if [ x -eq 1 ]; then... !

Multidimensional Array [][] vs [,]

double[][] is an array of arrays and double[,] is a matrix. If you want to initialize an array of array, you will need to do this:

double[][] ServicePoint = new double[10][]
for(var i=0;i<ServicePoint.Length;i++)
    ServicePoint[i] = new double[9];

Take in account that using arrays of arrays will let you have arrays of different lengths:

ServicePoint[0] = new double[10];
ServicePoint[1] = new double[3];
ServicePoint[2] = new double[5];
//and so on...

How to pass variable as a parameter in Execute SQL Task SSIS?

A little late to the party, but this is how I did it for an insert:

DECLARE @ManagerID AS Varchar (25) = 'NA'
DECLARE @ManagerEmail AS Varchar (50) = 'NA'
Declare @RecordCount AS int = 0

SET @ManagerID = ?
SET @ManagerEmail = ?
SET @RecordCount = ?

INSERT INTO...

Should each and every table have a primary key?

Except for a few very rare cases (possibly a many-to-many relationship table, or a table you temporarily use for bulk-loading huge amounts of data), I would go with the saying:

If it doesn't have a primary key, it's not a table!

Marc

AngularJS - Find Element with attribute

Your use-case isn't clear. However, if you are certain that you need this to be based on the DOM, and not model-data, then this is a way for one directive to have a reference to all elements with another directive specified on them.

The way is that the child directive can require the parent directive. The parent directive can expose a method that allows direct directive to register their element with the parent directive. Through this, the parent directive can access the child element(s). So if you have a template like:

<div parent-directive>
  <div child-directive></div>
  <div child-directive></div>
</div>

Then the directives can be coded like:

app.directive('parentDirective', function($window) {
  return {
    controller: function($scope) {
      var registeredElements = [];
      this.registerElement = function(childElement) {
        registeredElements.push(childElement);
      }
    }
  };
});

app.directive('childDirective', function() {
  return {
    require: '^parentDirective',
    template: '<span>Child directive</span>',
    link: function link(scope, iElement, iAttrs, parentController) {
      parentController.registerElement(iElement);
    }
   };
});

You can see this in action at http://plnkr.co/edit/7zUgNp2MV3wMyAUYxlkz?p=preview

Current date without time

This should work:

string datetime = DateTime.Today.ToString();

logout and redirecting session in php

<?php
session_start();
session_destroy();
header("Location: home.php");
?>

VBScript How can I Format Date?

This snippet also solve this question with datePart function. I've also used the right() trick to perform a rpad(x,2,"0").

option explicit

Wscript.Echo "Today is " & myDate(now)

' date formatted as your request
Function myDate(dt)
    dim d,m,y, sep
    sep = "-"
    ' right(..) here works as rpad(x,2,"0")
    d = right("0" & datePart("d",dt),2)
    m = right("0" & datePart("m",dt),2)
    y = datePart("yyyy",dt)
    myDate= m & sep & d & sep & y
End Function

Escape text for HTML

You can use actual html tags <xmp> and </xmp> to output the string as is to show all of the tags in between the xmp tags.

Or you can also use on the server Server.UrlEncode or HttpUtility.HtmlEncode.

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

C# 30 Days From Todays Date

DateTime.Now.Add(-30)

Gives you the date 30 days back from now

How to add text inside the doughnut chart using Chart.js?

Alesana's solution works very nicely for me in general, but like others, I wanted to be able to specify where line breaks occur. I made some simple modifications to wrap lines at '\n' characters, as long as the text is already being wrapped. A more complete solution would force wrapping if there are any '\n' characters in the text, but I don't have time at the moment to make that work with font sizing. The change also centers a little better horizontally when wrapping (avoids trailing spaces). The code's below (I can't post comments yet).

It would be cool if someone put this plug-in on GitHub...

Chart.pluginService.register({
  beforeDraw: function(chart) {
    if (chart.config.options.elements.center) {
      // Get ctx from string
      var ctx = chart.chart.ctx;

      // Get options from the center object in options
      var centerConfig = chart.config.options.elements.center;
      var fontStyle = centerConfig.fontStyle || 'Arial';
      var txt = centerConfig.text;
      var color = centerConfig.color || '#000';
      var maxFontSize = centerConfig.maxFontSize || 75;
      var sidePadding = centerConfig.sidePadding || 20;
      var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
      // Start with a base font of 30px
      ctx.font = "30px " + fontStyle;

      // Get the width of the string and also the width of the element minus 10 to give it 5px side padding
      var stringWidth = ctx.measureText(txt).width;
      var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;

      // Find out how much the font can grow in width.
      var widthRatio = elementWidth / stringWidth;
      var newFontSize = Math.floor(30 * widthRatio);
      var elementHeight = (chart.innerRadius * 2);

      // Pick a new font size so it will not be larger than the height of label.
      var fontSizeToUse = Math.min(newFontSize, elementHeight, maxFontSize);
      var minFontSize = centerConfig.minFontSize;
      var lineHeight = centerConfig.lineHeight || 25;
      var wrapText = false;

      if (minFontSize === undefined) {
        minFontSize = 20;
      }

      if (minFontSize && fontSizeToUse < minFontSize) {
        fontSizeToUse = minFontSize;
        wrapText = true;
      }

      // Set font settings to draw it correctly.
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
      var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
      ctx.font = fontSizeToUse + "px " + fontStyle;
      ctx.fillStyle = color;

      if (!wrapText) {
        ctx.fillText(txt, centerX, centerY);
        return;
      }

      var lines = [];
      var chunks = txt.split('\n');
      for (var m = 0; m < chunks.length; m++) {
        var words = chunks[m].split(' ');
        var line;

        // Break words up into multiple lines if necessary
        for (var n = 0; n < words.length; n++) {
          var testLine = (n == 0) ? words[n] : line + ' ' + words[n];
          var metrics = ctx.measureText(testLine);
          var testWidth = metrics.width;
          if (testWidth > elementWidth && n > 0) {
            lines.push(line);
            line = words[n];
          } else {
            line = testLine;
          }
        }
        lines.push(line);
      }

      // Move the center up depending on line height and number of lines
      centerY -= ((lines.length-1) / 2) * lineHeight;

      // All but last line
      for (var n = 0; n < lines.length; n++) {
        ctx.fillText(lines[n], centerX, centerY);
        centerY += lineHeight;
      }
    }
  }
});

POSTing JSON to URL via WebClient in C#

The following example demonstrates how to POST a JSON via WebClient.UploadString Method:

var vm = new { k = "1", a = "2", c = "3", v=  "4" };
using (var client = new WebClient())
{
   var dataString = JsonConvert.SerializeObject(vm);
   client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
   client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}

Prerequisites: Json.NET library

MySQL 'Order By' - sorting alphanumeric correctly

I had some good results with

SELECT alphanumeric, integer FROM sorting_test ORDER BY CAST(alphanumeric AS UNSIGNED), alphanumeric ASC

Sorted collection in Java

Using LambdaJ

You can try solving these tasks with LambdaJ if you are using prior versions to java 8. You can find it here: http://code.google.com/p/lambdaj/

Here you have an example:

Sort Iterative

List<Person> sortedByAgePersons = new ArrayList<Person>(persons);
Collections.sort(sortedByAgePersons, new Comparator<Person>() {
        public int compare(Person p1, Person p2) {
           return Integer.valueOf(p1.getAge()).compareTo(p2.getAge());
        }
}); 

Sort with LambdaJ

List<Person> sortedByAgePersons = sort(persons, on(Person.class).getAge()); 

Of course, having this kind of beauty impacts in the performance (an average of 2 times), but can you find a more readable code?

Sort with java 8 using lambda expression

Collections.sort(persons, (p1, p2) -> p1.getAge().compareTo(p2.getAge()));
//or
persons.sort((p1, p2) -> p1.getAge().compareTo(p2.getAge()));

PostgreSQL Crosstab Query

You can use the crosstab() function of the additional module tablefunc - which you have to install once per database. Since PostgreSQL 9.1 you can use CREATE EXTENSION for that:

CREATE EXTENSION tablefunc;

In your case, I believe it would look something like this:

CREATE TABLE t (Section CHAR(1), Status VARCHAR(10), Count integer);

INSERT INTO t VALUES ('A', 'Active',   1);
INSERT INTO t VALUES ('A', 'Inactive', 2);
INSERT INTO t VALUES ('B', 'Active',   4);
INSERT INTO t VALUES ('B', 'Inactive', 5);

SELECT row_name AS Section,
       category_1::integer AS Active,
       category_2::integer AS Inactive
FROM crosstab('select section::text, status, count::text from t',2)
            AS ct (row_name text, category_1 text, category_2 text);

Check if a file is executable

First you need to remember that in Unix and Linux, everything is a file, even directories. For a file to have the rights to be executed as a command, it needs to satisfy 3 conditions:

  1. It needs to be a regular file
  2. It needs to have read-permissions
  3. It needs to have execute-permissions

So this can be done simply with:

[ -f "${file}" ] && [ -r "${file}" ] && [ -x "${file}" ]

If your file is a symbolic link to a regular file, the test command will operate on the target and not the link-name. So the above command distinguishes if a file can be used as a command or not. So there is no need to pass the file first to realpath or readlink or any of those variants.

If the file can be executed on the current OS, that is a different question. Some answers above already pointed to some possibilities for that, so there is no need to repeat it here.

What's the difference between %s and %d in Python string formatting?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

name = 'marcog'
number = 42
print '%s %d' % (name, number)

will print marcog 42. Note that name is a string (%s) and number is an integer (%d for decimal).

See https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting for details.

In Python 3 the example would be:

print('%s %d' % (name, number))

Class has no objects member

By doing Question = new Question() (I assume the new is a typo) you are overwriting the Question model with an intance of Question. Like Sayse said in the comments: don't use the same name for your variable as the name of the model. So change it to something like my_question = Question().

How do I remove a single file from the staging area (undo git add)?

I think you probably got confused with the concept of index, as @CB Bailey commented:

The staging area is the index.

You can simply consider staging directory and index as the same thing.
So, just like @Tim Henigan's answer, I guess:

you simply want to "undo" the git add that was done for that file.



Here is my answer:

Commonly, there are two ways to undo a stage operation, as other answers already mentioned:

git reset HEAD <file>

and

git rm --cached <file>

But what is the difference?

Assume the file has been staged and exists in working directory too, use git rm --cached <file> if you want to remove it from staging directory, and keep the file in working directory. But notice that this operation will not only remove the file from staging directory but also mark the file as deleted in staging directory, if you use

git status

after this operation, you will see this :

        deleted:    <file>

It's a record of removing the file from staging directory. If you don't want to keep that record and just simply want to undo a previous stage operation of a file, use git reset HEAD <file> instead.


-------- END OF ANSWER --------

PS: I have noticed some answers mentioned:

git checkout -- <file>

This command is for the situation when the file has been staged, but the file has been modified in working directory after it was staged, use this operation to restore the file in working directory from staging directory. In other words, after this operation, changes happen in your working directory, NOT your staging directory.

A valid provisioning profile for this executable was not found... (again)

In my case it was just after a new Program Licence Agreement was released so we had to accept them and it was fine.

CSS/HTML: What is the correct way to make text italic?

TLDR

The correct way to make text italic is to ignore the problem until you get to the CSS, then style according to presentational semantics. The first two options you provided could be right depending on the circumstances. The last two are wrong.

Longer Explanation

Don't worry about presentation when writing the markup. Don't think in terms of italics. Think in terms of semantics. If it requires stress emphasis, then it's an em. If it's tangential to the main content, then it's an aside. Maybe it'll be bold, maybe it'll be italic, maybe it'll be fluorescent green. It doesn't matter when you're writing markup.

When you do get to the CSS, you might already have a semantic element that makes sense to put italics for all its occurrences in your site. em is a good example. But maybe you want all aside > ul > li on your site in italics. You have to separate thinking about the markup from thinking about the presentation.

As mentioned by DisgruntledGoat, i is semantic in HTML5. The semantics seem kind of narrow to me, though. Use will probably be rare.

The semantics of em have changed in HTML5 to stress emphasis. strong can be used to show importance as well. strong can be italic rather than bold if that's how you want to style it. Don't let the browser's stylesheet limit you. You can even use a reset stylesheet to help you stop thinking within the defaults. (Though there are some caveats.)

class="italic" is bad. Don't use it. It is not semantic and is not flexible at all. Presentation still has semantics, just a different kind from markup.

class="footnote" is emulating markup semantics and is incorrect as well. Your CSS for the footnote should not be completely unique to your footnote. Your site will look too messy if every part is styled differently. You should have some visual patterns scattered through your pages that you can turn into CSS classes. If your style for your footnotes and your blockquotes are very similar, then you should put the similarities into one class rather than repeat yourself over and over again. You might consider adopting the practices of OOCSS (links below).

Separation of concerns and semantics are big in HTML5. People often don't realize that the markup isn't the only place where semantics is important. There is content semantics (HTML), but there is also presentational semantics (CSS) and behavioral semantics (JavaScript) as well. They all have their own separate semantics that are important to pay attention to for maintainability and staying DRY.

OOCSS Resources

What is the Java equivalent for LINQ?

you can use scala, it is similar in syntax and it's actually probably more powerful than linq.

How do I iterate through children elements of a div using jQuery?

It is also possible to iterate through all elements within a specific context, no mattter how deeply nested they are:

$('input', $('#mydiv')).each(function () {
    console.log($(this)); //log every element found to console output
});

The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.

Why ModelState.IsValid always return false in mvc

Please post your Model Class.

To check the errors in your ModelState use the following code:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

OR: You can also use

var errors = ModelState.Values.SelectMany(v => v.Errors);

Place a break point at the above line and see what are the errors in your ModelState.

What's a quick way to comment/uncomment lines in Vim?

I use vim-multiple-cursors for this.

  1. To select the region, go to the first character of the first or last line of the region to be commented out by pressing 0 (it's zero, not letter "o"). Then press V and select the region using J, K or up and down arrow keys.
  2. Then put a virtual cursor on each line of the selection by pressing CtrlN.
  3. Then press I to simultaneously edit each line of the selection.

Disable scrolling when touch moving certain element

There is a little "hack" on CSS that also allows you to disable scrolling:

.lock-screen {
    height: 100%;
    overflow: hidden;
    width: 100%;
    position: fixed;
}

Adding that class to the body will prevent scrolling.

How to add 20 minutes to a current date?

Just get the millisecond timestamp and add 20 minutes to it:

twentyMinutesLater = new Date(currentDate.getTime() + (20*60*1000))

Combine two columns and add into one new column

You don't need to store the column to reference it that way. Try this:

To set up:

CREATE TABLE tbl
  (zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');

We can see we have "the right stuff":

\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+
| zipcode |  city  | state |
+---------+--------+-------+
| 10954   | Nanuet | NY    |
+---------+--------+-------+

Now add a function with the desired "column name" which takes the record type of the table as its only parameter:

CREATE FUNCTION combined(rec tbl)
  RETURNS text
  LANGUAGE SQL
AS $$
  SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;

This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:

SELECT *, tbl.combined FROM tbl;

Which displays like this:

+---------+--------+-------+--------------------+
| zipcode |  city  | state |      combined      |
+---------+--------+-------+--------------------+
| 10954   | Nanuet | NY    | 10954 - Nanuet, NY |
+---------+--------+-------+--------------------+

This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.

Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.

Jupyter/IPython Notebooks: Shortcut for "run all"?

Jupyter Lab 1.0.4:

  1. In the top menu, go to: Settings->Advanced Settings Editor->Keyboard Shortcuts

  2. Paste this code in the User Preferences window:

{
    "shortcuts": [
        {
            "command": "runmenu:run-all",
            "keys": [
                "R",
                "R"
            ],
            "selector": "[data-jp-kernel-user]:focus"
        }
    ]
}
  1. Save (top right of the user-preferences window)

This will be effective immediately. Here, two consecutive 'R' presses runs all cells (just like two '0' for kernel restart). Notably, system defaults has empty templates for all menu commands, including this code (search for run-all). The selector was copied from kernelmenu:restart, to allow printing r within cells. This system defaults copy-paste can be generalized to any command.

Calling a Function defined inside another function in Javascript

If you want to call the "inner" function with the "outer" function, you can do this:

function outer() { 
     function inner() {
          alert("hi");
     }
     return { inner };
}

And on "onclick" event you call the function like this:

<input type="button" onclick="outer().inner();" value="ACTION">?

Best Regular Expression for Email Validation in C#

Email Validation Regex

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+.)+[a-z]{2,5}$

Or

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+[.])+[a-z]{2,5}$

Demo Link:

https://regex101.com/r/kN4nJ0/53

Download multiple files with a single action

Angular solution:

HTML

    <!doctype html>
    <html ng-app='app'>
        <head>
            <title>
            </title>
            <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
            <link rel="stylesheet" href="style.css">
        </head>
        <body ng-cloack>        
            <div class="container" ng-controller='FirstCtrl'>           
              <table class="table table-bordered table-downloads">
                <thead>
                  <tr>
                    <th>Select</th>
                    <th>File name</th>
                    <th>Downloads</th>
                  </tr>
                </thead>
                <tbody>
                  <tr ng-repeat = 'tableData in tableDatas'>
                    <td>
                        <div class="checkbox">
                          <input type="checkbox" name="{{tableData.name}}" id="{{tableData.name}}" value="{{tableData.name}}" ng-model= 'tableData.checked' ng-change="selected()">
                        </div>
                    </td>
                    <td>{{tableData.fileName}}</td>
                    <td>
                        <a target="_self" id="download-{{tableData.name}}" ng-href="{{tableData.filePath}}" class="btn btn-success pull-right downloadable" download>download</a>
                    </td>
                  </tr>              
                </tbody>
              </table>
                <a class="btn btn-success pull-right" ng-click='downloadAll()'>download selected</a>

                <p>{{selectedone}}</p>
            </div>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
            <script src="script.js"></script>
        </body>
    </html>

app.js

var app = angular.module('app', []);            
app.controller('FirstCtrl', ['$scope','$http', '$filter', function($scope, $http, $filter){

$scope.tableDatas = [
    {name: 'value1', fileName:'file1', filePath: 'data/file1.txt', selected: true},
    {name: 'value2', fileName:'file2', filePath: 'data/file2.txt', selected: true},
    {name: 'value3', fileName:'file3', filePath: 'data/file3.txt', selected: false},
    {name: 'value4', fileName:'file4', filePath: 'data/file4.txt', selected: true},
    {name: 'value5', fileName:'file5', filePath: 'data/file5.txt', selected: true},
    {name: 'value6', fileName:'file6', filePath: 'data/file6.txt', selected: false},
  ];  
$scope.application = [];   

$scope.selected = function() {
    $scope.application = $filter('filter')($scope.tableDatas, {
      checked: true
    });
}

$scope.downloadAll = function(){
    $scope.selectedone = [];     
    angular.forEach($scope.application,function(val){
       $scope.selectedone.push(val.name);
       $scope.id = val.name;        
       angular.element('#'+val.name).closest('tr').find('.downloadable')[0].click();
    });
}         


}]);

working example: https://plnkr.co/edit/XynXRS7c742JPfCA3IpE?p=preview

Hash String via SHA-256 in Java

You don't necessarily need the BouncyCastle library. The following code shows how to do so using the Integer.toHexString function

public static String sha256(String base) {
    try{
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(base.getBytes("UTF-8"));
        StringBuffer hexString = new StringBuffer();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
    } catch(Exception ex){
       throw new RuntimeException(ex);
    }
}

Special thanks to user1452273 from this post: How to hash some string with sha256 in Java?

Keep up the good work !

Remove part of a string

If you're a Tidyverse kind of person, here's the stringr solution:

R> library(stringr)
R> strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121") 
R> strings %>% str_replace(".*_", "_")
[1] "_1121" "_1432" "_1121"
# Or:
R> strings %>% str_replace("^[A-Z]*", "")
[1] "_1121" "_1432" "_1121"

Check whether a path is valid in Python without creating a file at the path's target

tl;dr

Call the is_path_exists_or_creatable() function defined below.

Strictly Python 3. That's just how we roll.

A Tale of Two Questions

The question of "How do I test pathname validity and, for valid pathnames, the existence or writability of those paths?" is clearly two separate questions. Both are interesting, and neither have received a genuinely satisfactory answer here... or, well, anywhere that I could grep.

vikki's answer probably hews the closest, but has the remarkable disadvantages of:

  • Needlessly opening (...and then failing to reliably close) file handles.
  • Needlessly writing (...and then failing to reliable close or delete) 0-byte files.
  • Ignoring OS-specific errors differentiating between non-ignorable invalid pathnames and ignorable filesystem issues. Unsurprisingly, this is critical under Windows. (See below.)
  • Ignoring race conditions resulting from external processes concurrently (re)moving parent directories of the pathname to be tested. (See below.)
  • Ignoring connection timeouts resulting from this pathname residing on stale, slow, or otherwise temporarily inaccessible filesystems. This could expose public-facing services to potential DoS-driven attacks. (See below.)

We're gonna fix all that.

Question #0: What's Pathname Validity Again?

Before hurling our fragile meat suits into the python-riddled moshpits of pain, we should probably define what we mean by "pathname validity." What defines validity, exactly?

By "pathname validity," we mean the syntactic correctness of a pathname with respect to the root filesystem of the current system – regardless of whether that path or parent directories thereof physically exist. A pathname is syntactically correct under this definition if it complies with all syntactic requirements of the root filesystem.

By "root filesystem," we mean:

  • On POSIX-compatible systems, the filesystem mounted to the root directory (/).
  • On Windows, the filesystem mounted to %HOMEDRIVE%, the colon-suffixed drive letter containing the current Windows installation (typically but not necessarily C:).

The meaning of "syntactic correctness," in turn, depends on the type of root filesystem. For ext4 (and most but not all POSIX-compatible) filesystems, a pathname is syntactically correct if and only if that pathname:

  • Contains no null bytes (i.e., \x00 in Python). This is a hard requirement for all POSIX-compatible filesystems.
  • Contains no path components longer than 255 bytes (e.g., 'a'*256 in Python). A path component is a longest substring of a pathname containing no / character (e.g., bergtatt, ind, i, and fjeldkamrene in the pathname /bergtatt/ind/i/fjeldkamrene).

Syntactic correctness. Root filesystem. That's it.

Question #1: How Now Shall We Do Pathname Validity?

Validating pathnames in Python is surprisingly non-intuitive. I'm in firm agreement with Fake Name here: the official os.path package should provide an out-of-the-box solution for this. For unknown (and probably uncompelling) reasons, it doesn't. Fortunately, unrolling your own ad-hoc solution isn't that gut-wrenching...

O.K., it actually is. It's hairy; it's nasty; it probably chortles as it burbles and giggles as it glows. But what you gonna do? Nuthin'.

We'll soon descend into the radioactive abyss of low-level code. But first, let's talk high-level shop. The standard os.stat() and os.lstat() functions raise the following exceptions when passed invalid pathnames:

  • For pathnames residing in non-existing directories, instances of FileNotFoundError.
  • For pathnames residing in existing directories:
    • Under Windows, instances of WindowsError whose winerror attribute is 123 (i.e., ERROR_INVALID_NAME).
    • Under all other OSes:
    • For pathnames containing null bytes (i.e., '\x00'), instances of TypeError.
    • For pathnames containing path components longer than 255 bytes, instances of OSError whose errcode attribute is:
      • Under SunOS and the *BSD family of OSes, errno.ERANGE. (This appears to be an OS-level bug, otherwise referred to as "selective interpretation" of the POSIX standard.)
      • Under all other OSes, errno.ENAMETOOLONG.

Crucially, this implies that only pathnames residing in existing directories are validatable. The os.stat() and os.lstat() functions raise generic FileNotFoundError exceptions when passed pathnames residing in non-existing directories, regardless of whether those pathnames are invalid or not. Directory existence takes precedence over pathname invalidity.

Does this mean that pathnames residing in non-existing directories are not validatable? Yes – unless we modify those pathnames to reside in existing directories. Is that even safely feasible, however? Shouldn't modifying a pathname prevent us from validating the original pathname?

To answer this question, recall from above that syntactically correct pathnames on the ext4 filesystem contain no path components (A) containing null bytes or (B) over 255 bytes in length. Hence, an ext4 pathname is valid if and only if all path components in that pathname are valid. This is true of most real-world filesystems of interest.

Does that pedantic insight actually help us? Yes. It reduces the larger problem of validating the full pathname in one fell swoop to the smaller problem of only validating all path components in that pathname. Any arbitrary pathname is validatable (regardless of whether that pathname resides in an existing directory or not) in a cross-platform manner by following the following algorithm:

  1. Split that pathname into path components (e.g., the pathname /troldskog/faren/vild into the list ['', 'troldskog', 'faren', 'vild']).
  2. For each such component:
    1. Join the pathname of a directory guaranteed to exist with that component into a new temporary pathname (e.g., /troldskog) .
    2. Pass that pathname to os.stat() or os.lstat(). If that pathname and hence that component is invalid, this call is guaranteed to raise an exception exposing the type of invalidity rather than a generic FileNotFoundError exception. Why? Because that pathname resides in an existing directory. (Circular logic is circular.)

Is there a directory guaranteed to exist? Yes, but typically only one: the topmost directory of the root filesystem (as defined above).

Passing pathnames residing in any other directory (and hence not guaranteed to exist) to os.stat() or os.lstat() invites race conditions, even if that directory was previously tested to exist. Why? Because external processes cannot be prevented from concurrently removing that directory after that test has been performed but before that pathname is passed to os.stat() or os.lstat(). Unleash the dogs of mind-fellating insanity!

There exists a substantial side benefit to the above approach as well: security. (Isn't that nice?) Specifically:

Front-facing applications validating arbitrary pathnames from untrusted sources by simply passing such pathnames to os.stat() or os.lstat() are susceptible to Denial of Service (DoS) attacks and other black-hat shenanigans. Malicious users may attempt to repeatedly validate pathnames residing on filesystems known to be stale or otherwise slow (e.g., NFS Samba shares); in that case, blindly statting incoming pathnames is liable to either eventually fail with connection timeouts or consume more time and resources than your feeble capacity to withstand unemployment.

The above approach obviates this by only validating the path components of a pathname against the root directory of the root filesystem. (If even that's stale, slow, or inaccessible, you've got larger problems than pathname validation.)

Lost? Great. Let's begin. (Python 3 assumed. See "What Is Fragile Hope for 300, leycec?")

import errno, os

# Sadly, Python fails to provide the following magic number for us.
ERROR_INVALID_NAME = 123
'''
Windows-specific error code indicating an invalid pathname.

See Also
----------
https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
    Official listing of all such codes.
'''

def is_pathname_valid(pathname: str) -> bool:
    '''
    `True` if the passed pathname is a valid pathname for the current OS;
    `False` otherwise.
    '''
    # If this pathname is either not a string or is but is empty, this pathname
    # is invalid.
    try:
        if not isinstance(pathname, str) or not pathname:
            return False

        # Strip this pathname's Windows-specific drive specifier (e.g., `C:\`)
        # if any. Since Windows prohibits path components from containing `:`
        # characters, failing to strip this `:`-suffixed prefix would
        # erroneously invalidate all valid absolute Windows pathnames.
        _, pathname = os.path.splitdrive(pathname)

        # Directory guaranteed to exist. If the current OS is Windows, this is
        # the drive to which Windows was installed (e.g., the "%HOMEDRIVE%"
        # environment variable); else, the typical root directory.
        root_dirname = os.environ.get('HOMEDRIVE', 'C:') \
            if sys.platform == 'win32' else os.path.sep
        assert os.path.isdir(root_dirname)   # ...Murphy and her ironclad Law

        # Append a path separator to this directory if needed.
        root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep

        # Test whether each path component split from this pathname is valid or
        # not, ignoring non-existent and non-readable path components.
        for pathname_part in pathname.split(os.path.sep):
            try:
                os.lstat(root_dirname + pathname_part)
            # If an OS-specific exception is raised, its error code
            # indicates whether this pathname is valid or not. Unless this
            # is the case, this exception implies an ignorable kernel or
            # filesystem complaint (e.g., path not found or inaccessible).
            #
            # Only the following exceptions indicate invalid pathnames:
            #
            # * Instances of the Windows-specific "WindowsError" class
            #   defining the "winerror" attribute whose value is
            #   "ERROR_INVALID_NAME". Under Windows, "winerror" is more
            #   fine-grained and hence useful than the generic "errno"
            #   attribute. When a too-long pathname is passed, for example,
            #   "errno" is "ENOENT" (i.e., no such file or directory) rather
            #   than "ENAMETOOLONG" (i.e., file name too long).
            # * Instances of the cross-platform "OSError" class defining the
            #   generic "errno" attribute whose value is either:
            #   * Under most POSIX-compatible OSes, "ENAMETOOLONG".
            #   * Under some edge-case OSes (e.g., SunOS, *BSD), "ERANGE".
            except OSError as exc:
                if hasattr(exc, 'winerror'):
                    if exc.winerror == ERROR_INVALID_NAME:
                        return False
                elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}:
                    return False
    # If a "TypeError" exception was raised, it almost certainly has the
    # error message "embedded NUL character" indicating an invalid pathname.
    except TypeError as exc:
        return False
    # If no exception was raised, all path components and hence this
    # pathname itself are valid. (Praise be to the curmudgeonly python.)
    else:
        return True
    # If any other exception was raised, this is an unrelated fatal issue
    # (e.g., a bug). Permit this exception to unwind the call stack.
    #
    # Did we mention this should be shipped with Python already?

Done. Don't squint at that code. (It bites.)

Question #2: Possibly Invalid Pathname Existence or Creatability, Eh?

Testing the existence or creatability of possibly invalid pathnames is, given the above solution, mostly trivial. The little key here is to call the previously defined function before testing the passed path:

def is_path_creatable(pathname: str) -> bool:
    '''
    `True` if the current user has sufficient permissions to create the passed
    pathname; `False` otherwise.
    '''
    # Parent directory of the passed path. If empty, we substitute the current
    # working directory (CWD) instead.
    dirname = os.path.dirname(pathname) or os.getcwd()
    return os.access(dirname, os.W_OK)

def is_path_exists_or_creatable(pathname: str) -> bool:
    '''
    `True` if the passed pathname is a valid pathname for the current OS _and_
    either currently exists or is hypothetically creatable; `False` otherwise.

    This function is guaranteed to _never_ raise exceptions.
    '''
    try:
        # To prevent "os" module calls from raising undesirable exceptions on
        # invalid pathnames, is_pathname_valid() is explicitly called first.
        return is_pathname_valid(pathname) and (
            os.path.exists(pathname) or is_path_creatable(pathname))
    # Report failure on non-fatal filesystem complaints (e.g., connection
    # timeouts, permissions issues) implying this path to be inaccessible. All
    # other exceptions are unrelated fatal issues and should not be caught here.
    except OSError:
        return False

Done and done. Except not quite.

Question #3: Possibly Invalid Pathname Existence or Writability on Windows

There exists a caveat. Of course there does.

As the official os.access() documentation admits:

Note: I/O operations may fail even when os.access() indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model.

To no one's surprise, Windows is the usual suspect here. Thanks to extensive use of Access Control Lists (ACL) on NTFS filesystems, the simplistic POSIX permission-bit model maps poorly to the underlying Windows reality. While this (arguably) isn't Python's fault, it might nonetheless be of concern for Windows-compatible applications.

If this is you, a more robust alternative is wanted. If the passed path does not exist, we instead attempt to create a temporary file guaranteed to be immediately deleted in the parent directory of that path – a more portable (if expensive) test of creatability:

import os, tempfile

def is_path_sibling_creatable(pathname: str) -> bool:
    '''
    `True` if the current user has sufficient permissions to create **siblings**
    (i.e., arbitrary files in the parent directory) of the passed pathname;
    `False` otherwise.
    '''
    # Parent directory of the passed path. If empty, we substitute the current
    # working directory (CWD) instead.
    dirname = os.path.dirname(pathname) or os.getcwd()

    try:
        # For safety, explicitly close and hence delete this temporary file
        # immediately after creating it in the passed path's parent directory.
        with tempfile.TemporaryFile(dir=dirname): pass
        return True
    # While the exact type of exception raised by the above function depends on
    # the current version of the Python interpreter, all such types subclass the
    # following exception superclass.
    except EnvironmentError:
        return False

def is_path_exists_or_creatable_portable(pathname: str) -> bool:
    '''
    `True` if the passed pathname is a valid pathname on the current OS _and_
    either currently exists or is hypothetically creatable in a cross-platform
    manner optimized for POSIX-unfriendly filesystems; `False` otherwise.

    This function is guaranteed to _never_ raise exceptions.
    '''
    try:
        # To prevent "os" module calls from raising undesirable exceptions on
        # invalid pathnames, is_pathname_valid() is explicitly called first.
        return is_pathname_valid(pathname) and (
            os.path.exists(pathname) or is_path_sibling_creatable(pathname))
    # Report failure on non-fatal filesystem complaints (e.g., connection
    # timeouts, permissions issues) implying this path to be inaccessible. All
    # other exceptions are unrelated fatal issues and should not be caught here.
    except OSError:
        return False

Note, however, that even this may not be enough.

Thanks to User Access Control (UAC), the ever-inimicable Windows Vista and all subsequent iterations thereof blatantly lie about permissions pertaining to system directories. When non-Administrator users attempt to create files in either the canonical C:\Windows or C:\Windows\system32 directories, UAC superficially permits the user to do so while actually isolating all created files into a "Virtual Store" in that user's profile. (Who could have possibly imagined that deceiving users would have harmful long-term consequences?)

This is crazy. This is Windows.

Prove It

Dare we? It's time to test-drive the above tests.

Since NULL is the only character prohibited in pathnames on UNIX-oriented filesystems, let's leverage that to demonstrate the cold, hard truth – ignoring non-ignorable Windows shenanigans, which frankly bore and anger me in equal measure:

>>> print('"foo.bar" valid? ' + str(is_pathname_valid('foo.bar')))
"foo.bar" valid? True
>>> print('Null byte valid? ' + str(is_pathname_valid('\x00')))
Null byte valid? False
>>> print('Long path valid? ' + str(is_pathname_valid('a' * 256)))
Long path valid? False
>>> print('"/dev" exists or creatable? ' + str(is_path_exists_or_creatable('/dev')))
"/dev" exists or creatable? True
>>> print('"/dev/foo.bar" exists or creatable? ' + str(is_path_exists_or_creatable('/dev/foo.bar')))
"/dev/foo.bar" exists or creatable? False
>>> print('Null byte exists or creatable? ' + str(is_path_exists_or_creatable('\x00')))
Null byte exists or creatable? False

Beyond sanity. Beyond pain. You will find Python portability concerns.

Any easy way to use icons from resources?

  1. Add the icon to the project resources and rename to icon.

  2. Open the designer of the form you want to add the icon to.

  3. Append the InitializeComponent function.

  4. Add this line in the top:

    this.Icon = PROJECTNAME.Properties.Resources.icon;
    

    repeat step 4 for any forms in your project you want to update

GET parameters in the URL with CodeIgniter

GET parameters are cached by the web browser, POST is not. So with a POST you don't have to worry about caching, so that is why it is usually prefered.

How to Disable GUI Button in Java

Rather than using booleans, why not just set the button to false when its clicked, so you do that in your actionPerformed method. Its more efficient..

if (command.equals("w"))
{
    FileConverter fc = new FileConverter();
    btnConvertDocuments.setEnabled(false);
}

How to update Xcode from command line

I had the same issue and I solved by doing the following:

  1. removing the old tools ($ sudo rm -rf /Library/Developer/CommandLineTools)
  2. install xcode command line tools again ($ xcode-select --install).

After these steps you will see a pop to install the new version of the tools.

How do you convert epoch time in C#?

With all credit to LukeH, I've put together some extension methods for easy use:

public static DateTime FromUnixTime(this long unixTime)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return epoch.AddSeconds(unixTime);
}

public static long ToUnixTime(this DateTime date)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return Convert.ToInt64((date - epoch).TotalSeconds);
}

Note the comment below from CodesInChaos that the above FromUnixTime returns a DateTime with a Kind of Utc, which is fine, but the above ToUnixTime is much more suspect in that doesn't account for what kind of DateTime the given date is. To allow for date's Kind being either Utc or Local, use ToUniversalTime:

public static long ToUnixTime(this DateTime date)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}

ToUniversalTime will convert a Local (or Unspecified) DateTime to Utc.

if you dont want to create the epoch DateTime instance when moving from DateTime to epoch you can also do:

public static long ToUnixTime(this DateTime date)
{
    return (date.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}

How to get week number in Python?

For the integer value of the instantaneous week of the year try:

import datetime
datetime.datetime.utcnow().isocalendar()[1]

TypeError: unhashable type: 'numpy.ndarray'

numpy.ndarray can contain any type of element, e.g. int, float, string etc. Check the type an do a conversion if neccessary.

Switch with if, else if, else, and loops inside case

If you need the for statement to contain only the if, you need to remove its else, like this:

for(int i=0; i<something_in_the_array.length;i++)
    if(whatever_value==(something_in_the_array[i]))
    {
        value=2;
        break;
    }

    /*this "else" must go*/
    if(whatever_value==2)
    {
        value=3;
        break;
    }

    else if(whatever_value==3)
    {
        value=4;
        break;
    }

JavaScript chop/slice/trim off last character in string

Use regex:

_x000D_
_x000D_
let aStr = "12345.00";_x000D_
aStr = aStr.replace(/.$/, '');_x000D_
console.log(aStr);
_x000D_
_x000D_
_x000D_

Excel VBA - select a dynamic cell range

sub selectVar ()
    dim x,y as integer
    let srange = "A" & x & ":" & "m" & y
    range(srange).select
end sub

I think this is the simplest way.

Remove all spaces from a string in SQL Server

I would use a REPLACE

select REPLACE (' Hello , How Are You ?', ' ', '' )

REPLACE

How to check if memcache or memcached is installed for PHP?

Note that all of the class_exists, extensions_loaded, and function_exists only check the link between PHP and the memcache package.

To actually check whether memcache is installed you must either:

  • know the OS platform and use shell commands to check whether memcache package is installed
  • or test whether memcache connection can be established on the expected port

EDIT 2: OK, actually here's an easier complete solution:

if (class_exists('Memcache')) {
    $memcache = new Memcache;
    $isMemcacheAvailable = @$memcache->connect('localhost');
}
if ($isMemcacheAvailable) {
    //...
}

Outdated code below


EDIT: Actually you must force PHP to throw error on warnings first. Have a look at this SO question answer.

You can then test the connection via:

try {
    $memcache->connect('localhost');
} catch (Exception $e) {
    // well it's not here
}

How can I initialise a static Map?

I like the Guava way of initialising a static, immutable map:

static final Map<Integer, String> MY_MAP = ImmutableMap.of(
    1, "one",
    2, "two"
);

As you can see, it's very concise (because of the convenient factory methods in ImmutableMap).

If you want the map to have more than 5 entries, you can no longer use ImmutableMap.of(). Instead, try ImmutableMap.builder() along these lines:

static final Map<Integer, String> MY_MAP = ImmutableMap.<Integer, String>builder()
    .put(1, "one")
    .put(2, "two")
    // ... 
    .put(15, "fifteen")
    .build();

To learn more about the benefits of Guava's immutable collection utilities, see Immutable Collections Explained in Guava User Guide.

(A subset of) Guava used to be called Google Collections. If you aren't using this library in your Java project yet, I strongly recommend trying it out! Guava has quickly become one of the most popular and useful free 3rd party libs for Java, as fellow SO users agree. (If you are new to it, there are some excellent learning resources behind that link.)


Update (2015): As for Java 8, well, I would still use the Guava approach because it is way cleaner than anything else. If you don't want Guava dependency, consider a plain old init method. The hack with two-dimensional array and Stream API is pretty ugly if you ask me, and gets uglier if you need to create a Map whose keys and values are not the same type (like Map<Integer, String> in the question).

As for future of Guava in general, with regards to Java 8, Louis Wasserman said this back in 2014, and [update] in 2016 it was announced that Guava 21 will require and properly support Java 8.


Update (2016): As Tagir Valeev points out, Java 9 will finally make this clean to do using nothing but pure JDK, by adding convenience factory methods for collections:

static final Map<Integer, String> MY_MAP = Map.of(
    1, "one", 
    2, "two"
);

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

How to work with string fields in a C struct?

I think this solution uses less code and is easy to understand even for newbie.

For string field in struct, you can use pointer and reassigning the string to that pointer will be straightforward and simpler.

Define definition of struct:

typedef struct {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} Patient;

Initialize variable with type of that struct:

Patient patient;
patient.number = 12345;
patient.address = "123/123 some road Rd.";
patient.birthdate = "2020/12/12";
patient.gender = "M";

It is that simple. Hope this answer helps many developers.

How can I stop .gitignore from appearing in the list of untracked files?

I found that the best place to set up an ignore to the pesky .DS_Store files is in the .git/info/exclude file.

IntelliJ seems to do this automatically when you set up a git repository in it.

Is it fine to have foreign key as primary key?

Short answer: DEPENDS.... In this particular case, it might be fine. However, experts will recommend against it just about every time; including your case.

Why?

Keys are seldomly unique in tables when they are foreign (originated in another table) to the table in question. For example, an item ID might be unique in an ITEMS table, but not in an ORDERS table, since the same type of item will most likely exist in another order. Likewise, order IDs might be unique (might) in the ORDERS table, but not in some other table like ORDER_DETAILS where an order with multiple line items can exist and to query against a particular item in a particular order, you need the concatenation of two FK (order_id and item_id) as the PK for this table.

I am not DB expert, but if you can justify logically to have an auto-generated value as your PK, I would do that. If this is not practical, then a concatenation of two (or maybe more) FK could serve as your PK. BUT, I cannot think of any case where a single FK value can be justified as the PK.

How do I programmatically "restart" an Android app?

try this:

Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Change user-agent for Selenium web-driver

There is no way in Selenium to read the request or response headers. You could do it by instructing your browser to connect through a proxy that records this kind of information.

Setting the User Agent in Firefox

The usual way to change the user agent for Firefox is to set the variable "general.useragent.override" in your Firefox profile. Note that this is independent from Selenium.

You can direct Selenium to use a profile different from the default one, like this:

from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "whatever you want")
driver = webdriver.Firefox(profile)

Setting the User Agent in Chrome

With Chrome, what you want to do is use the user-agent command line option. Again, this is not a Selenium thing. You can invoke Chrome at the command line with chrome --user-agent=foo to set the agent to the value foo.

With Selenium you set it like this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("user-agent=whatever you want")

driver = webdriver.Chrome(chrome_options=opts)

Both methods above were tested and found to work. I don't know about other browsers.

Getting the User Agent

Selenium does not have methods to query the user agent from an instance of WebDriver. Even in the case of Firefox, you cannot discover the default user agent by checking what general.useragent.override would be if not set to a custom value. (This setting does not exist before it is set to some value.)

Once the browser is started, however, you can get the user agent by executing:

agent = driver.execute_script("return navigator.userAgent")

The agent variable will contain the user agent.

How to solve a pair of nonlinear equations using Python?

You can use openopt package and its NLP method. It has many dynamic programming algorithms to solve nonlinear algebraic equations consisting:
goldenSection, scipy_fminbound, scipy_bfgs, scipy_cg, scipy_ncg, amsg2p, scipy_lbfgsb, scipy_tnc, bobyqa, ralg, ipopt, scipy_slsqp, scipy_cobyla, lincher, algencan, which you can choose from.
Some of the latter algorithms can solve constrained nonlinear programming problem. So, you can introduce your system of equations to openopt.NLP() with a function like this:

lambda x: x[0] + x[1]**2 - 4, np.exp(x[0]) + x[0]*x[1]

How do you remove duplicates from a list whilst preserving order?

Borrowing the recursive idea used in definining Haskell's nub function for lists, this would be a recursive approach:

def unique(lst):
    return [] if lst==[] else [lst[0]] + unique(filter(lambda x: x!= lst[0], lst[1:]))

e.g.:

In [118]: unique([1,5,1,1,4,3,4])
Out[118]: [1, 5, 4, 3]

I tried it for growing data sizes and saw sub-linear time-complexity (not definitive, but suggests this should be fine for normal data).

In [122]: %timeit unique(np.random.randint(5, size=(1)))
10000 loops, best of 3: 25.3 us per loop

In [123]: %timeit unique(np.random.randint(5, size=(10)))
10000 loops, best of 3: 42.9 us per loop

In [124]: %timeit unique(np.random.randint(5, size=(100)))
10000 loops, best of 3: 132 us per loop

In [125]: %timeit unique(np.random.randint(5, size=(1000)))
1000 loops, best of 3: 1.05 ms per loop

In [126]: %timeit unique(np.random.randint(5, size=(10000)))
100 loops, best of 3: 11 ms per loop

I also think it's interesting that this could be readily generalized to uniqueness by other operations. Like this:

import operator
def unique(lst, cmp_op=operator.ne):
    return [] if lst==[] else [lst[0]] + unique(filter(lambda x: cmp_op(x, lst[0]), lst[1:]), cmp_op)

For example, you could pass in a function that uses the notion of rounding to the same integer as if it was "equality" for uniqueness purposes, like this:

def test_round(x,y):
    return round(x) != round(y)

then unique(some_list, test_round) would provide the unique elements of the list where uniqueness no longer meant traditional equality (which is implied by using any sort of set-based or dict-key-based approach to this problem) but instead meant to take only the first element that rounds to K for each possible integer K that the elements might round to, e.g.:

In [6]: unique([1.2, 5, 1.9, 1.1, 4.2, 3, 4.8], test_round)
Out[6]: [1.2, 5, 1.9, 4.2, 3]

User Control - Custom Properties

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

How can I start and check my MySQL log?

Its given on OFFICIAL MYSQL website.

SET GLOBAL general_log = 'ON';

You can also use custom path:

[mysqld]
# Set Slow Query Log
long_query_time = 1
slow_query_log = 1
slow_query_log_file = "C:/slowquery.log"

#Set General Log
log = "C:/genquery.log"

Command CompileSwift failed with a nonzero exit code in Xcode 10

I also encountered the same issue and I did what @cdeerinck suggested and got to the following link which suggested adding a user-defined variable to the Build Settings to disable batch mode i.e. add a new user defined variable named SWIFT_ENABLE_BATCH_MODE and set it to NO, I was able to get more insights into the issue and I got to know that the error was in a framework using CommonCrypto which was added to it(by me) but since Xcode 10 it is exposed natively as part of Swift (for Apple platforms only), and adding it (or its existence from the previous version) was causing a name collision and hence it was throwing the error. To know more refer to the this link which explains the issue in more detail.

pip3: command not found

You would need to install pip3.

On Linux, the command would be: sudo apt install python3-pip

On Mac, using brew, first brew install python3
Then brew postinstall python3

Try calling pip3 -V to see if it worked.

Can't create handler inside thread which has not called Looper.prepare()

You create handler in background thread this way

private void createHandler() {
        Thread thread = new Thread() {
          public void run() {
               Looper.prepare();

               final Handler handler = new Handler();
               handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                       // Do Work
                        handler.removeCallbacks(this);
                        Looper.myLooper().quit();
                   }
                }, 2000);

                Looper.loop();
            }
        };
        thread.start();
    }

How to delete last character in a string in C#?

It's better if you use string.Join.

 class Product
 {
   public int ProductID { get; set; }
 }
 static void Main(string[] args)
 {
   List<Product> products = new List<Product>()
      {   
         new Product { ProductID = 1 },
         new Product { ProductID = 2 },
         new Product { ProductID = 3 }
      };
   string theURL = string.Join("&", products.Select(p => string.Format("productID={0}", p.ProductID)));
   Console.WriteLine(theURL);
 }

Matrix Multiplication in pure Python?

This is incorrect initialization. You interchanged row with col!

C = [[0 for row in range(len(A))] for col in range(len(B[0]))]

Correct initialization would be

C = [[0 for col in range(len(B[0]))] for row in range(len(A))]

Also I would suggest using better naming conventions. Will help you a lot in debugging. For example:

def matrixmult (A, B):
    rows_A = len(A)
    cols_A = len(A[0])
    rows_B = len(B)
    cols_B = len(B[0])

    if cols_A != rows_B:
      print "Cannot multiply the two matrices. Incorrect dimensions."
      return

    # Create the result matrix
    # Dimensions would be rows_A x cols_B
    C = [[0 for row in range(cols_B)] for col in range(rows_A)]
    print C

    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k] * B[k][j]
    return C

You can do a lot more, but you get the idea...

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

Command find_package has two modes: Module mode and Config mode. You are trying to use Module mode when you actually need Config mode.

Module mode

Find<package>.cmake file located within your project. Something like this:

CMakeLists.txt
cmake/FindFoo.cmake
cmake/FindBoo.cmake

CMakeLists.txt content:

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake")
find_package(Foo REQUIRED) # FOO_INCLUDE_DIR, FOO_LIBRARIES
find_package(Boo REQUIRED) # BOO_INCLUDE_DIR, BOO_LIBRARIES

include_directories("${FOO_INCLUDE_DIR}")
include_directories("${BOO_INCLUDE_DIR}")
add_executable(Bar Bar.hpp Bar.cpp)
target_link_libraries(Bar ${FOO_LIBRARIES} ${BOO_LIBRARIES})

Note that CMAKE_MODULE_PATH has high priority and may be usefull when you need to rewrite standard Find<package>.cmake file.

Config mode (install)

<package>Config.cmake file located outside and produced by install command of other project (Foo for example).

foo library:

> cat CMakeLists.txt 
cmake_minimum_required(VERSION 2.8)
project(Foo)

add_library(foo Foo.hpp Foo.cpp)
install(FILES Foo.hpp DESTINATION include)
install(TARGETS foo DESTINATION lib)
install(FILES FooConfig.cmake DESTINATION lib/cmake/Foo)

Simplified version of config file:

> cat FooConfig.cmake 
add_library(foo STATIC IMPORTED)
find_library(FOO_LIBRARY_PATH foo HINTS "${CMAKE_CURRENT_LIST_DIR}/../../")
set_target_properties(foo PROPERTIES IMPORTED_LOCATION "${FOO_LIBRARY_PATH}")

By default project installed in CMAKE_INSTALL_PREFIX directory:

> cmake -H. -B_builds
> cmake --build _builds --target install
-- Install configuration: ""
-- Installing: /usr/local/include/Foo.hpp
-- Installing: /usr/local/lib/libfoo.a
-- Installing: /usr/local/lib/cmake/Foo/FooConfig.cmake

Config mode (use)

Use find_package(... CONFIG) to include FooConfig.cmake with imported target foo:

> cat CMakeLists.txt 
cmake_minimum_required(VERSION 2.8)
project(Boo)

# import library target `foo`
find_package(Foo CONFIG REQUIRED)

add_executable(boo Boo.cpp Boo.hpp)
target_link_libraries(boo foo)
> cmake -H. -B_builds -DCMAKE_VERBOSE_MAKEFILE=ON
> cmake --build _builds
Linking CXX executable Boo
/usr/bin/c++ ... -o Boo /usr/local/lib/libfoo.a

Note that imported target is highly configurable. See my answer.

Update

How to run php files on my computer

In short:

  1. Install WAMP

  2. Put this file to C:\wamp\www\ProjectName\filename.php

  3. Go to browser: http://localhost/ProjectName/filename.php

How to merge remote changes at GitHub?

You can also force a push by adding the + symbol before your branch name.

git push origin +some_branch

How To: Execute command line in C#, get STD OUT results

// usage
const string ToolFileName = "example.exe";
string output = RunExternalExe(ToolFileName);

public string RunExternalExe(string filename, string arguments = null)
{
    var process = new Process();

    process.StartInfo.FileName = filename;
    if (!string.IsNullOrEmpty(arguments))
    {
        process.StartInfo.Arguments = arguments;
    }

    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.UseShellExecute = false;

    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardOutput = true;
    var stdOutput = new StringBuilder();
    process.OutputDataReceived += (sender, args) => stdOutput.AppendLine(args.Data); // Use AppendLine rather than Append since args.Data is one line of output, not including the newline character.

    string stdError = null;
    try
    {
        process.Start();
        process.BeginOutputReadLine();
        stdError = process.StandardError.ReadToEnd();
        process.WaitForExit();
    }
    catch (Exception e)
    {
        throw new Exception("OS error while executing " + Format(filename, arguments)+ ": " + e.Message, e);
    }

    if (process.ExitCode == 0)
    {
        return stdOutput.ToString();
    }
    else
    {
        var message = new StringBuilder();

        if (!string.IsNullOrEmpty(stdError))
        {
            message.AppendLine(stdError);
        }

        if (stdOutput.Length != 0)
        {
            message.AppendLine("Std output:");
            message.AppendLine(stdOutput.ToString());
        }

        throw new Exception(Format(filename, arguments) + " finished with exit code = " + process.ExitCode + ": " + message);
    }
}

private string Format(string filename, string arguments)
{
    return "'" + filename + 
        ((string.IsNullOrEmpty(arguments)) ? string.Empty : " " + arguments) +
        "'";
}

How to view UTF-8 Characters in VIM or Gvim

Try to reload the document using:

:e! ++enc=utf8

If that works you should maybe change the fileencodings settings in your .vimrc.

Not class selector in jQuery

You can use the :not filter selector:

$('foo:not(".someClass")')

Or not() method:

$('foo').not(".someClass")

More Info:

How to fix a locale setting warning from Perl

Another Git-related answer:

The source of the problem might be the Git server. If all else fails, try doing dpkg-reconfigure locales (or whatever is appropriate for your distribution) on the server.

How to install sklearn?

You didn't provide us which operating system are you on? If it is a Linux, make sure you have scipy installed as well, after that just do

pip install -U scikit-learn

If you are on windows you might want to check out these pages.

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

protected void Page_PreInit(object sender, EventArgs e) 
{ 
 if (Membership.GetUser() == null) //check the user weather user is logged in or not
    this.Page.MasterPageFile = "~/General.master";
 else
    this.Page.MasterPageFile = "~/myMaster.master";
}

Android toolbar center title and custom font

No one has mentioned this, but there are some attributes for Toolbar:

app:titleTextColor for setting the title text color

app:titleTextAppearance for setting the title text appearance

app:titleMargin for setting the margin

And there are other specific-side margins such as marginStart, etc.

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

Here is the way to access :after and :before style properties, defined in css:

// Get the color value of .element:before
var color = window.getComputedStyle(
    document.querySelector('.element'), ':before'
).getPropertyValue('color');

// Get the content value of .element:before
var content = window.getComputedStyle(
    document.querySelector('.element'), ':before'
).getPropertyValue('content');

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

These names refers to different ways to encode pixel image data (JPG and JPEG are the same thing, and TIFF may just enclose a jpeg with some additional metadata).

These image formats may use different compression algorithms, different color representations, different capability in carrying additional data other than the image itself, and so on.

For web applications, I'd say jpeg or gif is good enough. Jpeg is used more often due to its higher compression ratio, and gif is typically used for light weight animation where a flash (or something similar) is an over kill, or places where transparent background is desired. PNG can be used too, but I don't have much experience with that. BMP and TIFF probably are not good candidates for web applications.

Show popup after page load

When the DOM is finished loading you can add your code in the $(document).ready() function.

Remove the onclick from here:

<input type="submit" name="submit" value="Submit" onClick="PopUp()" />

Try this:

$(document).ready(function(){
   setTimeout(function(){
      PopUp();
   },5000); // 5000 to load it after 5 seconds from page load
});

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

Initialise a list to a specific length in Python

list multiplication works.

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Using a dictionary to count the items in a list

How about this:

src = [ 'one', 'two', 'three', 'two', 'three', 'three' ]
result_dict = dict( [ (i, src.count(i)) for i in set(src) ] )

This results in

{'one': 1, 'three': 3, 'two': 2}

How to list only files and not directories of a directory Bash?

find files: ls -l /home | grep "^-" | tr -s ' ' | cut -d ' ' -f 9

find directories: ls -l /home | grep "^d" | tr -s ' ' | cut -d ' ' -f 9

find links: ls -l /home | grep "^l" | tr -s ' ' | cut -d ' ' -f 9

tr -s ' ' turns the output into a space-delimited file the cut command says the delimiter is a space, and return the 9th field (always the filename/directory name/linkname).

I use this all the time!

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This error is caused by:

Y = Dataset.iloc[:,18].values

Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.

Removing whitespace between HTML elements when using line breaks

Inspired by Quentin's answer, you can also place the closing > next to the start of the next tag.

 <img src="..." alt="..."
 /><img src="..." alt="..."
 /><img src="..." alt="..."
 /><img src="..." alt="..."/>

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

Pretty sure pk_OrderID is the PK of AC_Shipping_Addresses

And you are trying to insert a duplicate via the _Order.OrderNumber

Do a

select * from AC_Shipping_Addresses where pk_OrderID = 165863;

or select count(*) ....

Pretty sure you will get a row returned.

What it is telling you is you are already using pk_OrderID = 165863 and cannot have another row with that value.

if you want to not insert if there is a row

insert into table (pk, value) 
select 11 as pk, 'val' as value 
where not exists (select 1 from table where pk = 11) 

How to convert string to boolean php

I do it in a way that will cast any case insensitive version of the string "false" to the boolean FALSE, but will behave using the normal php casting rules for all other strings. I think this is the best way to prevent unexpected behavior.

$test_var = 'False';
$test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
$result = (boolean) $test_var;

Or as a function:

function safeBool($test_var){
    $test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
    return (boolean) $test_var;
}

java comparator, how to sort by integer?

Simply changing

public int compare(Dog d, Dog d1) {
  return d.age - d1.age;
}

to

public int compare(Dog d, Dog d1) {
  return d1.age - d.age;
}

should sort them in the reverse order of age if that is what you are looking for.

Update:

@Arian is right in his comments, one of the accepted ways of declaring a comparator for a dog would be where you declare it as a public static final field in the class itself.

class Dog implements Comparable<Dog> {
    private String name;
    private int age;

    public static final Comparator<Dog> DESCENDING_COMPARATOR = new Comparator<Dog>() {
        // Overriding the compare method to sort the age
        public int compare(Dog d, Dog d1) {
            return d.age - d1.age;
        }
    };

    Dog(String n, int a) {
        name = n;
        age = a;
    }

    public String getDogName() {
        return name;
    }

    public int getDogAge() {
        return age;
    }

    // Overriding the compareTo method
    public int compareTo(Dog d) {
        return (this.name).compareTo(d.name);
    }

}

You could then use it any where in your code where you would like to compare dogs as follows:

// Sorts the array list using comparator
Collections.sort(list, Dog.DESCENDING_COMPARATOR);

Another important thing to remember when implementing Comparable is that it is important that compareTo performs consistently with equals. Although it is not required, failing to do so could result in strange behaviour on some collections such as some implementations of Sets. See this post for more information on sound principles of implementing compareTo.

Update 2: Chris is right, this code is susceptible to overflows for large negative values of age. The correct way to implement this in Java 7 and up would be Integer.compare(d.age, d1.age) instead of d.age - d1.age.

Update 3: With Java 8, your Comparator could be written a lot more succinctly as:

public static final Comparator<Dog> DESCENDING_COMPARATOR = 
    Comparator.comparing(Dog::getDogAge).reversed();

The syntax for Collections.sort stays the same, but compare can be written as

public int compare(Dog d, Dog d1) {
    return DESCENDING_COMPARATOR.compare(d, d1);
}

How can I create an editable dropdownlist in HTML?

The <select> tag only allows the use of predefined entries. The typical solution to your problem is to have one entry labeled 'Other' and a disabled edit field (<input type="text"). Add some JavaScript to enable the edit field only when 'Other' is selected.

It may be possible to somehow create a dropdown that allows direct editing, but IMO that is not worth the effort. If it was, Amazon, Google or Microsoft would be doing it ;-) Just get the job done with the least complicated solution. It as faster (your boss may like that) and usually easier to maintain (you may like that).

Android Firebase, simply get one child object's data

Firebase listeners fire for both the initial data and any changes.

If you're looking to synchronize the data in a collection, use ChildEventListener. If you're looking to synchronize a single object, use ValueEventListener. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.

This is covered in Firebase's quickstart guide for Android. The relevant code and quote:

FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    System.out.println(snapshot.getValue());  //prints "Do you have data? You'll love Firebase."
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {        
  }
});

In the example above, the value event will fire once for the initial state of the data, and then again every time the value of that data changes.

Please spend a few moments to go through that quick start. It shouldn't take more than 15 minutes and it will save you from a lot of head scratching and questions. The Firebase Android Guide is probably a good next destination, for this question specifically: https://firebase.google.com/docs/database/android/read-and-write

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

Convert pandas dataframe to NumPy array

A simple way to convert dataframe to numpy array:

import pandas as pd
df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
df_to_array = df.to_numpy()
array([[1, 3],
   [2, 4]])

Use of to_numpy is encouraged to preserve consistency.

Reference: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html

Error in Process.Start() -- The system cannot find the file specified

Try to replace your initialization code with:

ProcessStartInfo info 
    = new ProcessStartInfo(@"C:\Program Files\Internet Explorer\iexplore.exe");

Using non full filepath on Process.Start only works if the file is found in System32 folder.

Stashing only staged changes in git - is it possible?

Stashing just the index (staged changes) in Git is more difficult than it should be. I've found @Joe's answer to work well, and turned a minor variation of it into this alias:

stash-index = "!f() { \
  git stash push --quiet --keep-index -m \"temp for stash-index\" && \
  git stash push \"$@\" && \
  git stash pop --quiet stash@{1} && \
  git stash show -p | git apply -R; }; f"

It pushes both the staged and unstaged changes into a temporary stash, leaving the staged changes alone. It then pushes the staged changes into the stash, which is the stash we want to keep. Arguments passed to the alias, such as --message "whatever" will be added to this stash command. Finally, it pops the temporary stash to restore the original state and remove the temporary stash, and then finally "removes" the stashed changes from the working directory via a reverse patch application.

For the opposite problem of stashing just the unstaged changes (alias stash-working) see this answer.

Check if a string is null or empty in XSLT

In some cases, you might want to know when the value is specifically null, which is particularly necessary when using XML which has been serialized from .NET objects. While the accepted answer works for this, it also returns the same result when the string is blank or empty, i.e. '', so you can't differentiate.

<group>
    <item>
        <id>item 1</id>
        <CategoryName xsi:nil="true" />
    </item>
</group>

So you can simply test the attribute.

<xsl:if test="CategoryName/@xsi:nil='true'">
   Hello World.
</xsl:if>

Sometimes it's necessary to know the exact state and you can't simply check if CategoryName is instantiated, because unlike say Javascript

<xsl:if test="CategoryName">
   Hello World.
</xsl:if>

Will return true for a null element.

How can I plot data with confidence intervals?

Here is a solution using functions plot(), polygon() and lines().

 set.seed(1234)
 df <- data.frame(x =1:10,
                 F =runif(10,1,2),
                 L =runif(10,0,1),
                 U =runif(10,2,3))


 plot(df$x, df$F, ylim = c(0,4), type = "l")
 #make polygon where coordinates start with lower limit and 
 # then upper limit in reverse order
 polygon(c(df$x,rev(df$x)),c(df$L,rev(df$U)),col = "grey75", border = FALSE)
 lines(df$x, df$F, lwd = 2)
 #add red lines on borders of polygon
 lines(df$x, df$U, col="red",lty=2)
 lines(df$x, df$L, col="red",lty=2)

enter image description here

Now use example data provided by OP in another question:

   Lower <- c(0.418116841, 0.391011834, 0.393297710,
        0.366144073,0.569956636,0.224775521,0.599166016,0.512269587,
        0.531378573, 0.311448219, 0.392045751,0.153614913, 0.366684097,
        0.161100849,0.700274810,0.629714150, 0.661641288, 0.533404093,
        0.412427559, 0.432905333, 0.525306427,0.224292061,
        0.28893064,0.099543648, 0.342995605,0.086973739,0.289030388,
        0.081230826,0.164505624, -0.031290586,0.148383474,0.070517523,0.009686605,
        -0.052703529,0.475924192,0.253382210, 0.354011010,0.130295355,0.102253218,
        0.446598823,0.548330752,0.393985810,0.481691632,0.111811248,0.339626541,
        0.267831909,0.133460254,0.347996621,0.412472322,0.133671128,0.178969601,0.484070587,
        0.335833224,0.037258467, 0.141312363,0.361392799,0.129791998,
        0.283759439,0.333893418,0.569533076,0.385258093,0.356201955,0.481816148,
        0.531282473,0.273126565,0.267815691,0.138127486,0.008865700,0.018118398,0.080143484,
        0.117861634,0.073697418,0.230002398,0.105855042,0.262367348,0.217799352,0.289108011,
        0.161271889,0.219663224,0.306117717,0.538088622,0.320711912,0.264395149,0.396061543,
        0.397350946,0.151726970,0.048650180,0.131914718,0.076629840,0.425849394,
        0.068692279,0.155144797,0.137939059,0.301912657,-0.071415593,-0.030141781,0.119450922,
        0.312927614,0.231345972)

 Upper.limit <- c(0.6446223,0.6177311, 0.6034427, 0.5726503,
      0.7644718, 0.4585430, 0.8205418, 0.7154043,0.7370033,
      0.5285199, 0.5973728, 0.3764209, 0.5818298,
      0.3960867,0.8972357, 0.8370151, 0.8359921, 0.7449118,
      0.6152879, 0.6200704, 0.7041068, 0.4541011, 0.5222653,
      0.3472364, 0.5956551, 0.3068065, 0.5112895, 0.3081448,
      0.3745473, 0.1931089, 0.3890704, 0.3031025, 0.2472591,
      0.1976092, 0.6906118, 0.4736644, 0.5770463, 0.3528607,
      0.3307651, 0.6681629, 0.7476231, 0.5959025, 0.7128883,
      0.3451623, 0.5609742, 0.4739216, 0.3694883, 0.5609220,
      0.6343219, 0.3647751, 0.4247147, 0.6996334, 0.5562876,
      0.2586490, 0.3750040, 0.5922248, 0.3626322, 0.5243285,
      0.5548211, 0.7409648, 0.5820070, 0.5530232, 0.6863703,
      0.7206998, 0.4952387, 0.4993264, 0.3527727, 0.2203694,
      0.2583149, 0.3035342, 0.3462009, 0.3003602, 0.4506054,
      0.3359478, 0.4834151, 0.4391330, 0.5273411, 0.3947622,
      0.4133769, 0.5288060, 0.7492071, 0.5381701, 0.4825456,
      0.6121942, 0.6192227, 0.3784870, 0.2574025, 0.3704140,
      0.2945623, 0.6532694, 0.2697202, 0.3652230, 0.3696383,
      0.5268808, 0.1545602, 0.2221450, 0.3553377, 0.5204076,
      0.3550094)

  Fitted.values<- c(0.53136955, 0.50437146, 0.49837019,
  0.46939721, 0.66721423, 0.34165926, 0.70985388, 0.61383696,
  0.63419092, 0.41998407, 0.49470927, 0.26501789, 0.47425695,
  0.27859380, 0.79875525, 0.73336461, 0.74881668, 0.63915795,
  0.51385774, 0.52648789, 0.61470661, 0.33919656, 0.40559797,
  0.22339000, 0.46932536, 0.19689011, 0.40015996, 0.19468781,
  0.26952645, 0.08090917, 0.26872696, 0.18680999, 0.12847285,
  0.07245286, 0.58326799, 0.36352329, 0.46552867, 0.24157804,
  0.21650915, 0.55738088, 0.64797691, 0.49494416, 0.59728999,
  0.22848680, 0.45030036, 0.37087676, 0.25147426, 0.45445930,
  0.52339711, 0.24922310, 0.30184215, 0.59185198, 0.44606040,
  0.14795374, 0.25815819, 0.47680880, 0.24621212, 0.40404398,
  0.44435727, 0.65524894, 0.48363255, 0.45461258, 0.58409323,
  0.62599114, 0.38418264, 0.38357103, 0.24545011, 0.11461756,
  0.13821664, 0.19183886, 0.23203127, 0.18702881, 0.34030391,
  0.22090140, 0.37289121, 0.32846615, 0.40822456, 0.27801706,
  0.31652008, 0.41746184, 0.64364785, 0.42944100, 0.37347037,
  0.50412786, 0.50828681, 0.26510696, 0.15302635, 0.25116438,
  0.18559609, 0.53955941, 0.16920626, 0.26018389, 0.25378867,
  0.41439675, 0.04157232, 0.09600163, 0.23739430, 0.41666762,
  0.29317767)

Assemble into a data frame (no x provided, so using indices)

 df2 <- data.frame(x=seq(length(Fitted.values)),
                    fit=Fitted.values,lwr=Lower,upr=Upper.limit)
 plot(fit~x,data=df2,ylim=range(c(df2$lwr,df2$upr)))
 #make polygon where coordinates start with lower limit and then upper limit in reverse order
 with(df2,polygon(c(x,rev(x)),c(lwr,rev(upr)),col = "grey75", border = FALSE))
 matlines(df2[,1],df2[,-1],
          lwd=c(2,1,1),
          lty=1,
          col=c("black","red","red"))

enter image description here

Forward declaration of a typedef in C++

You can do forward typedef. But to do

typedef A B;

you must first forward declare A:

class A;

typedef A B;

Android - Activity vs FragmentActivity?

ianhanniballake is right. You can get all the functionality of Activity from FragmentActivity. In fact, FragmentActivity has more functionality.

Using FragmentActivity you can easily build tab and swap format. For each tab you can use different Fragment (Fragments are reusable). So for any FragmentActivity you can reuse the same Fragment.

Still you can use Activity for single pages like list down something and edit element of the list in next page.

Also remember to use Activity if you are using android.app.Fragment; use FragmentActivity if you are using android.support.v4.app.Fragment. Never attach a android.support.v4.app.Fragment to an android.app.Activity, as this will cause an exception to be thrown.

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

The reason for this error is very simple. Your AJAX is trying to call over HTTP whereas your server is running over HTTPS, so your server is denying calling your AJAX. This can be fixed by adding the following line inside the head tag of your main HTML file:

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> 

Mean of a column in a data frame, given the column's name

Any of the following should work!!

df <- data.frame(x=1:3,y=4:6)

mean(df$x)
mean(df[,1])
mean(df[["x"]])

Trying to mock datetime.date.today(), but not working

I faced the same situation a couple of days ago, and my solution was to define a function in the module to test and just mock that:

def get_date_now():
    return datetime.datetime.now()

Today I found out about FreezeGun, and it seems to cover this case beautifully

from freezegun import freeze_time
import datetime
import unittest


@freeze_time("2012-01-14")
def test():
    assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)

How to check if any Checkbox is checked in Angular

Try to think in terms of a model and what happens to that model when a checkbox is checked.

Assuming that each checkbox is bound to a field on the model with ng-model then the property on the model is changed whenever a checkbox is clicked:

<input type='checkbox' ng-model='fooSelected' />
<input type='checkbox' ng-model='baaSelected' />

and in the controller:

$scope.fooSelected = false;
$scope.baaSelected = false;

The next button should only be available under certain circumstances so add the ng-disabled directive to the button:

<button type='button' ng-disabled='nextButtonDisabled'></button>

Now the next button should only be available when either fooSelected is true or baaSelected is true and we need to watch any changes to these fields to make sure that the next button is made available or not:

$scope.$watch('[fooSelected,baaSelected]', function(){
    $scope.nextButtonDisabled = !$scope.fooSelected && !scope.baaSelected;
}, true );

The above assumes that there are only a few checkboxes that affect the availability of the next button but it could be easily changed to work with a larger number of checkboxes and use $watchCollection to check for changes.

Node.js Hostname/IP doesn't match certificate's altnames

Since 0.9.2 (including 0.10.x) node.js now validates certificates by default. This is why you could see it become more strict when you upgrade past node.js 0.8. (HT: https://github.com/mscdex/node-imap/issues/181#issuecomment-14781480)

You can avoid this with the {rejectUnauthorized:false} option, however this has serious security implications. Anything you send to the peer will still be encrypted, but it becomes much easier to mount a man-in-the-middle attack, i.e. your data will be encrypted to the peer but the peer itself is not the server you think it is!

It would be better to first diagnose why the certificate is not authorizing and see if that could be fixed instead.

Conda version pip install -r requirements.txt --target ./lib

You can always try this:

/home/user/anaconda3/bin/pip install -r requirements.txt

This simply uses the pip installed in the conda environment. If pip is not preinstalled in your environment you can always run the following command

conda install pip

JavaScript for...in vs for

The two are not the same when the array is sparse.

var array = [0, 1, 2, , , 5];

for (var k in array) {
  // Not guaranteed by the language spec to iterate in order.
  alert(k);  // Outputs 0, 1, 2, 5.
  // Behavior when loop body adds to the array is unclear.
}

for (var i = 0; i < array.length; ++i) {
  // Iterates in order.
  // i is a number, not a string.
  alert(i);  // Outputs 0, 1, 2, 3, 4, 5
  // Behavior when loop body modifies array is clearer.
}

In Python, what happens when you import inside of a function?

It imports once when the function executes first time.

Pros:

  • imports related to the function they're used in
  • easy to move functions around the package

Cons:

  • couldn't see what modules this module might depend on

REST API Token-based Authentication

A pure RESTful API should use the underlying protocol standard features:

  1. For HTTP, the RESTful API should comply with existing HTTP standard headers. Adding a new HTTP header violates the REST principles. Do not re-invent the wheel, use all the standard features in HTTP/1.1 standards - including status response codes, headers, and so on. RESTFul web services should leverage and rely upon the HTTP standards.

  2. RESTful services MUST be STATELESS. Any tricks, such as token based authentication that attempts to remember the state of previous REST requests on the server violates the REST principles. Again, this is a MUST; that is, if you web server saves any request/response context related information on the server in attempt to establish any sort of session on the server, then your web service is NOT Stateless. And if it is NOT stateless it is NOT RESTFul.

Bottom-line: For authentication/authorization purposes you should use HTTP standard authorization header. That is, you should add the HTTP authorization / authentication header in each subsequent request that needs to be authenticated. The REST API should follow the HTTP Authentication Scheme standards.The specifics of how this header should be formatted are defined in the RFC 2616 HTTP 1.1 standards – section 14.8 Authorization of RFC 2616, and in the RFC 2617 HTTP Authentication: Basic and Digest Access Authentication.

I have developed a RESTful service for the Cisco Prime Performance Manager application. Search Google for the REST API document that I wrote for that application for more details about RESTFul API compliance here. In that implementation, I have chosen to use HTTP "Basic" Authorization scheme. - check out version 1.5 or above of that REST API document, and search for authorization in the document.

I want to multiply two columns in a pandas DataFrame and add the result into a new column

For me, this is the clearest and most intuitive:

values = []
for action in ['Sell','Buy']:
    amounts = orders_df['Amounts'][orders_df['Action'==action]].values
    if action == 'Sell':
        prices = orders_df['Prices'][orders_df['Action'==action]].values
    else:
        prices = -1*orders_df['Prices'][orders_df['Action'==action]].values
    values += list(amounts*prices)  
orders_df['Values'] = values

The .values method returns a numpy array allowing you to easily multiply element-wise and then you can cumulatively generate a list by 'adding' to it.

Convert a Unicode string to a string in Python (containing extra symbols)

>>> text=u'abcd'
>>> str(text)
'abcd'

If the string only contains ascii characters.