Programs & Examples On #Cgi application

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

Go to "File" in android studio, Click "invalidate caches/Restart" and "Invalidate and Restart"

That also works

Angular2 multiple router-outlet in the same template

You can not use multiple router outlets in the same template with ngIf condition. But you can use it in the way shown below:

<div *ngIf="loading">
  <span>loading true</span>
  <ng-container *ngTemplateOutlet="template"></ng-container>
</div>

<div *ngIf="!loading">
  <span>loading false</span>
  <ng-container *ngTemplateOutlet="template"></ng-container>
  </div>

  <ng-template #template>
    <router-outlet> </router-outlet>
  </ng-template>

How can I check if a user is logged-in in php?

Almost all of the answers on this page rely on checking a session variable's existence to validate a user login. That is absolutely fine, but it is important to consider that the PHP session state is not unique to your application if there are multiple virtual hosts/sites on the same bare metal.

If you have two PHP applications on a webserver, both checking a user's login status with a boolean flag in a session variable called 'isLoggedIn', then a user could log into one of the applications and then automagically gain access to the second without credentials.

I suspect even the most dinosaur of commercial shared hosting wouldn't let virtual hosts share the same PHP environment in such a way that this could happen across multiple customers site's (anymore), but its something to consider in your own environments.

The very simple solution is to use a session variable that identifies the app rather than a boolean flag. e.g $SESSION["isLoggedInToExample.com"].

Source: I'm a penetration tester, with a lot of experience on how you shouldn't do stuff.

Go doing a GET request and building the Querystring

Use r.URL.Query() when you appending to existing query, if you are building new set of params use the url.Values struct like so

package main

import (
    "fmt"
    "log"
    "net/http"
    "net/url"
    "os"
)

func main() {
    req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
    if err != nil {
        log.Print(err)
        os.Exit(1)
    }

    // if you appending to existing query this works fine 
    q := req.URL.Query()
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")

    // or you can create new url.Values struct and encode that like so
    q := url.Values{}
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")

    req.URL.RawQuery = q.Encode()

    fmt.Println(req.URL.String())
    // Output:
    // http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}

How can I clear the terminal in Visual Studio Code?

just type 'clear' in the terminal (windows) or ctrl+shift+p and on mac - right click

javascript date to string

I like Daniel Cerecedo's answer using toJSON() and regex. An even simpler form would be:

var now = new Date();
var regex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).*$/;
var token_array = regex.exec(now.toJSON());
// [ "2017-10-31T02:24:45.868Z", "2017", "10", "31", "02", "24", "45" ]
var myFormat = token_array.slice(1).join('');
// "20171031022445"

how to run or install a *.jar file in windows?

Have you tried (from a command line)

java -jar jbpm-installer-3.2.7.jar

or double clicking it with the mouse ?

Found this and this by googling.

Hope it helps

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

I tried to install only LocalDB, which was missed in my VS 2015 installation. Followed below URL & selectively download the LocalDB (2012) installer which is only 33mb in size :)

https://www.microsoft.com/en-us/download/details.aspx?id=29062

If you are looking for the SQL Server Data Tool for Visual Studio 2015 Integration, then Please download that from :

https://msdn.microsoft.com/en-us/mt186501

How to auto-generate a C# class file from a JSON string

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

onclick on a image to navigate to another page using Javascript

Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:

<script>
    $(document).ready(function() {
        $('img.thumbnail').click(function() {
            window.location.href = this.id + '.html';
        });
    });
</script>

Basically, it attaches an onClick event to all images with class thumbnail to redirect to the corresponding HTML page (id + .html). Then you only need the images in your HTML (without the a elements), like this:

<img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
<img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />

How to get pandas.DataFrame columns containing specific dtype

dtypes is a Pandas Series. That means it contains index & values attributes. If you only need the column names:

headers = df.dtypes.index

it will return a list containing the column names of "df" dataframe.

How to make a great R reproducible example

Inspired by this very post, I now use a handy function,
reproduce(<mydata>) when I need to post to StackOverflow.


QUICK INSTRUCTIONS

If myData is the name of your object to reproduce, run the following in R:

install.packages("devtools")
library(devtools)
source_url("https://raw.github.com/rsaporta/pubR/gitbranch/reproduce.R")

reproduce(myData)

Details:

This function is an intelligent wrapper to dput and does the following:

  • Automatically samples a large data set (based on size and class. Sample size can be adjusted)
  • Creates a dput output
  • Allows you to specify which columns to export
  • Appends to the front of it objName <- ... so that it can be easily copy+pasted, but...
  • If working on a mac, the output is automagically copied to the clipboard, so that you can simply run it and then paste it to your question.

The source is available here:


Example:

# sample data
DF <- data.frame(id=rep(LETTERS, each=4)[1:100], replicate(100, sample(1001, 100)), Class=sample(c("Yes", "No"), 100, TRUE))

DF is about 100 x 102. I want to sample 10 rows and a few specific columns

reproduce(DF, cols=c("id", "X1", "X73", "Class"))  # I could also specify the column number. 

Gives the following output:

This is what the sample looks like: 

    id  X1 X73 Class
1    A 266 960   Yes
2    A 373 315    No            Notice the selection split 
3    A 573 208    No           (which can be turned off)
4    A 907 850   Yes
5    B 202  46   Yes         
6    B 895 969   Yes   <~~~ 70 % of selection is from the top rows
7    B 940 928    No
98   Y 371 171   Yes          
99   Y 733 364   Yes   <~~~ 30 % of selection is from the bottom rows.  
100  Y 546 641    No        


    ==X==============================================================X==
         Copy+Paste this part. (If on a Mac, it is already copied!)
    ==X==============================================================X==

 DF <- structure(list(id = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 25L, 25L, 25L), .Label = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"), class = "factor"), X1 = c(266L, 373L, 573L, 907L, 202L, 895L, 940L, 371L, 733L, 546L), X73 = c(960L, 315L, 208L, 850L, 46L, 969L, 928L, 171L, 364L, 641L), Class = structure(c(2L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L), .Label = c("No", "Yes"), class = "factor")), .Names = c("id", "X1", "X73", "Class"), class = "data.frame", row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 98L, 99L, 100L)) 

    ==X==============================================================X==

Notice also that the entirety of the output is in a nice single, long line, not a tall paragraph of chopped up lines. This makes it easier to read on SO questions posts and also easier to copy+paste.


Update Oct 2013:

You can now specify how many lines of text output will take up (ie, what you will paste into StackOverflow). Use the lines.out=n argument for this. Example:

reproduce(DF, cols=c(1:3, 17, 23), lines.out=7) yields:

    ==X==============================================================X==
         Copy+Paste this part. (If on a Mac, it is already copied!)
    ==X==============================================================X==

 DF <- structure(list(id = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 25L,25L, 25L), .Label
      = c("A", "B", "C", "D", "E", "F", "G", "H","I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U","V", "W", "X", "Y"), class = "factor"),
      X1 = c(809L, 81L, 862L,747L, 224L, 721L, 310L, 53L, 853L, 642L),
      X2 = c(926L, 409L,825L, 702L, 803L, 63L, 319L, 941L, 598L, 830L),
      X16 = c(447L,164L, 8L, 775L, 471L, 196L, 30L, 420L, 47L, 327L),
      X22 = c(335L,164L, 503L, 407L, 662L, 139L, 111L, 721L, 340L, 178L)), .Names = c("id","X1",
      "X2", "X16", "X22"), class = "data.frame", row.names = c(1L,2L, 3L, 4L, 5L, 6L, 7L, 98L, 99L, 100L))

    ==X==============================================================X==

UnicodeEncodeError: 'ascii' codec can't encode character at special name

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

Example -

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .

What is mod_php?

It means that you have to have PHP installed as a module in Apache, instead of starting it as a CGI script.

Get all directories within directory nodejs

functional programming

const fs = require('fs')
const path = require('path')
const R = require('ramda')

const getDirectories = pathName => {
    const isDirectory = pathName => fs.lstatSync(pathName).isDirectory()
    const mapDirectories = pathName => R.map(name => path.join(pathName, name), fs.readdirSync(pathName))
    const filterDirectories = listPaths => R.filter(isDirectory, listPaths)

    return {
        paths:R.pipe(mapDirectories)(pathName),
        pathsFiltered: R.pipe(mapDirectories, filterDirectories)(pathName)
    }
}

How to add 10 days to current time in Rails

Try this on Rails

Time.new + 10.days 

Try this on Ruby

require 'date'
DateTime.now.next_day(10).to_time

How to add bootstrap in angular 6 project?

npm install --save bootstrap

afterwards, inside angular.json (previously .angular-cli.json) inside the project's root folder, find styles and add the bootstrap css file like this:

for angular 6

"styles": [
          "../node_modules/bootstrap/dist/css/bootstrap.min.css",
          "styles.css"
],

for angular 7

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
],

Do I need <class> elements in persistence.xml?

You can provide for jar-file element path to a folder with compiled classes. For example I added something like that when I prepared persistence.xml to some integration tests:

 <jar-file>file:../target/classes</jar-file>

Java: Simplest way to get last word in a string

If other whitespace characters are possible, then you'd want:

testString.split("\\s+");

Method with a bool return

private bool CheckAll()
{
    if ( ....)
    {
        return true;
    }

    return false;
}

When the if-condition is false the method doesn't know what value should be returned (you probably get an error like "not all paths return a value").

As CQQL pointed out if you mean to return true when your if-condition is true you could have simply written:

private bool CheckAll()
{
    return (your_condition);
}

If you have side effects, and you want to handle them before you return, the first (long) version would be required.

JavaScript alert not working in Android WebView

You can try with this, it worked for me

WebView wb_previewSurvey=new WebView(this); 


       wb_previewSurvey.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            //Required functionality here
            return super.onJsAlert(view, url, message, result);
        }

    });

Default argument values in JavaScript functions

In javascript you can call a function (even if it has parameters) without parameters.

So you can add default values like this:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   //your code
}

and then you can call it like func(); to use default parameters.

Here's a test:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   alert("A: "+a+"\nB: "+b);
}
//testing
func();
func(80);
func(100,200);

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

AssemblyVersion pretty much stays internal to .NET, while AssemblyFileVersion is what Windows sees. If you go to the properties of an assembly sitting in a directory and switch to the version tab, the AssemblyFileVersion is what you'll see up top. If you sort files by version, this is what's used by Explorer.

The AssemblyInformationalVersion maps to the "Product Version" and is meant to be purely "human-used".

AssemblyVersion is certainly the most important, but I wouldn't skip AssemblyFileVersion, either. If you don't provide AssemblyInformationalVersion, the compiler adds it for you by stripping off the "revision" piece of your version number and leaving the major.minor.build.

Equivalent of LIMIT and OFFSET for SQL Server?

@nombre_row :nombre ligne par page  
@page:numero de la page

//--------------code sql---------------

declare  @page int,@nombre_row int;
    set @page='2';
    set @nombre_row=5;
    SELECT  *
FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY etudiant_ID ) AS RowNum, *
      FROM      etudiant

    ) AS RowConstrainedResult
WHERE   RowNum >= ((@page-1)*@nombre_row)+1
    AND RowNum < ((@page)*@nombre_row)+1
ORDER BY RowNum

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

same problem happened to me, From this

I have faced the same issue, to solve it:

1- delete (or move) the projects folder (AndroidStudioProjects).

2- Run the Android-Studio (a WELCOME screen will started).

3- From Welcome Screen choose, "Configure -> Project Defaults -> Project Structure)

4- Under Platform Settings choose SDKs.

5- Select Android SDK -> right_click delete.

6- Right_click -> New Sdk -> Android SDK -> choose your SDK dir -> then OK.

7- Choose the Build target -> apply -> OK. enjoy

How can I download HTML source in C#

The newest, most recent, up to date answer
This post is really old (it's 7 years old when I answered it), so no one of the other answers used the new and recommended way, which is HttpClient class.


HttpClient is considered the new API and it should replace the old ones (WebClient and WebRequest)

string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
   using (HttpContent content = response.Content)
   {
      string result = content.ReadAsStringAsync().Result;
   }
}

for more information about how to use the HttpClient class (especially in async cases), you can refer this question


NOTE 1: If you want to use async/await

string url = "page url";
HttpClient client = new HttpClient();   // actually only one object should be created by Application
using (HttpResponseMessage response = await client.GetAsync(url))
{
   using (HttpContent content = response.Content)
   {
      string result = await content.ReadAsStringAsync();
   }
}

NOTE 2: If use C# 8 features

string url = "page url";
HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();

Create file path from variables

You can also use an object-oriented path with pathlib (available as a standard library as of Python 3.4):

from pathlib import Path

start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

Short and easy Soloution:

Go to MSSQL Studio Sever ;

Run the query of the cause of this error : in my case i see that id value was null because i forget to set Identity specification increment by 1.

enter image description here

So entered 1 for the id field as its is autoincremane and modify dont allow NULLS in desing view

enter image description here

That was the error that caused my bindingsource and tabel adapter throwin error at this code:

   this.exchangeCheckoutReportTableAdapter.Fill(this.sbmsDataSet.ExchangeCheckouReportTable);

How to sort an array in descending order in Ruby

Simple Solution from ascending to descending and vice versa is:

STRINGS

str = ['ravi', 'aravind', 'joker', 'poker']
asc_string = str.sort # => ["aravind", "joker", "poker", "ravi"]
asc_string.reverse # => ["ravi", "poker", "joker", "aravind"]

DIGITS

digit = [234,45,1,5,78,45,34,9]
asc_digit = digit.sort # => [1, 5, 9, 34, 45, 45, 78, 234]
asc_digit.reverse # => [234, 78, 45, 45, 34, 9, 5, 1]

Key hash for Android-Facebook app

The best approach is to use the following code:

private void getHashKey(String pkgName)
{
    try
    {
        PackageInfo info = getPackageManager().getPackageInfo(pkgName, PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures)
        {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            String hashKey = Base64.encodeBytes(md.digest());
            _hashKey_et.setText(hashKey);
            Log.i("KeyTool", pkgName + " -> hashKey = " + hashKey);
        }
    }
    catch (NameNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (NoSuchAlgorithmException e)
    {
        e.printStackTrace();
    }
}

But I was so frustrating with the fact that there is no simple tool to generate the HashKey for the Facebook app. Each time I had to play with Openssl and Keytool or to use a code to get the hash from signature ...

So I wrote a simple KeyGenTool that will do that work for you: -> KeyGenTool on Google Play <-

Enjoy :)

Letter Count on a string

A simple way is as follows:

def count_letters(word, char):
    return word.count(char)

Or, there's another way count each element directly:

from collections import Counter
Counter('banana')

Of course, you can specify one element, e.g.

Counter('banana')['a']

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

In my case the form (which I cannot modify) was always sending POST.
While in my Web Service I tried to implement GET method (due to lack of documentation I expected that both are allowed).

Thus, it was failing as "Not allowed", since there was no method with POST type on my end.

Changing @GET to @POST above my WS method fixed the issue.

How to pass parameters to ThreadStart method in Thread?

How about this: (or is it ok to use like this?)

var test = "Hello";
new Thread(new ThreadStart(() =>
{
    try
    {
        //Staff to do
        Console.WriteLine(test);
    }
    catch (Exception ex)
    {
        throw;
    }
})).Start();

how to kill the tty in unix

In addition to AIXroot's answer, there is also a logout function that can be used to write a utmp logout record. So if you don't have any processes for user xxxx, but userdel says "userdel: account xxxx is currently in use", you can add a logout record manually. Create a file logout.c like this:

#include <stdio.h>
#include <utmp.h>

int main(int argc, char *argv[])
{
  if (argc == 2) {
    return logout(argv[1]);
  }
  else {
    fprintf(stderr, "Usage: logout device\n");
    return 1;
  }
}

Compile it:

gcc -lutil -o logout logout.c

And then run it for whatever it says in the output of finger's "On since" line(s) as a parameter:

# finger xxxx
Login: xxxx                             Name:
Directory: /home/xxxx                   Shell: /bin/bash
On since Sun Feb 26 11:06 (GMT) on 127.0.0.1:6 (messages off) from 127.0.0.1
On since Fri Feb 24 16:53 (GMT) on pts/6, idle 3 days 17:16, from 127.0.0.1
Last login Mon Feb 10 14:45 (GMT) on pts/11 from somehost.example.com
Mail last read Sun Feb 27 08:44 2014 (GMT)
No Plan.

# userdel xxxx
userdel: account `xxxx' is currently in use.
# ./logout 127.0.0.1:6
# ./logout pts/6
# userdel xxxx
no crontab for xxxx

How do I solve this "Cannot read property 'appendChild' of null" error?

Just reorder or make sure, the (DOM or HTML) is loaded before the JavaScript.

Checking if a number is an Integer in Java

One example more :)

double a = 1.00

if(floor(a) == a) {
   // a is an integer
} else {
   //a is not an integer.
}

In this example, ceil can be used and have the exact same effect.

The request was aborted: Could not create SSL/TLS secure channel

I had this issue uploading a video to Wistia via a command line app. Our system administrator resolved the issue by enabling additional cipher suites using IIScrypto that was listed in the SSL labs scan for upload.wistia.com

TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 (0x9e) DH 2048 bits FS 128 TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 (0x9f) DH 2048 bits FS 256

Scale image to fit a bounding box

Here's a hackish solution I discovered:

#image {
    max-width: 10%;
    max-height: 10%;
    transform: scale(10);
}

This will enlarge the image tenfold, but restrict it to 10% of its final size - thus bounding it to the container.

Unlike the background-image solution, this will also work with <video> elements.

Interactive example:

_x000D_
_x000D_
 function step(timestamp) {
     var container = document.getElementById('container');
     timestamp /= 1000;
     container.style.left   = (200 + 100 * Math.sin(timestamp * 1.0)) + 'px';
     container.style.top    = (200 + 100 * Math.sin(timestamp * 1.1)) + 'px';
     container.style.width  = (500 + 500 * Math.sin(timestamp * 1.2)) + 'px';
     container.style.height = (500 + 500 * Math.sin(timestamp * 1.3)) + 'px';
     window.requestAnimationFrame(step);
 }

 window.requestAnimationFrame(step);
_x000D_
 #container {
     outline: 1px solid black;
     position: relative;
     background-color: red;
 }
 #image {
     display: block;
     max-width: 10%;
     max-height: 10%;
     transform-origin: 0 0;
     transform: scale(10);
 }
_x000D_
<div id="container">
    <img id="image" src="https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png">
</div>
_x000D_
_x000D_
_x000D_

How to enable scrolling of content inside a modal?

Bootstrap will add or remove a css "modal-open" to the <body> tag when we open or close a modal. So if you open multiple modal and then close arbitrary one, the modal-open css will be removed from the body tag.

But the scroll effect depend on the attribute "overflow-y: auto;" defined in modal-open

How can I remove a child node in HTML using JavaScript?

If you want to clear the div and remove all child nodes, you could put:

var mydiv = document.getElementById('FirstDiv');
while(mydiv.firstChild) {
  mydiv.removeChild(mydiv.firstChild);
}

How do you tell if a string contains another string in POSIX sh?

Here's yet another solution. This uses POSIX substring parameter expansion, so it works in Bash, Dash, KornShell (ksh), Z shell (zsh), etc.

test "${string#*$word}" != "$string" && echo "$word found in $string"

A functionalized version with some examples:

# contains(string, substring)
#
# Returns 0 if the specified string contains the specified substring,
# otherwise returns 1.
contains() {
    string="$1"
    substring="$2"
    if test "${string#*$substring}" != "$string"
    then
        return 0    # $substring is in $string
    else
        return 1    # $substring is not in $string
    fi
}

contains "abcd" "e" || echo "abcd does not contain e"
contains "abcd" "ab" && echo "abcd contains ab"
contains "abcd" "bc" && echo "abcd contains bc"
contains "abcd" "cd" && echo "abcd contains cd"
contains "abcd" "abcd" && echo "abcd contains abcd"
contains "" "" && echo "empty string contains empty string"
contains "a" "" && echo "a contains empty string"
contains "" "a" || echo "empty string does not contain a"
contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
contains "abcd efgh" " " && echo "abcd efgh contains a space"

How to upload a file to directory in S3 bucket using boto

Try this...

import boto
import boto.s3
import sys
from boto.s3.key import Key

AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''

bucket_name = AWS_ACCESS_KEY_ID.lower() + '-dump'
conn = boto.connect_s3(AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY)


bucket = conn.create_bucket(bucket_name,
    location=boto.s3.connection.Location.DEFAULT)

testfile = "replace this with an actual filename"
print 'Uploading %s to Amazon S3 bucket %s' % \
   (testfile, bucket_name)

def percent_cb(complete, total):
    sys.stdout.write('.')
    sys.stdout.flush()


k = Key(bucket)
k.key = 'my test file'
k.set_contents_from_filename(testfile,
    cb=percent_cb, num_cb=10)

[UPDATE] I am not a pythonist, so thanks for the heads up about the import statements. Also, I'd not recommend placing credentials inside your own source code. If you are running this inside AWS use IAM Credentials with Instance Profiles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html), and to keep the same behaviour in your Dev/Test environment, use something like Hologram from AdRoll (https://github.com/AdRoll/hologram)

How to include another XHTML in XHTML using JSF 2.0 Facelets?

Included page:

<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>

Including page:

<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
  • You start your included xhtml file with ui:composition as shown above.
  • You include that file with ui:include in the including xhtml file as also shown above.

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

@Garret Wilson Thank you so much! As a noob to android coding, I've been stuck with the preferences incompatibility issue for so many hours, and I find it so disappointing they deprecated the use of some methods/approaches for new ones that aren't supported by the older APIs thus having to resort to all sorts of workarounds to make your app work in a wide range of devices. It's really frustrating!

Your class is great, for it allows you to keep working in new APIs wih preferences the way it used to be, but it's not backward compatible. Since I'm trying to reach a wide range of devices I tinkered with it a bit to make it work in pre API 11 devices as well as in newer APIs:

import android.annotation.TargetApi;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;

public class MyPrefsActivity extends PreferenceActivity
{
    private static int prefs=R.xml.myprefs;

    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        try {
            getClass().getMethod("getFragmentManager");
            AddResourceApi11AndGreater();
        } catch (NoSuchMethodException e) { //Api < 11
            AddResourceApiLessThan11();
        }
    }

    @SuppressWarnings("deprecation")
    protected void AddResourceApiLessThan11()
    {
        addPreferencesFromResource(prefs);
    }

    @TargetApi(11)
    protected void AddResourceApi11AndGreater()
    {
        getFragmentManager().beginTransaction().replace(android.R.id.content,
                new PF()).commit();
    }

    @TargetApi(11)
    public static class PF extends PreferenceFragment
    {       
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(MyPrefsActivity.prefs); //outer class
            // private members seem to be visible for inner class, and
            // making it static made things so much easier
        }
    }
}

Tested in two emulators (2.2 and 4.2) with success.

Why my code looks so crappy:

I'm a noob to android coding, and I'm not the greatest java fan.

In order to avoid the deprecated warning and to force Eclipse to allow me to compile I had to resort to annotations, but these seem to affect only classes or methods, so I had to move the code onto two new methods to take advantage of this.

I wouldn't like having to write my xml resource id twice anytime I copy&paste the class for a new PreferenceActivity, so I created a new variable to store this value.

I hope this will be useful to somebody else.

P.S.: Sorry for my opinionated views, but when you come new and find such handicaps, you can't help it but to get frustrated!

How to redirect 'print' output to a file using python?

In python 3, you can reassign print:

#!/usr/bin/python3

def other_fn():
    #This will use the print function that's active when the function is called
    print("Printing from function")

file_name = "test.txt"
with open(file_name, "w+") as f_out:
    py_print = print #Need to use this to restore builtin print later, and to not induce recursion
   
    print = lambda out_str : py_print(out_str, file=f_out)
    
    #If you'd like, for completeness, you can include args+kwargs
    print = lambda *args, **kwargs : py_print(*args, file=f_out, **kwargs)
    
    print("Writing to %s" %(file_name))

    other_fn()  #Writes to file

    #Must restore builtin print, or you'll get 'I/O operation on closed file'
    #If you attempt to print after this block
    print = py_print

print("Printing to stdout")
other_fn() #Writes to console/stdout

Note that the print from other_fn only switches outputs because print is being reassigned in the global scope. If we assign print within a function, the print in other_fn is normally not affected. We can use the global keyword if we want to affect all print calls:

import builtins

def other_fn():
    #This will use the print function that's active when the function is called
    print("Printing from function")

def main():
    global print #Without this, other_fn will use builtins.print
    file_name = "test.txt"
    with open(file_name, "w+") as f_out:

        print = lambda *args, **kwargs : builtins.print(*args, file=f_out, **kwargs)

        print("Writing to %s" %(file_name))

        other_fn()  #Writes to file

        #Must restore builtin print, or you'll get 'I/O operation on closed file'
        #If you attempt to print after this block
        print = builtins.print

    print("Printing to stdout")
    other_fn() #Writes to console/stdout

Personally, I'd prefer sidestepping the requirement to use the print function by baking the output file descriptor into a new function:

file_name = "myoutput.txt"
with open(file_name, "w+") as outfile:
    fprint = lambda pstring : print(pstring, file=outfile)
    print("Writing to stdout")
    fprint("Writing to %s" % (file_name))

Unable instantiate android.gms.maps.MapFragment

To take care of the Drive-related imports, you'll need a few jars from the Google Drive SDK. There are a few large ones, so you may want to add them individually to suit your app.

If that doesn't resolve the com.google.android.gms.* imports, the Google Play Services add-on needs to be installed (from Extras -> Google Play Services in the SDK Manager) and google-play-services.jar needs to be added to your build path.

EDIT:

In this case, the following jars were needed:

google-api-services-drive-v2-rev1-1.7.2-beta.jar

google-http-client-1.10.3-beta.jar

google-http-client-android2-1.10.3-beta.jar

google-oauth-client-1.10.1-beta.jar

google-api-client-android2-1.10.3-beta.jar

google-api-client-1.10.3-beta.jar

using nth-child in tables tr td

table tr td:nth-child(2) {
    background: #ccc;
}

Working example: http://jsfiddle.net/gqr3J/

simple HTTP server in Java using only Java SE API

checkout Simple. its a pretty simple embeddable server with built in support for quite a variety of operations. I particularly love its threading model..

Amazing!

plotting different colors in matplotlib

@tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it...

There are a number of different ways you could do this. To begin with, matplotlib will automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

If you want to control which colors matplotlib cycles through, use ax.set_color_cycle:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.set_color_cycle(['red', 'black', 'yellow'])
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

If you'd like to explicitly specify the colors that will be used, just pass it to the color kwarg (html colors names are accepted, as are rgb tuples and hex strings):

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i, color in enumerate(['red', 'black', 'blue', 'brown', 'green'], start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

Finally, if you'd like to automatically select a specified number of colors from an existing colormap:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
number = 5
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, number)]

for i, color in enumerate(colors, start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

Hidden Features of Java

Every class file starts with the hex value 0xCAFEBABE to identify it as valid JVM bytecode.

(Explanation)

How to justify navbar-nav in Bootstrap 3

You can justify the navbar contents by using:

@media (min-width: 768px){
  .navbar-nav{
     margin: 0 auto;
     display: table;
     table-layout: fixed;
     float: none;
  }
}  

See this live: http://jsfiddle.net/panchroma/2fntE/

Good luck!

NameError: global name is not defined

Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:

import module

over

from module import function/class

Converting JSON String to Dictionary Not List

Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

datapoints = json1_data['datapoints']

I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?

datapoints[0:5][0] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

[p[0] for p in datapoints[0:5]]

Here's a simple way to calculate the mean:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

If you're willing to install NumPy, then it's even easier:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.

Iterate keys in a C++ map

With C++17 you can use a structured binding inside a range-based for loop (adapting John H.'s answer accordingly):

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> myMap;

    myMap["one"] = 1;
    myMap["two"] = 2;
    myMap["three"] = 3;

    for ( const auto &[key, value]: myMap ) {
        std::cout << key << '\n';
    }
}

Unfortunately the C++17 standard requires you to declare the value variable, even though you're not using it (std::ignore as one would use for std::tie(..) does not work, see this discussion).

Some compilers may therefore warn you about the unused value variable! Compile-time warnings regarding unused variables are a no-go for any production code in my mind. So, this may not be applicable for certain compiler versions.

How to write subquery inside the OUTER JOIN Statement

You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.

SELECT
       cs.CUSID
       ,dp.DEPID
FROM
    CUSTMR cs
        LEFT OUTER JOIN (
            SELECT
                    DEPID
                    ,DEPNAME
                FROM
                    DEPRMNT 
                WHERE
                    dp.DEPADDRESS = 'TOKYO'
        ) ss
            ON (
                ss.DEPID = cs.CUSID
                AND ss.DEPNAME = cs.CUSTNAME
            )
WHERE
    cs.CUSID != '' 

How to enter special characters like "&" in oracle database?

you can simply escape & by following a dot. try this:

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 &. Oracle_14');

How to create a unique index on a NULL column?

The calculated column trick is widely known as a "nullbuster"; my notes credit Steve Kass:

CREATE TABLE dupNulls (
pk int identity(1,1) primary key,
X  int NULL,
nullbuster as (case when X is null then pk else 0 end),
CONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)
)

Hide all elements with class using plain Javascript

I would propose a different approach. Instead of changing the properties of all objects manually, let's add a new CSS to the document:

/* License: CC0 */
var newStylesheet = document.createElement('style');
newStylesheet.textContent = '.classname { display: none; }';
document.head.appendChild(newStylesheet);

How do I discard unstaged changes in Git?

This works even in directories that are; outside of normal git permissions.

sudo chmod -R 664 ./* && git checkout -- . && git clean -dfx

Happened to me recently

JavaScript - Get minutes between two dates

The following code worked for me,

function timeDiffCalc(dateNow,dateFuture) {
    var newYear1 = new Date(dateNow);
    var newYear2 = new Date(dateFuture);

        var dif = (newYear2 - newYear1);
        var dif = Math.round((dif/1000)/60);
        console.log(dif);

}

Unable to begin a distributed transaction

For me, it relate to Firewall setting. Go to your firewall setting, allow DTC Service and it worked.enter image description here

Saving awk output to variable

as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.

awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:

variable=$(ps -ef | awk '/port 10 \-/ {print $12}')

variable=`ps -ef | awk '/port 10 \-/ {print $12}'`

The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.

Configuring Log4j Loggers Programmatically

If someone comes looking for configuring log4j2 programmatically in Java, then this link could help: (https://www.studytonight.com/post/log4j2-programmatic-configuration-in-java-class)

Here is the basic code for configuring a Console Appender:

ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();

builder.setStatusLevel(Level.DEBUG);
// naming the logger configuration
builder.setConfigurationName("DefaultLogger");

// create a console appender
AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
                .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
// add a layout like pattern, json etc
appenderBuilder.add(builder.newLayout("PatternLayout")
                .addAttribute("pattern", "%d %p %c [%t] %m%n"));
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
rootLogger.add(builder.newAppenderRef("Console"));

builder.add(appenderBuilder);
builder.add(rootLogger);
Configurator.reconfigure(builder.build());

This will reconfigure the default rootLogger and will also create a new appender.

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

From Which comparator, test, bracket, or double bracket, is fastest? (http://bashcurescancer.com)

The double bracket is a “compound command” where as test and the single bracket are shell built-ins (and in actuality are the same command). Thus, the single bracket and double bracket execute different code.

The test and single bracket are the most portable as they exist as separate and external commands. However, if your using any remotely modern version of BASH, the double bracket is supported.

how to use DEXtoJar

Can be used as follow:

  1. Download dex2jar here and extract it.
  2. Download Java decompiler here (If you want to investigate .class file)
  3. Get you release .apk file and change its extension with .zip
  4. Extract .zip and find the classes.dex and classes2.dex
  5. Paste these files into dex2jar folder where .bat file exist of dex2jar (normally names as d2j-dex2jar)
  6. From dex2jar folder, open cmd [Shift+right click to see option to open cmd/power shell]
  7. Type the command in cmd: d2j-dex2jar release.apk
  8. You will get the .class file, open this file into Java Decompiler.

C++ program converts fahrenheit to celsius

Mine worked perfectly!

/* Two common temperature scales are Fahrenheit and Celsius.
** The boiling point of water is 212° F, and 100° C.
** The freezing point of water is 32° F, and 0° C.
** Assuming that the relationship bewtween these two
** temperature scales is: F = 9/5C+32,
** Celsius = (f-32) * 5/9.
***********************/

#include <iostream> // cin, cout

using namespace std; // System definition of cin and cout commands,
                     // if not, programmer would have to write every
                     // single line as: std::cout or std::cin

int main () // Main function

{

    /* Declare variables */
    double c, f;

    cout << "\nProgram that changes temperature from Celsius to Fahrenheit.\n";
    cout << "Please enter a temperature in Celsius: ";

    cin >> c;
    f = c * 9 / 5 + 32;
    cout << "\nA temperature of " << c << "° Celsius, is equivalent to "
         << f << "° Fahrenheit.\n";
    return 0;

}

How to disable submit button once it has been clicked?

I did the trick. When set timeout, it works perfectly and sending all values.

    $(document).ready(function () {
        document.getElementById('btnSendMail').onclick = function () {
            setTimeout(function () {
                document.getElementById('btnSendMail').value = 'Sending…';
                document.getElementById('btnSendMail').disabled = true;
            }, 850);
        }
    });

C++ How do I convert a std::chrono::time_point to long and back

as a single line:

long value_ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch()).count();

How to get temporary folder for current user

System.IO.Path.GetTempPath() is just a wrapper for a native call to GetTempPath(..) in Kernel32.

Have a look at http://msdn.microsoft.com/en-us/library/aa364992(VS.85).aspx

Copied from that page:

The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found:

  • The path specified by the TMP environment variable.
  • The path specified by the TEMP environment variable.
  • The path specified by the USERPROFILE environment variable.
  • The Windows directory.

It's not entirely clear to me whether "The Windows directory" means the temp directory under windows or the windows directory itself. Dumping temp files in the windows directory itself sounds like an undesirable case, but who knows.

So combining that page with your post I would guess that either one of the TMP, TEMP or USERPROFILE variables for your Administrator user points to the windows path, or else they're not set and it's taking a fallback to the windows temp path.

Filtering a list of strings based on contents

mylist = ['a', 'ab', 'abc']
assert 'ab' in mylist

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

Setting background colour of Android layout element

Android studio 2.1.2 (or possibly earlier) will let you pick from a color wheel:

Color Wheel in Android Studio

I got this by adding the following to my layout:

android:background="#FFFFFF"

Then I clicked on the FFFFFF color and clicked on the lightbulb that appeared.

update package.json version automatically

I am using husky and git-branch-is:

As of husky v1+:

// package.json
{
  "husky": {
    "hooks": {
      "post-merge": "(git-branch-is master && npm version minor || 
  (git-branch-is dev && npm --no-git-tag-version version patch)",
    }
  }
}

Prior to husky V1:

"scripts": {
  ...
  "postmerge": "(git-branch-is master && npm version minor || 
  (git-branch-is dev && npm --no-git-tag-version version patch)",
  ...
},

Read more about npm version

Webpack or Vue.js

If you are using webpack or Vue.js, you can display this in the UI using Auto inject version - Webpack plugin

NUXT

In nuxt.config.js:

var WebpackAutoInject = require('webpack-auto-inject-version');

module.exports = {
  build: {
    plugins: [
      new WebpackAutoInject({
        // options
        // example:
        components: {
          InjectAsComment: false
        },
      }),
    ]
  },
}

Inside your template for example in the footer:

<p> All rights reserved © 2018 [v[AIV]{version}[/AIV]]</p>

Remove spaces from std::string in C++

string replaceinString(std::string str, std::string tofind, std::string toreplace)
{
        size_t position = 0;
        for ( position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position) )
        {
                str.replace(position ,1, toreplace);
        }
        return(str);
}

use it:

string replace = replaceinString(thisstring, " ", "%20");
string replace2 = replaceinString(thisstring, " ", "-");
string replace3 = replaceinString(thisstring, " ", "+");

How to get value of a div using javascript

First of all

<div id="demo" align="center"  value="1"></div>

that is not valid HTML. Read up on custom data attributes or use the following instead:

<div id="demo" align="center" data-value="1"></div>

Since "data-value" is an attribute, you have to use the getAttribute function to retrieve its value.

var cookieValue = document.getElementById("demo").getAttribute("data-value"); 

How to get height of Keyboard?

Swift

You can get the keyboard height by subscribing to the UIKeyboardWillShowNotification notification. (Assuming you want to know what the height will be before it's shown).

Swift 4

NotificationCenter.default.addObserver(
    self,
    selector: #selector(keyboardWillShow),
    name: UIResponder.keyboardWillShowNotification,
    object: nil
)
@objc func keyboardWillShow(_ notification: Notification) {
    if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
    }
}

Swift 3

NotificationCenter.default.addObserver(
    self,
    selector: #selector(keyboardWillShow),
    name: NSNotification.Name.UIKeyboardWillShow,
    object: nil
)
@objc func keyboardWillShow(_ notification: Notification) {
    if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
    }
}

Swift 2

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
func keyboardWillShow(notification: NSNotification) {
        let userInfo: NSDictionary = notification.userInfo!
        let keyboardFrame: NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
        let keyboardRectangle = keyboardFrame.CGRectValue()
        let keyboardHeight = keyboardRectangle.height
    }

Python: Get relative path from comparing two absolute paths

A write-up of jme's suggestion, using pathlib, in Python 3.

from pathlib import Path
parent = Path(r'/a/b')
son = Path(r'/a/b/c/d')            
?
if parent in son.parents or parent==son:
    print(son.relative_to(parent)) # returns Path object equivalent to 'c/d'

T-SQL stored procedure that accepts multiple Id values

A superfast XML Method, if you want to use a stored procedure and pass the comma separated list of Department IDs :

Declare @XMLList xml
SET @XMLList=cast('<i>'+replace(@DepartmentIDs,',','</i><i>')+'</i>' as xml)
SELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i))

All credit goes to Guru Brad Schulz's Blog

Unix command to find lines common in two files

The command you are seeking is comm. eg:-

comm -12 1.sorted.txt 2.sorted.txt

Here:

-1 : suppress column 1 (lines unique to 1.sorted.txt)

-2 : suppress column 2 (lines unique to 2.sorted.txt)

Iterating over a numpy array

I think you're looking for the ndenumerate.

>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
...  print x,y
... 
0 0
0 1
1 0
1 1
2 0
2 1

Regarding the performance. It is a bit slower than a list comprehension.

X = np.zeros((100, 100, 100))

%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop

%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop

If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords attribute of the flat iterator.

a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop

How can I conditionally import an ES6 module?

No, you can't!

However, having bumped into that issue should make you rethink on how you organize your code.

Before ES6 modules, we had CommonJS modules which used the require() syntax. These modules were "dynamic", meaning that we could import new modules based on conditions in our code. - source: https://bitsofco.de/what-is-tree-shaking/

I guess one of the reasons they dropped that support on ES6 onward is the fact that compiling it would be very difficult or impossible.

What's the "Content-Length" field in HTTP header?

From this page

The most common use of POST, by far, is to submit HTML form data to CGI scripts. In this case, the Content-Type: header is usually application/x-www-form-urlencoded, and the Content-Length: header gives the length of the URL-encoded form data (here's a note on URL-encoding). The CGI script receives the message body through STDIN, and decodes it. Here's a typical form submission, using POST:

POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

Finding Android SDK on Mac and adding to PATH

AndroidStudioFrontScreenI simply double clicked the Android dmg install file that I saved on the hard drive and when the initial screen came up I dragged the icon for Android Studio into the Applications folder, now I know where it is!!! Also when you run it, be sure to right click the Android Studio while on the Dock and select "Options" -> "Keep on Dock". Everything else works. Dr. Roger Webster

How to fill a Javascript object literal with many static key/value pairs efficiently?

Give this a try:

var map = {"aaa": "rrr", "bbb": "ppp"};

Update multiple rows in same query using PostgreSQL

I don't think the accepted answer is entirely correct. It is order dependent. Here is an example that will not work correctly with an approach from the answer.

create table xxx (
    id varchar(64),
    is_enabled boolean
);

insert into xxx (id, is_enabled) values ('1',true);
insert into xxx (id, is_enabled) values ('2',true);
insert into xxx (id, is_enabled) values ('3',true);

UPDATE public.xxx AS pns
        SET is_enabled         = u.is_enabled
            FROM (
            VALUES
         (
            '3',
            false
         ,
            '1',
            true
         ,
            '2',
            false
         )
        ) AS u(id, is_enabled)
            WHERE u.id = pns.id;

select * from xxx;

So the question still stands, is there a way to do it in an order independent way?

---- after trying a few things this seems to be order independent

UPDATE public.xxx AS pns
        SET is_enabled         = u.is_enabled
            FROM (
            SELECT '3' as id, false as is_enabled UNION
            SELECT '1' as id, true as is_enabled UNION
            SELECT '2' as id, false as is_enabled
         ) as u
            WHERE u.id = pns.id;

Change the Theme in Jupyter Notebook?

Instead of installing a library inside Jupyter, I would recommend you use the 'Dark Reader' extension in Chrome (you can find 'Dark Reader' extension in other browsers, e.g. Firefox). You can play with it; filter the URL(s) you want to have dark theme, or even how define the Dark theme for yourself. Below are couple of examples:

enter image description here

enter image description here

I hope it helps.

Are duplicate keys allowed in the definition of binary search trees?

If your binary search tree is a red black tree, or you intend to any kind of "tree rotation" operations, duplicate nodes will cause problems. Imagine your tree rule is this:

left < root <= right

Now imagine a simple tree whose root is 5, left child is nil, and right child is 5. If you do a left rotation on the root you end up with a 5 in the left child and a 5 in the root with the right child being nil. Now something in the left tree is equal to the root, but your rule above assumed left < root.

I spent hours trying to figure out why my red/black trees would occasionally traverse out of order, the problem was what I described above. Hopefully somebody reads this and saves themselves hours of debugging in the future!

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

It was on Chrome for Android in my case. All the static files served from a CDN with a CNAME that's SSL encrypted were not showing up. On Chrome desktop, it all showed fine.

Broken SSL cert

When I properly added the certs in ca_bundle the files displayed correctly.

Chrome for Android takes encryption seriously unlike Desktop. I hope this saves you time and stress

Global variables in R

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

How to use the priority queue STL for objects?

This piece of code may help..

#include <bits/stdc++.h>
using namespace std;    

class node{
public:
    int age;
    string name;
    node(int a, string b){
        age = a;
        name = b;
    }
};

bool operator<(const node& a, const node& b) {

    node temp1=a,temp2=b;
    if(a.age != b.age)
        return a.age > b.age;
    else{
        return temp1.name.append(temp2.name) > temp2.name.append(temp1.name);
    }
}

int main(){
    priority_queue<node> pq;
    node b(23,"prashantandsoon..");
    node a(22,"prashant");
    node c(22,"prashantonly");
    pq.push(b);
    pq.push(a);
    pq.push(c);

    int size = pq.size();
    for (int i = 0; i < size; ++i)
    {
        cout<<pq.top().age<<" "<<pq.top().name<<"\n";
        pq.pop();
    }
}

Output:

22 prashantonly
22 prashant
23 prashantandsoon..

Lists in ConfigParser

Only primitive types are supported for serialization by config parser. I would use JSON or YAML for that kind of requirement.

How to stop an app on Heroku?

Go to your dashboard on heroku. Select the app. There is a dynos section. Just pull the sliders for the dynos down, (a decrease in dynos is to the left), to the number of dynos you want to be running. The slider goes to 0. Then save your changes. Boom.

According to the comment below: there is a pencil icon that needs to be clicked to accomplish this. I have not checked - but am putting it here in case it helps.

How do I determine the size of an object in Python?

Having run into this problem many times myself, I wrote up a small function (inspired by @aaron-hall's answer) & tests that does what I would have expected sys.getsizeof to do:

https://github.com/bosswissam/pysize

If you're interested in the backstory, here it is

EDIT: Attaching the code below for easy reference. To see the most up-to-date code, please check the github link.

    import sys

    def get_size(obj, seen=None):
        """Recursively finds size of objects"""
        size = sys.getsizeof(obj)
        if seen is None:
            seen = set()
        obj_id = id(obj)
        if obj_id in seen:
            return 0
        # Important mark as seen *before* entering recursion to gracefully handle
        # self-referential objects
        seen.add(obj_id)
        if isinstance(obj, dict):
            size += sum([get_size(v, seen) for v in obj.values()])
            size += sum([get_size(k, seen) for k in obj.keys()])
        elif hasattr(obj, '__dict__'):
            size += get_size(obj.__dict__, seen)
        elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
            size += sum([get_size(i, seen) for i in obj])
        return size

How to fill in proxy information in cntlm config file?

Just to add , if you are performing a "pip" operation , you might need to add and additional "--proxy=localhost:port_number"

e.g pip install --proxy=localhost:3128 matplotlib

Visit this link to see full details.

How can I display a tooltip on an HTML "option" tag?

I don't believe that you can achieve this functionality with standard <select> element.

What i would suggest is to use such way.

http://filamentgroup.com/lab/jquery_ipod_style_and_flyout_menus/

The basic version of it won't take too much space and you can easily bind mouseover events to sub items to show a nice tooltip.

Hope this helps, Sinan.

Strip off URL parameter with PHP

Here is the actual code for what's described above as the "the safest 'correct' method"...

function reduce_query($uri = '') {
    $kill_params = array('gclid');

    $uri_array = parse_url($uri);
    if (isset($uri_array['query'])) {
        // Do the chopping.
        $params = array();
        foreach (explode('&', $uri_array['query']) as $param) {
          $item = explode('=', $param);
          if (!in_array($item[0], $kill_params)) {
            $params[$item[0]] = isset($item[1]) ? $item[1] : '';
          }
        }
        // Sort the parameter array to maximize cache hits.
        ksort($params);
        // Build new URL (no hosts, domains, or fragments involved).
        $new_uri = '';
        if ($uri_array['path']) {
          $new_uri = $uri_array['path'];
        }
        if (count($params) > 0) {
          // Wish there was a more elegant option.
          $new_uri .= '?' . urldecode(http_build_query($params));
        }
        return $new_uri;
    }
    return $uri;
}

$_SERVER['REQUEST_URI'] = reduce_query($_SERVER['REQUEST_URI']);

However, since this will likely exist prior to the bootstrap of your application, you should probably put it into an anonymous function. Like this...

call_user_func(function($uri) {
    $kill_params = array('gclid');

    $uri_array = parse_url($uri);
    if (isset($uri_array['query'])) {
        // Do the chopping.
        $params = array();
        foreach (explode('&', $uri_array['query']) as $param) {
          $item = explode('=', $param);
          if (!in_array($item[0], $kill_params)) {
            $params[$item[0]] = isset($item[1]) ? $item[1] : '';
          }
        }
        // Sort the parameter array to maximize cache hits.
        ksort($params);
        // Build new URL (no hosts, domains, or fragments involved).
        $new_uri = '';
        if ($uri_array['path']) {
          $new_uri = $uri_array['path'];
        }
        if (count($params) > 0) {
          // Wish there was a more elegant option.
          $new_uri .= '?' . urldecode(http_build_query($params));
        }
        // Update server variable.
        $_SERVER['REQUEST_URI'] = $new_uri;

    }
}, $_SERVER['REQUEST_URI']);

NOTE: Updated with urldecode() to avoid double encoding via http_build_query() function. NOTE: Updated with ksort() to allow params with no value without an error.

How to disable spring security for particular url

If you want to ignore multiple API endpoints you can use as follow:

 @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests() 
            .antMatchers("/api/v1/**").authenticated()
            .antMatchers("api/v1/authenticate**").permitAll()
            .antMatchers("**").permitAll()
            .and().exceptionHandling().and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

Can you require two form fields to match with HTML5?

As has been mentioned in other answers, there is no pure HTML5 way to do this.

If you are already using JQuery, then this should do what you need:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#ourForm').submit(function(e){_x000D_
      var form = this;_x000D_
      e.preventDefault();_x000D_
      // Check Passwords are the same_x000D_
      if( $('#pass1').val()==$('#pass2').val() ) {_x000D_
          // Submit Form_x000D_
          alert('Passwords Match, submitting form');_x000D_
          form.submit();_x000D_
      } else {_x000D_
          // Complain bitterly_x000D_
          alert('Password Mismatch');_x000D_
          return false;_x000D_
      }_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="ourForm">_x000D_
    <input type="password" name="password" id="pass1" placeholder="Password" required>_x000D_
    <input type="password" name="password" id="pass2" placeholder="Repeat Password" required>_x000D_
    <input type="submit" value="Go">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to uninstall mini conda? python

In order to uninstall miniconda, simply remove the miniconda folder,

rm -r ~/miniconda/

As for avoiding conflicts between different Python environments, you can use virtual environments. In particular, with Miniconda, the following workflow could be used,

$ wget https://repo.continuum.io/miniconda/Miniconda3-3.7.0-Linux-x86_64.sh -O ~/miniconda.sh
$ bash miniconda
$ conda env remove --yes -n new_env    # remove the environement new_env if it exists (optional)
$ conda create --yes -n new_env pip numpy pandas scipy matplotlib scikit-learn nltk ipython-notebook seaborn python=2
$ activate new_env
$ # pip install modules if needed, run python scripts, etc
  # everything will be installed in the new_env
  # located in ~/miniconda/envs/new_env
$ deactivate

Blank HTML SELECT without blank item in dropdown list

You can try this snippet

$("#your-id")[0].selectedIndex = -1

It worked for me.

How to get a list of installed android applications and pick one to run

I had a requirement to filter out the system apps which user do not really use(eg. "com.qualcomm.service", "update services", etc). Ultimately I added another condition to filter down the app list. I just checked whether the app has 'launcher intent'.

So, the resultant code looks like...

PackageManager pm = getPackageManager();
        List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_GIDS);

        for (ApplicationInfo app : apps) {
            if(pm.getLaunchIntentForPackage(app.packageName) != null) {
                // apps with launcher intent
                if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                    // updated system apps

                } else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                    // system apps

                } else {
                    // user installed apps

                }
                appsList.add(app);
            }

        }

How to parse an RSS feed using JavaScript?

For anyone else reading this (in 2019 onwards) unfortunately most JS RSS reading implementations don't now work. Firstly Google API has shut down so this is no longer an option and because of the CORS security policy you generally cannot now request RSS feeds cross-domains.

Using the example on https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options (2015) I get the following:

Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This is correct and is a security precaution by the end website but does now mean that the answers above are unlikely to work.

My workaround will probably be to parse the RSS feed through PHP and allow the javascript to access my PHP rather than trying to access the end-destination feed itself.

CSS '>' selector; what is it?

It is the CSS child selector. Example:

div > p selects all paragraphs that are direct children of div.

See this

How to break lines in PowerShell?

You can also just use:

Write-Host "";

Or, to put it in terms of your specific question:

$str = ""
foreach($line in $file){
  if($line -Match $review){ #Special condition
    $str += Write-Host ""
    $str += ANSWER #looking for ANSWER
  }
  #code.....
}

Difference between abstract class and interface in Python

For completeness, we should mention PEP3119 where ABC was introduced and compared with interfaces, and original Talin's comment.

The abstract class is not perfect interface:

  • belongs to the inheritance hierarchy
  • is mutable

But if you consider writing it your own way:

def some_function(self):
     raise NotImplementedError()

interface = type(
    'your_interface', (object,),
    {'extra_func': some_function,
     '__slots__': ['extra_func', ...]
     ...
     '__instancecheck__': your_instance_checker,
     '__subclasscheck__': your_subclass_checker
     ...
    }
)

ok, rather as a class
or as a metaclass
and fighting with python to achieve the immutable object
and doing refactoring
...

you'll quite fast realize that you're inventing the wheel to eventually achieve abc.ABCMeta

abc.ABCMeta was proposed as a useful addition of the missing interface functionality, and that's fair enough in a language like python.

Certainly, it was able to be enhanced better whilst writing version 3, and adding new syntax and immutable interface concept ...

Conclusion:

The abc.ABCMeta IS "pythonic" interface in python

MySQL stored procedure return value

You have done the stored procedure correctly but I think you have not referenced the valido variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido

This statement SELECT valido; should be like this SELECT @valido;

Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido

I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.

Double array initialization in Java

If you can accept Double Objects than this post is helpful: Initialization of an ArrayList in one line

List<Double> y = Arrays.asList(null, 1.0, 2.0);
Double x = y.get(1);

how to set imageview src?

To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.

If you have image in the form of bitmap then use

imageview.setImageBitmap(bm);

If you have image in the form of drawable then use

imageview.setImageDrawable(drawable);

If you have image in your resource example if image is present in drawable folder then use

imageview.setImageResource(R.drawable.image);

If you have path of image then use

imageview.setImageURI(Uri.parse("pathofimage"));

How can I reset eclipse to default settings?

Delete the .metadata folder in your workspace.

How do I give ASP.NET permission to write to a folder in Windows 7?

Giving write permissions to all IIS_USRS group is a bad idea from the security point of view. You dont need to do that and you can go with giving permissions only to system user running the application pool.

If you are using II7 (and I guess you do) do the following.

  1. Open IIS7
  2. Select Website for which you need to modify permissions
  3. Go to Basic Settings and see which application pool you're using.
  4. Go to Application pools and find application pool from #3
  5. Find system account used for running this application pool (Identity column)
  6. Navigate to your storage folder in IIS, select it and click on Edit Permissions (under Actions sub menu on the right)
  7. Open security tab and add needed permissions only for user you identified in #3

Note #1: if you see ApplicationPoolIdentity in #3 you need to reference this system user like this IIS AppPool{application_pool_name} . For example IIS AppPool\DefaultAppPool

Note #2: when adding this user make sure to set correct locations in the Select Users or Groups dialog. This needs to be set to local machine because this is local account.

How to determine an object's class?

Any use of any of the methods suggested is considered a code smell which is based in a bad OO design.

If your design is good, you should not find yourself needing to use getClass() or instanceof.

Any of the suggested methods will do, but just something to keep in mind, design-wise.

Why would an Enum implement an Interface?

Another posibility:

public enum ConditionsToBeSatisfied implements Predicate<Number> {
    IS_NOT_NULL(Objects::nonNull, "Item is null"),
    IS_NOT_AN_INTEGER(item -> item instanceof Integer, "Item is not an integer"),
    IS_POSITIVE(item -> item instanceof Integer && (Integer) item > 0, "Item is negative");

    private final Predicate<Number> predicate;
    private final String notSatisfiedLogMessage;

    ConditionsToBeSatisfied(final Predicate<Number> predicate, final String notSatisfiedLogMessage) {
        this.predicate = predicate;
        this.notSatisfiedLogMessage = notSatisfiedLogMessage;
    }

    @Override
    public boolean test(final Number item) {
        final boolean isNotValid = predicate.negate().test(item);

        if (isNotValid) {
            log.warn("Invalid {}. Cause: {}", item, notSatisfiedLogMessage);
        }

        return predicate.test(item);
    }
}

and using:

Predicate<Number> p = IS_NOT_NULL.and(IS_NOT_AN_INTEGER).and(IS_POSITIVE);

bash echo number of lines of file given in a bash variable without the file name

wc can't get the filename if you don't give it one.

wc -l < "$JAVA_TAGS_FILE"

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

My problems solved by remove all the runtime part

<runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>

With CSS, how do I make an image span the full width of the page as a background image?

You set the CSS to :

#elementID {
    background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
    height: 200px;
}

It centers the image, but does not scale it.

FIDDLE

In newer browsers you can use the background-size property and do:

#elementID {
    height: 200px; 
    width: 100%;
    background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
    background-size: 100% 100%;
}

FIDDLE

Other than that, a regular image is one way to do it, but then it's not really a background image.

?

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

I had this same error message, turns out it was because I didn't have mixed mode auth enabled. I was on Windows Auth only. This is common in default MSSQL deployments for vSphere, and becomes an issue when upgrading to vSphere 5.1.

To change to mixed mode auth you can follow the instructions at http://support.webecs.com/kb/a374/how-do-i-configure-sql-server-express-to-enable-mixed-mode-authentication.aspx.

Get a list of resources from classpath directory

With Spring it's easy. Be it a file, or folder, or even multiple files, there are chances, you can do it via injection.

This example demonstrates the injection of multiple files located in x/y/z folder.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

@Service
public class StackoverflowService {
    @Value("classpath:x/y/z/*")
    private Resource[] resources;

    public List<String> getResourceNames() {
        return Arrays.stream(resources)
                .map(Resource::getFilename)
                .collect(Collectors.toList());
    }
}

It does work for resources in the filesystem as well as in JARs.

Select all occurrences of selected word in VSCode

on Mac:

select all matches: Command + Shift + L

but if you just want to select another match up coming next: Command + D

React native ERROR Packager can't listen on port 8081

Check if there is already a Node server running on your machine and then close it.

SQL Server: the maximum number of rows in table

Partition the table monthly.That is the best way to handle tables with large daily influx ,be it oracle or MSSQL.

HTML entity for the middle dot

There's actually seven variants of this:

    char   description          unicode   html       html entity    utf-8

    ·      Middle Dot           U+00B7    &#183;     &middot;       C2 B7
    ·      Greek Ano Teleia     U+0387    &#903;                    CE 87
    •      Bullet               U+2022    &#8226;    &bull;         E2 80 A2
    ‧      Hyphenation Point    U+2027    &#8321;                   E2 80 A7
    ∙      Bullet Operator      U+2219    &#8729;                   E2 88 99
    ●      Black Circle         U+25CF    &#9679;                   E2 97 8F
    ⬤     Black Large Circle   U+2B24    &#11044;                  E2 AC A4

Depending on your viewing application or font, the Bullet Operator may seem very similar to either the Middle Dot or the Bullet.

Using Cookie in Asp.Net Mvc 4

We are using Response.SetCookie() for update the old one cookies and Response.Cookies.Add() are use to add the new cookies. Here below code CompanyId is update in old cookie[OldCookieName].

HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.

Text Editor which shows \r\n?

If you have Mathematica, you can try with this command:

ReadList["filename.txt", Record, RecordSeparators -> {}] // InputForm

That will show all the /r and /n

What is Type-safe?

Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.

In practice, this means that 7 (an integer type) is different from "7" (a quoted character of string type).

PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) "7" to an (integer) 7 if you try to add "7" + 3, although sometimes you have to do this explicitly (and Javascript uses the "+" character for concatenation).

C/C++/Java will not understand that, or will concatenate the result into "73" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.

Type-safety is very useful. The solution to the above "7" + 3 would be to type cast (int) "7" + 3 (equals 10).

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

C++ Structure Initialization

You can just initialize via a constructor:

struct address {
  address() : city("Hamilton"), prov("Ontario") {}
  int street_no;
  char *street_name;
  char *city;
  char *prov;
  char *postal_code;
};

How can I set the form action through JavaScript?

document.forms[0].action="http://..."

...assuming it is the first form on the page.

jQuery change input text value

Just adding to Jason's answer, the . selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.

e.g.

$('element[attr=val]')

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

To find files in immediate subdirectories:

configfiles = glob.glob(r'C:\Users\sam\Desktop\*\*.txt')

For a recursive version that traverse all subdirectories, you could use ** and pass recursive=True since Python 3.5:

configfiles = glob.glob(r'C:\Users\sam\Desktop\**\*.txt', recursive=True)

Both function calls return lists. You could use glob.iglob() to return paths one by one. Or use pathlib:

from pathlib import Path

path = Path(r'C:\Users\sam\Desktop')
txt_files_only_subdirs = path.glob('*/*.txt')
txt_files_all_recursively = path.rglob('*.txt') # including the current dir

Both methods return iterators (you can get paths one by one).

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

Another "finally" block emulation using C++11 lambda functions

template <typename TCode, typename TFinallyCode>
inline void with_finally(const TCode &code, const TFinallyCode &finally_code)
{
    try
    {
        code();
    }
    catch (...)
    {
        try
        {
            finally_code();
        }
        catch (...) // Maybe stupid check that finally_code mustn't throw.
        {
            std::terminate();
        }
        throw;
    }
    finally_code();
}

Let's hope the compiler will optimize the code above.

Now we can write code like this:

with_finally(
    [&]()
    {
        try
        {
            // Doing some stuff that may throw an exception
        }
        catch (const exception1 &)
        {
            // Handling first class of exceptions
        }
        catch (const exception2 &)
        {
            // Handling another class of exceptions
        }
        // Some classes of exceptions can be still unhandled
    },
    [&]() // finally
    {
        // This code will be executed in all three cases:
        //   1) exception was not thrown at all
        //   2) exception was handled by one of the "catch" blocks above
        //   3) exception was not handled by any of the "catch" block above
    }
);

If you wish you can wrap this idiom into "try - finally" macros:

// Please never throw exception below. It is needed to avoid a compilation error
// in the case when we use "begin_try ... finally" without any "catch" block.
class never_thrown_exception {};

#define begin_try    with_finally([&](){ try
#define finally      catch(never_thrown_exception){throw;} },[&]()
#define end_try      ) // sorry for "pascalish" style :(

Now "finally" block is available in C++11:

begin_try
{
    // A code that may throw
}
catch (const some_exception &)
{
    // Handling some exceptions
}
finally
{
    // A code that is always executed
}
end_try; // Sorry again for this ugly thing

Personally I don't like the "macro" version of "finally" idiom and would prefer to use pure "with_finally" function even though a syntax is more bulky in that case.

You can test the code above here: http://coliru.stacked-crooked.com/a/1d88f64cb27b3813

PS

If you need a finally block in your code, then scoped guards or ON_FINALLY/ON_EXCEPTION macros will probably better fit your needs.

Here is short example of usage ON_FINALLY/ON_EXCEPTION:

void function(std::vector<const char*> &vector)
{
    int *arr1 = (int*)malloc(800*sizeof(int));
    if (!arr1) { throw "cannot malloc arr1"; }
    ON_FINALLY({ free(arr1); });

    int *arr2 = (int*)malloc(900*sizeof(int));
    if (!arr2) { throw "cannot malloc arr2"; }
    ON_FINALLY({ free(arr2); });

    vector.push_back("good");
    ON_EXCEPTION({ vector.pop_back(); });

    ...

Python - Get Yesterday's date as a string in YYYY-MM-DD format

Calling .isoformat() on a date object will give you YYYY-MM-DD

from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()

Insert image after each list item

The easier way to do it is just:

ul li:after {
    content: url('../images/small_triangle.png');
}

Correct file permissions for WordPress

I can't tell you whether or not this is correct, but I am using a Bitnami image over Google Compute App Engine. I has having problems with plugins and migration, and after further messing things up by chmod'ing permissions, I found these three lines which solved all my problems. Not sure if it's the proper way but worked for me.

sudo chown -R bitnami:daemon /opt/bitnami/apps/wordpress/htdocs/
sudo find /opt/bitnami/apps/wordpress/htdocs/ -type f -exec chmod 664 {} \;
sudo find /opt/bitnami/apps/wordpress/htdocs/ -type d -exec chmod 775 {} \;

NHibernate.MappingException: No persister for: XYZ

I my case I fetched an entity without await:

var company = _unitOfWork.Session.GetAsync<Company>(id);

and then I tried to delete it:

await _unitOfWork.Session.DeleteAsync(company);

I could not decipher the error message that I'm deleting a Task<Company> instead of Company:

MappingException: No persister for: System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null],[NHibernate.Impl.SessionImpl+d__54`1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]], NHibernate, Version=5.3.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4]]

Disable submit button ONLY after submit

  $(function(){

    $("input[type='submit']").click(function () {
        $(this).attr("disabled", true);   
     });
  });

thant's it.

How can I check whether a radio button is selected with JavaScript?

Try

[...myForm.sex].filter(r=>r.checked)[0].value

_x000D_
_x000D_
function check() {
  let v= ([...myForm.sex].filter(r=>r.checked)[0] || {}).value ;
  console.log(v);
}
_x000D_
<form id="myForm">
  <input name="sex" type="radio" value="men"> Men
  <input name="sex" type="radio" value="woman"> Woman
</form>
<br><button onClick="check()">Check</button>
_x000D_
_x000D_
_x000D_

Import XXX cannot be resolved for Java SE standard classes

This is an issue relating JRE.In my case (eclipse Luna with Maven plugin, JDK 7) I solved this by making following change in pom.xml and then Maven Update Project.

from:

 <configuration>
        <source>1.8</source>
        <target>1.8</target>
</configuration>

to:

 <configuration>
        <source>1.7</source>
        <target>1.7</target>
</configuration>

Screenshot showing problem in JRE: enter image description here

How to click a href link using Selenium

You can use this method:

For the links if you use linkText(); it is more effective than the any other locator.

driver.findElement(By.linkText("App Configuration")).click();

How can I directly view blobs in MySQL Workbench

Perform three steps:

  1. Go to "WorkBench Preferences" --> Choose "SQL Editor" Under "Query Results": check "Treat BINARY/VARBINARY as nonbinary character string"

  2. Restart MySQL WorkBench.

  3. Now select SELECT SUBSTRING(BLOB<COLUMN_NAME>,1,2500) FROM <Table_name>;

How to split a number into individual digits in c#?

Substring and Join methods are usable for this statement.

string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;

   for (int i = 0; i < no.Length; i++)
   {
     numberArray[i] = no.Substring(counter, 1); // 1 is split length
     counter++;
   }

Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5

How do I include negative decimal numbers in this regular expression?

I don't know why you need that first [0-9].

Try:

^-?\d*(\.\d+)?$

Update

If you want to be sure that you'll have a digit on the ones place, then use

^-?\d+(\.\d+)?$

How to disable Django's CSRF validation?

CSRF can be enforced at the view level, which can't be disabled globally.

In some cases this is a pain, but um, "it's for security". Gotta retain those AAA ratings.

https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps

Start an external application from a Google Chrome Extension?

Question has a good pagerank on google, so for anyone who's looking for answer to this question this might be helpful.

There is an extension in google chrome marketspace to do exactly that: https://chrome.google.com/webstore/detail/hccmhjmmfdfncbfpogafcbpaebclgjcp

What is the difference between #include <filename> and #include "filename"?

The simple general rule is to use angled brackets to include header files that come with the compiler. Use double quotes to include any other header files. Most compilers do it this way.

1.9 — Header files explains in more detail about pre-processor directives. If you are a novice programmer, that page should help you understand all that. I learned it from here, and I have been following it at work.

MongoDB: Combine data from multiple collections into one..how?

You've to do that in your application layer. If you're using an ORM, it could use annotations (or something similar) to pull references that exist in other collections. I only have worked with Morphia, and the @Reference annotation fetches the referenced entity when queried, so I am able to avoid doing it myself in the code.

Is there 'byte' data type in C++?

Using C++11 there is a nice version for a manually defined byte type:

enum class byte : std::uint8_t {};

That's at least what the GSL does.

Starting with C++17 (almost) this very version is defined in the standard as std::byte (thanks Neil Macintosh for both).

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

Should I always use a parallel stream when possible?

A parallel stream has a much higher overhead compared to a sequential one. Coordinating the threads takes a significant amount of time. I would use sequential streams by default and only consider parallel ones if

  • I have a massive amount of items to process (or the processing of each item takes time and is parallelizable)

  • I have a performance problem in the first place

  • I don't already run the process in a multi-thread environment (for example: in a web container, if I already have many requests to process in parallel, adding an additional layer of parallelism inside each request could have more negative than positive effects)

In your example, the performance will anyway be driven by the synchronized access to System.out.println(), and making this process parallel will have no effect, or even a negative one.

Moreover, remember that parallel streams don't magically solve all the synchronization problems. If a shared resource is used by the predicates and functions used in the process, you'll have to make sure that everything is thread-safe. In particular, side effects are things you really have to worry about if you go parallel.

In any case, measure, don't guess! Only a measurement will tell you if the parallelism is worth it or not.

Check if an array contains duplicate values

Wrote this to initialize a new array of length uniqueIndexCount. It's presented here minus unrelated logic.

    public Vector3[] StandardizeVertices(Vector3[] dimensions, int standard)
    {
        //determine the number of unique dimension vectors
        int uniqueIndexCount = 0;
        for (int a=0; a < dimensions.Length; ++a)
        {
            int duplicateIndexCount = 0;
            for (int b = a; b < dimensions.Length; ++b)
            {
                if(a!=b && dimensions[a] == dimensions[b])
                {
                    duplicateIndexCount++;
                }
            }
            if (duplicateIndexCount == 0)
            {
                uniqueIndexCount++;
            }
        }
        Debug.Log("uniqueIndexCount: "+uniqueIndexCount);
        return dimensions;
    }

How to specify the port an ASP.NET Core application is hosted on?

You can insert Kestrel section in asp.net core 2.1+ appsettings.json file.

  "Kestrel": {
    "EndPoints": {
      "Http": {
        "Url": "http://0.0.0.0:5002"
      }
    }
  },

html button to send email

@user544079

Even though it is very old and irrelevant now, I am replying to help people like me! it should be like this:

<form method="post" action="mailto:$emailID?subject=$MySubject &message= $MyMessageText">

Here $emailID, $MySubject, $MyMessageText are variables which you assign from a FORM or a DATABASE Table or just you can assign values in your code itself. Alternatively you can put the code like this (normally it is not used):

<form method="post" action="mailto:[email protected]?subject=New Registration Alert &message= New Registration requires your approval">

Check file size before upload

Client side Upload Canceling

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

PHP Validation

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES array to find out the upload size. (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs)

upload.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

Java ArrayList clear() function

ArrayList.clear(From Java Doc):

Removes all of the elements from this list. The list will be empty after this call returns

Google Maps API 3 - Custom marker color for default (dot) marker

You can use color code also.

 const marker: Marker = this.map.addMarkerSync({
    icon: '#008000',
    animation: 'DROP',
    position: {lat: 39.0492127, lng: -111.1435662},
    map: this.map,
 });

Merge up to a specific commit

Recently we had a similar problem and had to solve it in a different way. We had to merge two branches up to two commits, which were not the heads of either branches:

branch A: A1 -> A2 -> A3 -> A4
branch B: B1 -> B2 -> B3 -> B4
branch C: C1 -> A2 -> B3 -> C2

For example, we had to merge branch A up to A2 and branch B up to B3. But branch C had cherry-picks from A and B. When using the SHA of A2 and B3 it looked like there was confusion because of the local branch C which had the same SHA.

To avoid any kind of ambiguity we removed branch C locally, and then created a branch AA starting from commit A2:

git co A
git co SHA-of-A2
git co -b AA

Then we created a branch BB from commit B3:

git co B
git co SHA-of-B3
git co -b BB

At that point we merged the two branches AA and BB. By removing branch C and then referencing the branches instead of the commits it worked.

It's not clear to me how much of this was superstition or what actually made it work, but this "long approach" may be helpful.

How to tell bash that the line continues on the next line

\ does the job. @Guillaume's answer and @George's comment clearly answer this question. Here I explains why The backslash has to be the very last character before the end of line character. Consider this command:

   mysql -uroot \
   -hlocalhost      

If there is a space after \, the line continuation will not work. The reason is that \ removes the special meaning for the next character which is a space not the invisible line feed character. The line feed character is after the space not \ in this example.

Android ListView Text Color

never use getApplicationContext(). Just use your Activity as the Context. See if that helps.

Please check here: CommonsWare answers

How to disable scrolling temporarily?

The scroll event cannot be canceled. But you can do it by canceling these interaction events:
Mouse & Touch scroll and Buttons associated with scrolling.

[Working demo]

// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {37: 1, 38: 1, 39: 1, 40: 1};

function preventDefault(e) {
  e.preventDefault();
}

function preventDefaultForScrollKeys(e) {
  if (keys[e.keyCode]) {
    preventDefault(e);
    return false;
  }
}

// modern Chrome requires { passive: false } when adding event
var supportsPassive = false;
try {
  window.addEventListener("test", null, Object.defineProperty({}, 'passive', {
    get: function () { supportsPassive = true; } 
  }));
} catch(e) {}

var wheelOpt = supportsPassive ? { passive: false } : false;
var wheelEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';

// call this to Disable
function disableScroll() {
  window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF
  window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop
  window.addEventListener('touchmove', preventDefault, wheelOpt); // mobile
  window.addEventListener('keydown', preventDefaultForScrollKeys, false);
}

// call this to Enable
function enableScroll() {
  window.removeEventListener('DOMMouseScroll', preventDefault, false);
  window.removeEventListener(wheelEvent, preventDefault, wheelOpt); 
  window.removeEventListener('touchmove', preventDefault, wheelOpt);
  window.removeEventListener('keydown', preventDefaultForScrollKeys, false);
}

UPDATE: fixed Chrome desktop and modern mobile browsers with passive listeners

XPath using starts-with function

Use:

//REVENUE_YEAR[starts-with(.,'2552')]/../REGION/text() 

rake assets:precompile RAILS_ENV=production not working as required

Have you added this gem to your gemfile?

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

move that gem out of assets group and then run bundle again, I hope that would help!

Select from where field not equal to Mysql Php

You can use like

NOT columnA = 'x'

Or

columnA != 'x'

Or

columnA <> 'x'

And like Jeffly Bake's query, for including null values, you don't have to write like

(NOT columnA = 'x' OR columnA IS NULL)

You can make it simple by

Not columnA <=> 'x'

<=> is the Null Safe equal to Operator, which includes results from even null values.

Show/hide div if checkbox selected

change the input boxes like

<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox

and js code as

function showMe (box) {

    var chboxs = document.getElementsByName("c1");
    var vis = "none";
    for(var i=0;i<chboxs.length;i++) { 
        if(chboxs[i].checked){
         vis = "block";
            break;
        }
    }
    document.getElementById(box).style.display = vis;


}

here is a demo fiddle

How do I detect if software keyboard is visible on Android Device or not?

There is a direct method to find this out. And, it does not require the layout changes.
So it works in immersive fullscreen mode, too.
But, unfortunately, it does not work on all devices. So you have to test it with your device(s).

The trick is that you try to hide or show the soft keyboard and capture the result of that try.
If it works correct then the keyboard is not really shown or hidden. We just ask for the state.

To stay up-to-date, you simply repeat this operation, e.g. every 200 milliseconds, using a Handler.

The implementation below does just a single check.
If you do multiple checks, then you should enable all the (_keyboardVisible) tests.

public interface OnKeyboardShowHide
{
    void    onShowKeyboard( Object param );
    void    onHideKeyboard( Object param );
}

private static Handler      _keyboardHandler    = new Handler();
private boolean             _keyboardVisible    = false;
private OnKeyboardShowHide  _keyboardCallback;
private Object              _keyboardCallbackParam;

public void start( OnKeyboardShowHide callback, Object callbackParam )
{
    _keyboardCallback      = callback;
    _keyboardCallbackParam = callbackParam;
    //
    View view = getCurrentFocus();
    if (view != null)
    {
        InputMethodManager imm = (InputMethodManager) getSystemService( Activity.INPUT_METHOD_SERVICE );
        imm.hideSoftInputFromWindow( view.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY, _keyboardResultReceiver );
        imm.showSoftInput( view, InputMethodManager.SHOW_IMPLICIT, _keyboardResultReceiver );
    }
    else // if (_keyboardVisible)
    {
        _keyboardVisible = false;
        _keyboardCallback.onHideKeyboard( _keyboardCallbackParam );
    }
}

private ResultReceiver      _keyboardResultReceiver = new ResultReceiver( _keyboardHandler )
{
    @Override
    protected void onReceiveResult( int resultCode, Bundle resultData )
    {
        switch (resultCode)
        {
            case InputMethodManager.RESULT_SHOWN :
            case InputMethodManager.RESULT_UNCHANGED_SHOWN :
                // if (!_keyboardVisible)
                {
                    _keyboardVisible = true;
                    _keyboardCallback.onShowKeyboard( _keyboardCallbackParam );
                }
                break;
            case InputMethodManager.RESULT_HIDDEN :
            case InputMethodManager.RESULT_UNCHANGED_HIDDEN :
                // if (_keyboardVisible)
                {
                    _keyboardVisible = false;
                    _keyboardCallback.onHideKeyboard( _keyboardCallbackParam );
                }
                break;
        }
    }
};

How to check if a string starts with one of several prefixes?

if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || newStr4.startsWith("Weds") .. etc)

You need to include the whole str.startsWith(otherStr) for each item, since || only works with boolean expressions (true or false).

There are other options if you have a lot of things to check, like regular expressions, but they tend to be slower and more complicated regular expressions are generally harder to read.

An example regular expression for detecting day name abbreviations would be:

if(Pattern.matches("Mon|Tues|Wed|Thurs|Fri", stringToCheck)) {

ES6 Class Multiple inheritance

This isn't really possible with the way prototypical inheritance works. Lets take a look at how inherited props work in js

var parent = {a: function() { console.log('ay'); }};
var child = Object.create(parent);
child.a() // first look in child instance, nope let's go to it's prototype
          // then look in parent, found! return the method

let's see what happens when you access a prop that doesn't exist:

child.b; // first look in child instance, nope let's go to it's prototype
         // then look in parent, nope let's go to it's prototype
         // then look in Object.prototype, nope let's go to it's prototype
         // then look at null, give up and return undefined

You can use mixins to get some of that functionality but you won't get late binding:

var a = {x: '1'};
var b = {y: '2'};
var c = createWithMixin([a, b]);
c.x; // 1
c.y; // 2
b.z = 3;
c.z; // undefined

vs

var a = {x: 1}
var o = Object.create(a);
o.x; // 1
a.y = 2;
o.y; // 2

How do I change a PictureBox's image?

You can use the ImageLocation property of pictureBox1:

pictureBox1.ImageLocation = @"C:\Users\MSI\Desktop\MYAPP\Slider\Slider\bt1.jpg";

Cannot use string offset as an array in php

I was able to reproduce this once I upgraded to PHP 7. It breaks when you try to force array elements into a string.

$params = '';
foreach ($foo) {
  $index = 0;
  $params[$index]['keyName'] = $name . '.' . $fileExt;
}

After changing:

$params = '';

to:

$params = array();

I stopped getting the error. I found the solution in this bug report thread. I hope this helps.

JavaScriptSerializer.Deserialize - how to change field names

I took another try at it, using the DataContractJsonSerializer class. This solves it:

The code looks like this:

using System.Runtime.Serialization;

[DataContract]
public class DataObject
{
    [DataMember(Name = "user_id")]
    public int UserId { get; set; }

    [DataMember(Name = "detail_level")]
    public string DetailLevel { get; set; }
}

And the test is:

using System.Runtime.Serialization.Json;

[TestMethod]
public void DataObjectSimpleParseTest()
{
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DataObject));

        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(JsonData));
        DataObject dataObject = serializer.ReadObject(ms) as DataObject;

        Assert.IsNotNull(dataObject);
        Assert.AreEqual("low", dataObject.DetailLevel);
        Assert.AreEqual(1234, dataObject.UserId);
}

The only drawback is that I had to change DetailLevel from an enum to a string - if you keep the enum type in place, the DataContractJsonSerializer expects to read a numeric value and fails. See DataContractJsonSerializer and Enums for further details.

In my opinion this is quite poor, especially as JavaScriptSerializer handles it correctly. This is the exception that you get trying to parse a string into an enum:

System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type DataObject. The value 'low' cannot be parsed as the type 'Int64'. --->
System.Xml.XmlException: The value 'low' cannot be parsed as the type 'Int64'. --->  
System.FormatException: Input string was not in a correct format

And marking up the enum like this does not change this behaviour:

[DataContract]
public enum DetailLevel
{
    [EnumMember(Value = "low")]
    Low,
   ...
 }

This also seems to work in Silverlight.

How would I create a UIAlertView in Swift?

// Custom Class For UIAlertView

//MARK:- MODULES
import Foundation
import UIKit

//MARK:- CLASS
class Alert  : NSObject{

static let shared = Alert()

var okAction : AlertSuccess?
typealias AlertSuccess = (()->())?
var alert: UIAlertController?

/** show */
public func show(title : String?, message : String?, viewController : UIViewController?, okAction : AlertSuccess = nil) {

    let version : NSString = UIDevice.current.systemVersion as NSString
    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: title, message: message, preferredStyle:.alert)
        alert?.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) in

            if let okAction = okAction {
                okAction()
            }
        }))
        viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil);
    }
}

/** showWithCancelAndOk */
public func showWithCancelAndOk(title : String, okTitle : String, cancelTitle : String, message : String, viewController : UIViewController?, okAction : AlertSuccess = nil, cancelAction : AlertSuccess = nil) {
    let version:NSString = UIDevice.current.systemVersion as NSString;

    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: title, message: message, preferredStyle:.alert)

        alert?.addAction(UIAlertAction(title: cancelTitle, style: .default, handler: { (action: UIAlertAction) in

            if let cancelAction = cancelAction {
                cancelAction()
            }
        }))
        alert?.addAction(UIAlertAction(title: okTitle, style: .default, handler: { (action: UIAlertAction) in

            if let okAction = okAction {
                okAction()
            }
        }))
        viewController?.present(alert!, animated:true, completion:nil);
    }
}

/** showWithTimer */
public func showWithTimer(message : String?, viewController : UIViewController?) {

    let version : NSString = UIDevice.current.systemVersion as NSString
    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
        viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
        let when = DispatchTime.now() + 1
        DispatchQueue.main.asyncAfter(deadline: when){
            self.alert?.dismiss(animated: true, completion: nil)
        }
    }
}
}

Use:-

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self) //without ok action

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
                            //ok action
                        }) // with ok action

Alert.shared.show(title: "No Internet Connection", message: "The internet connection appers to be offline.", viewController: self, okAction: {
                            //ok action 
}, cancelAction: {
 //cancel action
}) //with cancel and ok action

Alert.shared.showWithTimer(message : "This is an alert with timer", viewController : self) //with timer

Center image horizontally within a div

A responsive way to center an image can be like this:

.center {
    display: block;
    margin: auto;
    max-width: 100%;
    max-height: 100%;
}

ASP.NET Core configuration for .NET Core console application

On .Net Core 3.1 we just need to do these:

static void Main(string[] args)
{
  var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
}

Using SeriLog will look like:

using Microsoft.Extensions.Configuration;
using Serilog;
using System;


namespace yournamespace
{
    class Program
    {

        static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
            Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();

            try
            {
                Log.Information("Starting Program.");
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Program terminated unexpectedly.");
                return;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
    }
}

And the Serilog appsetings.json section for generating one file daily will look like:

  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "C:\\Logs\\Program.json",
          "rollingInterval": "Day",
          "formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
        }
      }
    ]
  }

How to use timer in C?

Here's a solution I used (it needs #include <time.h>):

int msec = 0, trigger = 10; /* 10ms */
clock_t before = clock();

do {
  /*
   * Do something to busy the CPU just here while you drink a coffee
   * Be sure this code will not take more than `trigger` ms
   */

  clock_t difference = clock() - before;
  msec = difference * 1000 / CLOCKS_PER_SEC;
  iterations++;
} while ( msec < trigger );

printf("Time taken %d seconds %d milliseconds (%d iterations)\n",
  msec/1000, msec%1000, iterations);

ngModel cannot be used to register form controls with a parent formGroup directive

If component has more than 1 form, register all controls and forms

I needed to know why this was happening in a certain component and not in any other component.

The issue was that I had 2 forms in one component and the second form didn't yet have [formGroup] and wasn't registered yet since I was still building the forms.

I went ahead and completed writting both forms complete without leaving a input not registered which solve the issue.

How can I make a ComboBox non-editable in .NET?

Stay on your ComboBox and search the DropDropStyle property from the properties window and then choose DropDownList.

Foreign key referring to primary keys across multiple tables?

You can probably add two foreign key constraints (honestly: I've never tried it), but it'd then insist the parent row exist in both tables.

Instead you probably want to create a supertype for your two employee subtypes, and then point the foreign key there instead. (Assuming you have a good reason to split the two types of employees, of course).

                 employee       
employees_ce     ————————       employees_sn
————————————     type           ————————————
empid —————————> empid <——————— empid
name               /|\          name
                    |  
                    |  
      deductions    |  
      ——————————    |  
      empid ————————+  
      name

type in the employee table would be ce or sn.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

I followed @PabloG's steps as follows

  1. goto http://www.autohotkey.com/ - download autohotkey
  2. follow simple installation steps
  3. after installation create new *.ahk file as follows right click on desktop > new > Autohotkey Script > giveAnyFileName.ahk
  4. right click on this file > Edit
  5. copy paste autohotkey script given by @PabloG in his answer
  6. save and close
  7. double click on file to run
  8. Done now you should be able to use Ctrl+v for paste in command prompt

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

Change: case (divisor(T,round(math:sqrt(T))) > 500) of

To: case (divisor(T,round(math:sqrt(T))) > 1000) of

This will produce the correct answer for the Erlang multi-process example.

How to write some data to excel file(.xlsx)

Try this code

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
    //Start Excel and get Application object.
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;

    //Get a new workbook.
    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

    //Add table headers going cell by cell.
    oSheet.Cells[1, 1] = "First Name";
    oSheet.Cells[1, 2] = "Last Name";
    oSheet.Cells[1, 3] = "Full Name";
    oSheet.Cells[1, 4] = "Salary";

    //Format A1:D1 as bold, vertical alignment = center.
    oSheet.get_Range("A1", "D1").Font.Bold = true;
    oSheet.get_Range("A1", "D1").VerticalAlignment =
        Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

    // Create an array to multiple values at once.
    string[,] saNames = new string[5, 2];

    saNames[0, 0] = "John";
    saNames[0, 1] = "Smith";
    saNames[1, 0] = "Tom";

    saNames[4, 1] = "Johnson";

    //Fill A2:B6 with an array of values (First and Last Names).
    oSheet.get_Range("A2", "B6").Value2 = saNames;

    //Fill C2:C6 with a relative formula (=A2 & " " & B2).
    oRng = oSheet.get_Range("C2", "C6");
    oRng.Formula = "=A2 & \" \" & B2";

    //Fill D2:D6 with a formula(=RAND()*100000) and apply format.
    oRng = oSheet.get_Range("D2", "D6");
    oRng.Formula = "=RAND()*100000";
    oRng.NumberFormat = "$0.00";

    //AutoFit columns A:D.
    oRng = oSheet.get_Range("A1", "D1");
    oRng.EntireColumn.AutoFit();

    oXL.Visible = false;
    oXL.UserControl = false;
    oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    oWB.Close();
    oXL.Quit();

    //...

How to connect PHP with Microsoft Access database

Are you sure the odbc connector is well created ? if not check the step "Create an ODBC Connection" again

EDIT: Connection without DSN from php.net

// Microsoft Access

$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);

in your case it might be if your filename is northwind and your file extension mdb:

$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=northwind", "", "");

AngularJS ui router passing data between states without URL

We can use params, new feature of the UI-Router:

API Reference / ui.router.state / $stateProvider

params A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.

See the part: "...or defines additional non-url parameters..."

So the state def would be:

$stateProvider
  .state('home', {
    url: "/home",
    templateUrl: 'tpl.html',
    params: { hiddenOne: null, }
  })

Few examples form the doc mentioned above:

// define a parameter's default value
params: {
  param1: { value: "defaultValue" }
}
// shorthand default values
params: {
  param1: "defaultValue",
  param2: "param2Default"
}

// param will be array []
params: {
  param1: { array: true }
}

// handling the default value in url:
params: {
  param1: {
    value: "defaultId",
    squash: true
} }
// squash "defaultValue" to "~"
params: {
  param1: {
    value: "defaultValue",
    squash: "~"
  } }

EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info

Here is an example of a state definition:

 $stateProvider
  .state('home', {
      url: "/home",
      params : { veryLongParamHome: null, },
      ...
  })
  .state('parent', {
      url: "/parent",
      params : { veryLongParamParent: null, },
      ...
  })
  .state('parent.child', { 
      url: "/child",
      params : { veryLongParamChild: null, },
      ...
  })

This could be a call using ui-sref:

<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
  })">home</a>

<a ui-sref="parent({ 
    veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
  })">parent</a>

<a ui-sref="parent.child({
    veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',  
    veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
  })">parent.child</a>

Check the example here

How to remove an app with active device admin enabled on Android?

On Samsung go to "Settings" -> "Lock screen and security" -> "Other security settings" -> "Phone administrators" and deselect the admin which you want to uninstall.

The "security" word was hidden on my display, so it was not obvious that I should click on "Lock screen".

Simplest SOAP example

This cannot be done with straight JavaScript unless the web service is on the same domain as your page. Edit: In 2008 and in IE<10 this cannot be done with straight javascript unless the service is on the same domain as your page.

If the web service is on another domain [and you have to support IE<10] then you will have to use a proxy page on your own domain that will retrieve the results and return them to you. If you do not need old IE support then you need to add CORS support to your service. In either case, you should use something like the lib that timyates suggested because you do not want to have to parse the results yourself.

If the web service is on your own domain then don't use SOAP. There is no good reason to do so. If the web service is on your own domain then modify it so that it can return JSON and save yourself the trouble of dealing with all the hassles that come with SOAP.

Short answer is: Don't make SOAP requests from javascript. Use a web service to request data from another domain, and if you do that then parse the results on the server-side and return them in a js friendly form.

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

YES, PUT, DELETE, HEAD etc HTTP methods are available in all modern browsers.

To be compliant with XMLHttpRequest Level 2 browsers must support these methods. To check which browsers support XMLHttpRequest Level 2 I recommend CanIUse:

http://caniuse.com/#feat=xhr2

Only Opera Mini is lacking support atm (juli '15), but Opera Mini lacks support for everything. :)

How to generate sample XML documents from their DTD or XSD?

XML Blueprint also does that; instructions here

http://www.xmlblueprint.com/help/html/topic_170.htm

It's not free, but there's a 10-day free trial; it seems fast and efficient; unfortunately it's Windows only.

mongodb service is not starting up

On my ubuntu server, just run:

sudo rm /var/lib/mongodb/mongod.lock
mongod --repair
sudo service mongodb start

Google.com and clients1.google.com/generate_204

This documents explains:

http://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1417&context=ecetr&sei-redir=1

(Search for generate204)

Relevant section:

Among the different objects, a javascript function triggers a generate204 request sent to the video server that is supposed to serve the video. This starts the video prefetch, which has two main goals: first, it forces the client to perform the DNS resolution of the video server name. Second, it forces the client to open a TCP connection toward the video server. Both help to speed-up the video download phase.

In addition, the generate204 request has exactly the same format and options of the real video download request, so that the video server is eventually warned that a client will possibly download that video very soon. Note that the video server replies with a 204 No Content response, as implied by the command, and no video content is downloaded so far.

Django Rest Framework -- no module named rest_framework

When using a virtual environment like virtualenvwithout having django-rest-framework installed globally you might as well have the error. The solution would be:

  • activate the environment first with {{your environment name}}/bin/activate for Linux or {{your environment name}}/Scripts/activate for Windows

  • and then run the command again.

Visual C++: How to disable specific linker warnings?

Update 2018-10-16

Reportedly, as of VS 2013, this warning can be disabled. See the comment by @Mark Ransom.

Original Answer

You can't disable that specific warning.

According to Geoff Chappell the 4099 warning is treated as though it's too important to ignore, even by using in conjunction with /wx (which would treat warnings as errors and ignore the specified warning in other situations)

Here is the relevant text from the link:

Not Quite Unignorable Warnings

For some warning numbers, specification in a /ignore option is accepted but not necessarily acted upon. Should the warning occur while the /wx option is not active, then the warning message is still displayed, but if the /wx option is active, then the warning is ignored. It is as if the warning is thought important enough to override an attempt at ignoring it, but not if the user has put too high a price on unignored warnings.

The following warning numbers are affected:

4200, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4219, 4231 and 4237

Auto refresh code in HTML using meta tags

<meta http-equiv="refresh" content="600; url=index.php">

600 is the amount of seconds between refresh cycles.

Get Android Device Name

@hbhakhra's answer will do.

If you're interested in detailed explanation, it is useful to look into Android Compatibility Definition Document. (3.2.2 Build Parameters)

You will find:

DEVICE - A value chosen by the device implementer containing the development name or code name identifying the configuration of the hardware features and industrial design of the device. The value of this field MUST be encodable as 7-bit ASCII and match the regular expression “^[a-zA-Z0-9_-]+$”.

MODEL - A value chosen by the device implementer containing the name of the device as known to the end user. This SHOULD be the same name under which the device is marketed and sold to end users. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").

MANUFACTURER - The trade name of the Original Equipment Manufacturer (OEM) of the product. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").

powershell - list local users and their groups

try this one :),

Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }

How to generate .angular-cli.json file in Angular Cli?

In angular.json you can insert all css and js file in your template. Other ways, you can use from Style.css in src folder for load stylesheets.

@import "../src/fonts/font-awesome/css/font-awesome.min.css";
@import "../src/css/bootstrap.min.css";
@import "../src/css/now-ui-kit.css";
@import "../src/css/plugins/owl.carousel.css";
@import "../src/css/plugins/owl.theme.default.min.css";
@import "../src/css/main.css";

HTML entity for check mark

Something like this?

if so, type the HTML &#10004;

And &#10003; gives a lighter one:

Static variable inside of a function in C

Let's just read the Wikipedia article on Static Variables...

Static local variables: variables declared as static inside a function are statically allocated while having the same scope as automatic local variables. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.

What does "int 0x80" mean in assembly code?

It passes control to interrupt vector 0x80

See http://en.wikipedia.org/wiki/Interrupt_vector

On Linux, have a look at this: it was used to handle system_call. Of course on another OS this could mean something totally different.