Programs & Examples On #Setupapi

SetupAPI is a Win32API that is used for installing device drivers and in enumerating existing devices on a Windows computer.

Error Message : Cannot find or open the PDB file

Working with VS 2013. Try the following Tools -> Options -> Debugging -> Output Window -> Module Load Messages -> Off It will disable the display of modules loaded.

Why does npm install say I have unmet dependencies?

--dev installing devDependencies recursively (and its run forever..) how it can help to resolve the version differences?

You can try remove the node_moduls folder, then clean the npm cache and then run 'npm i' again

Does Go have "if x in" construct similar to Python?

Another solution if the list contains static values.

eg: checking for a valid value from a list of valid values:

func IsValidCategory(category string) bool {
    switch category {
    case
        "auto",
        "news",
        "sport",
        "music":
        return true
    }
    return false
}

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

What is the difference between H.264 video and MPEG-4 video?

H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance application

H264 is now enshrined in MPEG4 as part 10 also known as AVC

Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf

Hope this helps.

How to add (vertical) divider to a horizontal LinearLayout?

You have to create the any view for separater like textview or imageview then set the background for that if you have image else use the color as the background.

Hope this helps you.

TypeScript - Append HTML to container element in Angular 2

You could do something like this:

htmlComponent.ts

htmlVariable: string = "<b>Some html.</b>"; //this is html in TypeScript code that you need to display

htmlComponent.html

<div [innerHtml]="htmlVariable"></div> //this is how you display html code from TypeScript in your html

What is default session timeout in ASP.NET?

The default is 20 minutes. http://msdn.microsoft.com/en-us/library/h6bb9cz9(v=vs.80).aspx

<sessionState 
mode="[Off|InProc|StateServer|SQLServer|Custom]"
timeout="number of minutes"
cookieName="session identifier cookie name"
cookieless=
     "[true|false|AutoDetect|UseCookies|UseUri|UseDeviceProfile]"
regenerateExpiredSessionId="[True|False]"
sqlConnectionString="sql connection string"
sqlCommandTimeout="number of seconds"
allowCustomSqlDatabase="[True|False]"
useHostingIdentity="[True|False]"
stateConnectionString="tcpip=server:port"
stateNetworkTimeout="number of seconds"
customProvider="custom provider name">
<providers>...</providers>
</sessionState>

access denied for user @ 'localhost' to database ''

Try this: Adding users to MySQL

You need grant privileges to the user if you want external acess to database(ie. web pages).

IBOutlet and IBAction

Ran into the diagram while looking at key-value coding, thought it might help someone. It helps with understanding of what IBOutlet is.

By looking at the flow, one could see that IBOutlets are only there to match the property name with a control name in the Nib file.

How nib file is loaded, screenshot of Matt's online book for iOS6

Python logging not outputting anything

Maybe try this? It seems the problem is solved after remove all the handlers in my case.

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

logging.basicConfig(filename='output.log', level=logging.INFO)

How to make a cross-module variable?

I don't endorse this solution in any way, shape or form. But if you add a variable to the __builtin__ module, it will be accessible as if a global from any other module that includes __builtin__ -- which is all of them, by default.

a.py contains

print foo

b.py contains

import __builtin__
__builtin__.foo = 1
import a

The result is that "1" is printed.

Edit: The __builtin__ module is available as the local symbol __builtins__ -- that's the reason for the discrepancy between two of these answers. Also note that __builtin__ has been renamed to builtins in python3.

How to push object into an array using AngularJS

You should try this way. It will definitely work.

(function() {

var app = angular.module('myApp', []);

 app.controller('myController', ['$scope', function($scope) {

    $scope.myText = "Object Push inside ";

    $scope.arrayText = [

        ];

    $scope.addText = function() {
        $scope.arrayText.push(this.myText);
    }

 }]);

})();

In your case $scope.arrayText is an object. You should initialize as a array.

How to redirect output of systemd service to a file

You possibly get this error:

Failed to parse output specifier, ignoring: /var/log1.log

From the systemd.exec(5) man page:

StandardOutput=

Controls where file descriptor 1 (STDOUT) of the executed processes is connected to. Takes one of inherit, null, tty, journal, syslog, kmsg, journal+console, syslog+console, kmsg+console or socket.

The systemd.exec(5) man page explains other options related to logging. See also the systemd.service(5) and systemd.unit(5) man pages.

Or maybe you can try things like this (all on one line):

ExecStart=/bin/sh -c '/usr/local/bin/binary1 agent -config-dir /etc/sample.d/server 2>&1 > /var/log.log' 

C - determine if a number is prime

After reading this question, I was intrigued by the fact that some answers offered optimization by running a loop with multiples of 2*3=6.

So I create a new function with the same idea, but with multiples of 2*3*5=30.

int check235(unsigned long n)
{
    unsigned long sq, i;

    if(n<=3||n==5)
        return n>1;

    if(n%2==0 || n%3==0 || n%5==0)
        return 0;

    if(n<=30)
        return checkprime(n); /* use another simplified function */

    sq=ceil(sqrt(n));
    for(i=7; i<=sq; i+=30)
        if (n%i==0 || n%(i+4)==0 || n%(i+6)==0 || n%(i+10)==0 || n%(i+12)==0 
           || n%(i+16)==0 || n%(i+22)==0 || n%(i+24)==0)
            return 0;

        return 1;
}

By running both functions and checking times I could state that this function is really faster. Lets see 2 tests with 2 different primes:

$ time ./testprimebool.x 18446744069414584321 0
f(2,3)
Yes, its prime.    
real    0m14.090s
user    0m14.096s
sys     0m0.000s

$ time ./testprimebool.x 18446744069414584321 1
f(2,3,5)
Yes, its prime.    
real    0m9.961s
user    0m9.964s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 0
f(2,3)
Yes, its prime.    
real    0m13.990s
user    0m13.996s
sys     0m0.004s

$ time ./testprimebool.x 18446744065119617029 1
f(2,3,5)
Yes, its prime.    
real    0m10.077s
user    0m10.068s
sys     0m0.004s

So I thought, would someone gain too much if generalized? I came up with a function that will do a siege first to clean a given list of primordial primes, and then use this list to calculate the bigger one.

int checkn(unsigned long n, unsigned long *p, unsigned long t)
{
    unsigned long sq, i, j, qt=1, rt=0;
    unsigned long *q, *r;

    if(n<2)
        return 0;

    for(i=0; i<t; i++)
    {
        if(n%p[i]==0)
            return 0;
        qt*=p[i];
    }
    qt--;

    if(n<=qt)
        return checkprime(n); /* use another simplified function */

    if((q=calloc(qt, sizeof(unsigned long)))==NULL)
    {
        perror("q=calloc()");
        exit(1);
    }
    for(i=0; i<t; i++)
        for(j=p[i]-2; j<qt; j+=p[i])
            q[j]=1;

    for(j=0; j<qt; j++)
        if(q[j])
            rt++;

    rt=qt-rt;
    if((r=malloc(sizeof(unsigned long)*rt))==NULL)
    {
        perror("r=malloc()");
        exit(1);
    }
    i=0;
    for(j=0; j<qt; j++)
        if(!q[j])
            r[i++]=j+1;

    free(q);

    sq=ceil(sqrt(n));
    for(i=1; i<=sq; i+=qt+1)
    {
        if(i!=1 && n%i==0)
            return 0;
        for(j=0; j<rt; j++)
            if(n%(i+r[j])==0)
                return 0;
    }
    return 1;
}

I assume I did not optimize the code, but it's fair. Now, the tests. Because so many dynamic memory, I expected the list 2 3 5 to be a little slower than the 2 3 5 hard-coded. But it was ok as you can see bellow. After that, time got smaller and smaller, culminating the best list to be:

2 3 5 7 11 13 17 19

With 8.6 seconds. So if someone would create a hardcoded program that makes use of such technique I would suggest use the list 2 3 and 5, because the gain is not that big. But also, if willing to code, this list is ok. Problem is you cannot state all cases without a loop, or your code would be very big (There would be 1658879 ORs, that is || in the respective internal if). The next list:

2 3 5 7 11 13 17 19 23

time started to get bigger, with 13 seconds. Here the whole test:

$ time ./testprimebool.x 18446744065119617029 2 3 5
f(2,3,5)
Yes, its prime.
real    0m12.668s
user    0m12.680s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7
f(2,3,5,7)
Yes, its prime.
real    0m10.889s
user    0m10.900s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11
f(2,3,5,7,11)
Yes, its prime.
real    0m10.021s
user    0m10.028s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13
f(2,3,5,7,11,13)
Yes, its prime.
real    0m9.351s
user    0m9.356s
sys     0m0.004s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17
f(2,3,5,7,11,13,17)
Yes, its prime.
real    0m8.802s
user    0m8.800s
sys     0m0.008s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17 19
f(2,3,5,7,11,13,17,19)
Yes, its prime.
real    0m8.614s
user    0m8.564s
sys     0m0.052s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17 19 23
f(2,3,5,7,11,13,17,19,23)
Yes, its prime.
real    0m13.013s
user    0m12.520s
sys     0m0.504s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17 19 23 29
f(2,3,5,7,11,13,17,19,23,29)                                                                                                                         
q=calloc(): Cannot allocate memory

PS. I did not free(r) intentionally, giving this task to the OS, as the memory would be freed as soon as the program exited, to gain some time. But it would be wise to free it if you intend to keep running your code after the calculation.


BONUS

int check2357(unsigned long n)
{
    unsigned long sq, i;

    if(n<=3||n==5||n==7)
        return n>1;

    if(n%2==0 || n%3==0 || n%5==0 || n%7==0)
        return 0;

    if(n<=210)
        return checkprime(n); /* use another simplified function */

    sq=ceil(sqrt(n));
    for(i=11; i<=sq; i+=210)
    {    
        if(n%i==0 || n%(i+2)==0 || n%(i+6)==0 || n%(i+8)==0 || n%(i+12)==0 || 
   n%(i+18)==0 || n%(i+20)==0 || n%(i+26)==0 || n%(i+30)==0 || n%(i+32)==0 || 
   n%(i+36)==0 || n%(i+42)==0 || n%(i+48)==0 || n%(i+50)==0 || n%(i+56)==0 || 
   n%(i+60)==0 || n%(i+62)==0 || n%(i+68)==0 || n%(i+72)==0 || n%(i+78)==0 || 
   n%(i+86)==0 || n%(i+90)==0 || n%(i+92)==0 || n%(i+96)==0 || n%(i+98)==0 || 
   n%(i+102)==0 || n%(i+110)==0 || n%(i+116)==0 || n%(i+120)==0 || n%(i+126)==0 || 
   n%(i+128)==0 || n%(i+132)==0 || n%(i+138)==0 || n%(i+140)==0 || n%(i+146)==0 || 
   n%(i+152)==0 || n%(i+156)==0 || n%(i+158)==0 || n%(i+162)==0 || n%(i+168)==0 || 
   n%(i+170)==0 || n%(i+176)==0 || n%(i+180)==0 || n%(i+182)==0 || n%(i+186)==0 || 
   n%(i+188)==0 || n%(i+198)==0)
            return 0;
    }
    return 1;
}

Time:

$ time ./testprimebool.x 18446744065119617029 7
h(2,3,5,7)
Yes, its prime.
real    0m9.123s
user    0m9.132s
sys     0m0.000s

What's the proper value for a checked attribute of an HTML checkbox?

<input ... checked />
<input ... checked="checked" />

Those are equally valid. And in JavaScript:

input.checked = true;
input.setAttribute("checked");
input.setAttribute("checked","checked");

How to extract epoch from LocalDate and LocalDateTime?

This is one way without using time a zone:

LocalDateTime now = LocalDateTime.now();
long epoch = (now.getLong(ChronoField.EPOCH_DAY) * 86400000) + now.getLong(ChronoField.MILLI_OF_DAY);

How to pass credentials to the Send-MailMessage command for sending emails

I found this blog site: Adam Kahtava
I also found this question: send-mail-via-gmail-with-powershell-v2s-send-mailmessage
The problem is, neither of them addressed both your needs (Attachment with a password), so I did some combination of the two and came up with this:

$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Test" 
$Body = "Test Body" 
$SMTPServer = "smtp.gmail.com" 
$filenameAndPath = "C:\CDF.pdf"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password"); 
$SMTPClient.Send($SMTPMessage)

Since I love to make functions for things, and I need all the practice I can get, I went ahead and wrote this:

Function Send-EMail {
    Param (
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailTo,
        [Parameter(`
            Mandatory=$true)]
        [String]$Subject,
        [Parameter(`
            Mandatory=$true)]
        [String]$Body,
        [Parameter(`
            Mandatory=$true)]
        [String]$EmailFrom="[email protected]",  #This gives a default value to the $EmailFrom command
        [Parameter(`
            mandatory=$false)]
        [String]$attachment,
        [Parameter(`
            mandatory=$true)]
        [String]$Password
    )

        $SMTPServer = "smtp.gmail.com" 
        $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
        if ($attachment -ne $null) {
            $SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
            $SMTPMessage.Attachments.Add($SMTPattachment)
        }
        $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
        $SMTPClient.EnableSsl = $true 
        $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("@")[0], $Password); 
        $SMTPClient.Send($SMTPMessage)
        Remove-Variable -Name SMTPClient
        Remove-Variable -Name Password

} #End Function Send-EMail

To call it, just use this command:

Send-EMail -EmailTo "[email protected]" -Body "Test Body" -Subject "Test Subject" -attachment "C:\cdf.pdf" -password "Passowrd"

I know it's not secure putting the password in plainly like that. I'll see if I can come up with something more secure and update later, but at least this should get you what you need to get started. Have a great week!

Edit: Added $EmailFrom based on JuanPablo's comment

Edit: SMTP was spelled STMP in the attachments.

What is the role of "Flatten" in Keras?

short read:

Flattening a tensor means to remove all of the dimensions except for one. This is exactly what the Flatten layer do.

long read:

If we take the original model (with the Flatten layer) created in consideration we can get the following model summary:

Layer (type)                 Output Shape              Param #   
=================================================================
D16 (Dense)                  (None, 3, 16)             48        
_________________________________________________________________
A (Activation)               (None, 3, 16)             0         
_________________________________________________________________
F (Flatten)                  (None, 48)                0         
_________________________________________________________________
D4 (Dense)                   (None, 4)                 196       
=================================================================
Total params: 244
Trainable params: 244
Non-trainable params: 0

For this summary the next image will hopefully provide little more sense on the input and output sizes for each layer.

The output shape for the Flatten layer as you can read is (None, 48). Here is the tip. You should read it (1, 48) or (2, 48) or ... or (16, 48) ... or (32, 48), ...

In fact, None on that position means any batch size. For the inputs to recall, the first dimension means the batch size and the second means the number of input features.

The role of the Flatten layer in Keras is super simple:

A flatten operation on a tensor reshapes the tensor to have the shape that is equal to the number of elements contained in tensor non including the batch dimension.

enter image description here


Note: I used the model.summary() method to provide the output shape and parameter details.

Relative paths based on file location instead of current working directory

@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.

This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:


Linux / GNU readlink solution:

If your script needs to run on Linux only or you know that GNU readlink is in the $PATH, use readlink -f, which conveniently resolves a symlink to its ultimate target:

 scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")

Note that GNU readlink has 3 related options for resolving a symlink to its ultimate target's full path: -f (--canonicalize), -e (--canonicalize-existing), and -m (--canonicalize-missing) - see man readlink.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f here, because it is the most well-known one.


Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):

If your script must run on any platform that:

  • has a readlink utility, but lacks the -f option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.

    • macOS uses an older version of the BSD implementation of readlink; note that recent versions of FreeBSD/PC-BSD do support -f.
  • does not even have readlink, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).

The following solution, inspired by https://stackoverflow.com/a/1116890/45375, defines helper shell function, rreadlink(), which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink's -e option, which is similar to the -f option, except that the ultimate target must exist.

Note: The function is a bash function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh), see here.

  • If readlink is available, it is used (without options) - true on most modern platforms.

  • Otherwise, the output from ls -l is parsed, which is the only POSIX-compliant way to determine a symlink's target.
    Caveat: this will break if a filename or path contains the literal substring -> - which is unlikely, however.
    (Note that platforms that lack readlink may still provide other, non-POSIX methods for resolving a symlink; e.g., @Charles Duffy mentions HP-UX's find utility supporting the %l format char. with its -printf primary; in the interest of brevity the function does NOT try to detect such cases.)

  • An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink; on other platforms (assuming they have bash), follow the manual installation instructions.

If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.

#!/usr/bin/env bash

# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...

  local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH= 

  # Since we'll be using `command` below for a predictable execution
  # environment, we make sure that it has its original meaning.
  { \unalias command; \unset -f command; } &>/dev/null

  while :; do # Resolve potential symlinks until the ultimate target is found.
      [[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
      command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
      fname=$(command basename -- "$target") # Extract filename.
      [[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
      if [[ -L $fname ]]; then
        # Extract [next] target path, which is defined
        # relative to the symlink's own directory.
        if [[ -n $readlinkexe ]]; then # Use `readlink`.
          target=$("$readlinkexe" -- "$fname")
        else # `readlink` utility not available.
          # Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant 
          # way to determine a symlink's target. Hypothetically, this can break with
          # filenames containig literal ' -> ' and embedded newlines.
          target=$(command ls -l -- "$fname")
          target=${target#* -> }
        fi
        continue # Resolve [next] symlink target.
      fi
      break # Ultimate target reached.
  done
  targetDir=$(command pwd -P) # Get canonical dir. path
  # Output the ultimate target's canonical path.
  # Note that we manually resolve paths ending in /. and /.. to make sure we
  # have a normalized path.
  if [[ $fname == '.' ]]; then
    command printf '%s\n' "${targetDir%/}"
  elif  [[ $fname == '..' ]]; then
    # Caveat: something like /var/.. will resolve to /private (assuming
    # /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
    command printf '%s\n' "$(command dirname -- "${targetDir}")"
  else
    command printf '%s\n' "${targetDir%/}/$fname"
  fi
)

# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")

Changing plot scale by a factor in matplotlib

Instead of changing the ticks, why not change the units instead? Make a separate array X of x-values whose units are in nm. This way, when you plot the data it is already in the correct format! Just make sure you add a xlabel to indicate the units (which should always be done anyways).

from pylab import *

# Generate random test data in your range
N = 200
epsilon = 10**(-9.0)
X = epsilon*(50*random(N) + 1)
Y = random(N)

# X2 now has the "units" of nanometers by scaling X
X2 = (1/epsilon) * X

subplot(121)
scatter(X,Y)
xlim(epsilon,50*epsilon)
xlabel("meters")

subplot(122)
scatter(X2,Y)
xlim(1, 50)
xlabel("nanometers")

show()

enter image description here

catch specific HTTP error in python

For Python 3.x

import urllib.request
from urllib.error import HTTPError
try:
    urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
    print(err.code)

Center Contents of Bootstrap row container

I solved this by doing the following:

<body class="container-fluid">
    <div class="row">
        <div class="span6" style="float: none; margin: 0 auto;">
           ....
        </div>
    </div>
</body>

SwiftUI - How do I change the background color of a View?

Would this solution work?:

add following line to SceneDelegate: window.rootViewController?.view.backgroundColor = .black

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {

                window.rootViewController?.view.backgroundColor = .black
}

HTTP POST Returns Error: 417 "Expectation Failed."

Does the form you are trying to emulate have two fields, username and password?

If so, this line:

 postData.Add("username", "password");

is not correct.

you would need two lines like:

 postData.Add("username", "Moose");
postData.Add("password", "NotMoosespasswordreally");

Edit:

Okay, since that is not the problem, one way to tackle this is to use something like Fiddler or Wireshark to watch what is being sent to the web server from the browser successfully, then compare that to what is being sent from your code. If you are going to a normal port 80 from .Net, Fiddler will still capture this traffic.

There is probably some other hidden field on the form that the web server is expecting that you are not sending.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

The exception indicates a problem with the unobtrusive JavaScript validation mode. This issue is not Sitefinity specific and occurs in any standard ASP.NET applications when the project targets .NET 4.5 framework and the pre-4.5 validation is not enabled in the web.config file.

Open the web.config file and make sure that there is a ValidationSettings:UnobtrusiveValidationMode in the app settings:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

What is HTML5 ARIA?

What is ARIA?

ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.

The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.

It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.

Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

Just use ojdb6.jar and will fix all such issues.

For maven based applications:

  1. Download and copy ojdbc6.jar to a directory in your local machine

  2. From the location where you have copied your jar install the ojdbc6.jar in your local .M2 Repo by issuing below command C:\SRK\Softwares\Libraries>mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=ojdbc6.jar -DgeneratePom=true

  3. Add the below in your project pom.xml as ojdbc6.jar dependency

    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.3</version>
    </dependency>
    

PS: The issue might be due to uses of @Lob annotation in JPA for storing large objects specifically in oracle db columns. Upgrading to 11.2.0.3 (ojdbc6.jar) can resolve the issue.

How To Get The Current Year Using Vba

Try =Year(Now()) and format the cell as General.

What is the "-->" operator in C/C++?

char sep = '\n'  /1\
; int i = 68    /1  \
; while (i  ---      1\
                       \
                       /1/1/1                               /1\
                                                            /1\
                                                            /1\
                                                            /1\
                                                            /1\
                            /           1\
                           /            1 \
                          /             1  \
                         /              1   \
                         /1            /1    \
                          /1          /1      \
                           /1        /1        /1/1> 0) std::cout \
                              <<i<<                               sep;

For larger numbers, C++20 introduces some more advanced looping features. First to catch i we can build an inverse loop-de-loop and deflect it onto the std::ostream. However, the speed of i is implementation-defined, so we can use the new C++20 speed operator <<i<< to speed it up. We must also catch it by building wall, if we don't, i leaves the scope and de referencing it causes undefined behavior. To specify the separator, we can use:

 std::cout \
           sep

and there we have a for loop from 67 to 1.

possible EventEmitter memory leak detected

I was facing the same issue, but i have successfully handled with async await.
Please check if it helps.

let dataLength = 25;
Before:
  for (let i = 0; i < dataLength; i++) {
      sftp.get(remotePath, fs.createWriteStream(xyzProject/${data[i].name}));
  }

After:
  for (let i = 0; i < dataLength; i++) {
      await sftp.get(remotePath, fs.createWriteStream(xyzProject/${data[i].name}));
  }

How to hide Table Row Overflow?

wrap the table in a div with class="container"

div.container {
    width: 100%;
    overflow-x: auto;
}

then

#table_id tr td {
   white-space:nowrap;
}

result

overflow effect

Case insensitive regular expression without re.compile?

Pass re.IGNORECASE to the flags param of search, match, or sub:

re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)

Difference between "and" and && in Ruby?

The practical difference is binding strength, which can lead to peculiar behavior if you're not prepared for it:

foo = :foo
bar = nil

a = foo and bar
# => nil
a
# => :foo

a = foo && bar
# => nil
a
# => nil

a = (foo and bar)
# => nil
a
# => nil

(a = foo) && bar
# => nil
a
# => :foo

The same thing works for || and or.

Set ANDROID_HOME environment variable in mac

Open the terminal and type :

export ANDROID_HOME=/Applications/ADT/sdk

Add this to the PATH environment variable

export PATH=$PATH:$ANDROID_HOME/platform-tools

If the terminal doesn't locate the added path(s) from the .bash_profile, please run this command

source ~/.bash_profile

Hope it works to you!

Change the default base url for axios

Instead of

this.$axios.get('items')

use

this.$axios({ url: 'items', baseURL: 'http://new-url.com' })

If you don't pass method: 'XXX' then by default, it will send via get method.

Request Config: https://github.com/axios/axios#request-config

PHP json_decode() returns NULL with valid JSON?

  • I also face the same issue...
  • I fix the following steps... 1) I print that variable in browser 2) Validate that variable data by freeformatter 3) copy/refer that data in further processing
  • after that, I didn't get any issue.

Android 8: Cleartext HTTP traffic not permitted

I using Cordova 8 with cordova-plugin-whitelist 1.3.4 and it default configuration my app no access to internet and i only add a parameter in the manifest.xml -> android:usesCleartextTraffic="true"

The path of mainfest changed in Cordova 8: platform/android/app/src/main/AndroidManifest.xml.

 <?xml version='1.0' encoding='utf-8'?>
    <manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="io.cordova.hellocordova" xmlns:android="http://schemas.android.com/apk/res/android">
        <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
        <application 
android:hardwareAccelerated="true" 
android:icon="@mipmap/ic_launcher" 
android:label="@string/app_name" 
android:supportsRtl="true" 
android:usesCleartextTraffic="true">
            <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
                <intent-filter android:label="@string/launcher_name">
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    </manifest>

this is a real stupid because it obvious that your app need access to internet....

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

How to detect if javascript files are loaded?

Like T.J. wrote: the order is defined (at least it's sequential when your browser is about to execute any JavaScript, even if it may download the scripts in parallel somehow). However, as apparently you're having trouble, maybe you're using third-party JavaScript libraries that yield some 404 Not Found or timeout? If so, then read Best way to use Google’s hosted jQuery, but fall back to my hosted library on Google fail.

Python Pandas counting and summing specific conditions

I usually use numpy sum over the logical condition column:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'Age' : [20,24,18,5,78]})
>>> np.sum(df['Age'] > 20)
2

This seems to me slightly shorter than the solution presented above

How to convert a time string to seconds?

def time_to_sec(time):
    sep = ','
    rest = time.split(sep, 1)[0]
    splitted = rest.split(":")
    emel = len(splitted) - 1
    i = 0
    summa = 0
    for numb in splitted:
        szor = 60 ** (emel - i)
        i += 1
        summa += int(numb) * szor
    return summa

How do I use namespaces with TypeScript external modules?

Small impovement of Albinofrenchy answer:

base.ts

export class Animal {
move() { /* ... */ }
}

export class Plant {
  photosynthesize() { /* ... */ }
}

dog.ts

import * as b from './base';

export class Dog extends b.Animal {
   woof() { }
} 

things.ts

import { Dog } from './dog'

namespace things {
  export const dog = Dog;
}

export = things;

main.ts

import * as things from './things';

console.log(things.dog);

Apply multiple functions to multiple groupby columns

Ted's answer is amazing. I ended up using a smaller version of that in case anyone is interested. Useful when you are looking for one aggregation that depends on values from multiple columns:

create a dataframe

df=pd.DataFrame({'a': [1,2,3,4,5,6], 'b': [1,1,0,1,1,0], 'c': ['x','x','y','y','z','z']})


   a  b  c
0  1  1  x
1  2  1  x
2  3  0  y
3  4  1  y
4  5  1  z
5  6  0  z

grouping and aggregating with apply (using multiple columns)

df.groupby('c').apply(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

c
x    2.0
y    4.0
z    5.0

grouping and aggregating with aggregate (using multiple columns)

I like this approach since I can still use aggregate. Perhaps people will let me know why apply is needed for getting at multiple columns when doing aggregations on groups.

It seems obvious now, but as long as you don't select the column of interest directly after the groupby, you will have access to all the columns of the dataframe from within your aggregation function.

only access to the selected column

df.groupby('c')['a'].aggregate(lambda x: x[x>1].mean())

access to all columns since selection is after all the magic

df.groupby('c').aggregate(lambda x: x[(x['a']>1) & (x['b']==1)].mean())['a']

or similarly

df.groupby('c').aggregate(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

I hope this helps.

How to remove the arrow from a select element in Firefox

hackity hack ... a solution that works in every browser I've tested (Safari, Firefox, Chrome). Don't have any IEs lying around, so it would be nice if you could test and comment:

<div class="wrapper">
  <select>
    <option>123456789</option>
    <option>234567890</option>
  </select>
</div>

CSS, with url-encoded image:

.wrapper { position:relative; width:200px; }
.wrapper:after {
  content:"";
  display: block;
  position: absolute;
  top:1px; height:28px;
  right:1px; width:16px;
  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAcCAYAAACH81QkAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2hpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDowODgwMTE3NDA3MjA2ODExOEE2RENENTU2MTFGMEQ1RCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpGNDE5NDQ3Nzc5ODIxMUU0OEU0M0JFMzgzMkUxOTk3MiIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpGNDE5NDQ3Njc5ODIxMUU0OEU0M0JFMzgzMkUxOTk3MiIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M2IChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6MDk4MDExNzQwNzIwNjgxMThBNkRDRDU1NjExRjBENUQiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6MDg4MDExNzQwNzIwNjgxMThBNkRDRDU1NjExRjBENUQiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4o7anbAAAAjklEQVR42uzUsQ3EIAwFUPty7MBOsAoVC7EVYgyUSFcdzn0iJYquAZGSLxnLzatsWERWGsvGP0QGkc+LxvN9AqGJTKQJMcYQM/+VtbZdiTGKUgr3cxbmlJI0ZiW83vsbgrkjB5JzFq11BdAxdyNICKEi6J25kFKKOOdq70We+JS2ufYTacjyxrKMLtsuwAAznzqGLHX9BwAAAABJRU5ErkJggg==);

  pointer-events: none;
}

select {
  width: 100%;
  padding:3px;
  margin: 0;
  border-radius: 0;
  border:1px solid black;
  outline:none;
  display: inline-block;
  -webkit-appearance:none;
  -moz-appearance:none;
  appearance:none;
  cursor:pointer;
  float:none!important;
  background:white;

  font-size:13px;
  line-height: 1em;
  height: 30px;
  padding:6px 20px 6px 10px;
}

http://codepen.io/anon/pen/myPEBy

I'm using the :after-element to cover the ugly arrow. Since select doesn't support :after, i need a wrapper to work with. Now, if you would click on the arrow, the dropdown won't register it ... unless your browser supports pointer-events: none, which everyone except IE10- does: http://caniuse.com/#feat=pointer-events

So for me it's perfect - a nice, clean, low-headache solution, at least compared to all the other options which include javascript.

tl;dr:

If IE10 (or lower) Users click the arrow, it won't work. Works good enough for me...

Gradle proxy configuration

Based on SourceSimian's response; this worked on Windows domain user accounts. Note that the Username does not have domain included,

task setHttpProxyFromEnv {
    def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
    for (e in System.getenv()) {
        def key = e.key.toUpperCase()
        if (key in map) {
            def base = map[key]
            def url = e.value.toURL()
            println " - systemProp.${base}.proxy=${url.host}:${url.port}"
            System.setProperty("${base}.proxyHost", url.host.toString())
            System.setProperty("${base}.proxyPort", url.port.toString())
            System.setProperty("${base}.proxyUser", "Username")
            System.setProperty("${base}.proxyPassword", "Password")
        }
    }
}
build.dependsOn setHttpProxyFromEnv

Rails raw SQL example

You can do this:

sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)

records_array would then be the result of your sql query in an array which you can iterate through.

JavaScript: filter() for Objects

My opinionated solution:

function objFilter(obj, filter, nonstrict){
  r = {}
  if (!filter) return {}
  if (typeof filter == 'string') return {[filter]: obj[filter]}
  for (p in obj) {
    if (typeof filter == 'object' &&  nonstrict && obj[p] ==  filter[p]) r[p] = obj[p]
    else if (typeof filter == 'object' && !nonstrict && obj[p] === filter[p]) r[p] = obj[p]
    else if (typeof filter == 'function'){ if (filter(obj[p],p,obj)) r[p] = obj[p]}
    else if (filter.length && filter.includes(p)) r[p] = obj[p]
  }
  return r
}

Test cases:

obj = {a:1, b:2, c:3}

objFilter(obj, 'a') // returns: {a: 1}
objFilter(obj, ['a','b']) // returns: {a: 1, b: 2}
objFilter(obj, {a:1}) // returns: {a: 1}
objFilter(obj, {'a':'1'}, true) // returns: {a: 1}
objFilter(obj, (v,k,o) => v%2===1) // returns: {a: 1, c: 3}

https://gist.github.com/bernardoadc/872d5a174108823159d845cc5baba337

What are the differences between a clustered and a non-clustered index?

Clustered basically means that the data is in that physical order in the table. This is why you can have only one per table.

Unclustered means it's "only" a logical order.

How do I send a JSON string in a POST request in Go

I'm not familiar with napping, but using Golang's net/http package works fine (playground):

func main() {
    url := "http://restapi3.apiary.io/notes"
    fmt.Println("URL:>", url)

    var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
}

Mismatch Detected for 'RuntimeLibrary'

Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.

Creating and Update Laravel Eloquent

firstOrNew will create record if not exist and updating a row if already exist. You can also use updateOrCreate here is the full example

$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
); 

If there's a flight from Oakland to San Diego, set the price to $99. if not exist create new row

Reference Doc here: (https://laravel.com/docs/5.5/eloquent)

How to save a plot as image on the disk?

If you use R Studio http://rstudio.org/ there is a special menu to save you plot as any format you like and at any resolution you choose

Set a button group's width to 100% and make buttons equal width?

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="btn-group btn-block">_x000D_
  <button type="button" data-toggle="dropdown" class="btn btn-default btn-xs  btn-block  dropdown-toggle">Actions <span class="caret"></span>_x000D_
<span class="sr-only">Toggle Dropdown</span></button><ul role="menu" class="dropdown-menu"><li><a href="#">Action one</a></li><li class="divider"></li><li><a href="#" >Action Two</a></li></ul></div>
_x000D_
_x000D_
_x000D_

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

eval() can not handle the list object

tf.reset_default_graph()

a = tf.Variable(0.2, name="a")
b = tf.Variable(0.3, name="b")
z = tf.constant(0.0, name="z0")
for i in range(100):
    z = a * tf.cos(z + i) + z * tf.sin(b - i)
grad = tf.gradients(z, [a, b])

init = tf.global_variables_initializer()

with tf.Session() as sess:
    init.run()
    print("z:", z.eval())
    print("grad", grad.eval())

but Session.run() can

print("grad", sess.run(grad))

correct me if I am wrong

How to set the From email address for mailx command?

Just ran into this syntax problem on a CentOS 7 machine.

On a very old Ubuntu machine running mail, the syntax for a nicely composed email is

echo -e "$body" | mail -s "$subject" -a "From: Sender Name <$sender>" "$recipient"

However on a CentOS 7 box which came with mailx installed, it's quite different:

echo -e "$body" | mail -s "$subject" -S "from=Sender Name <$sender>" "$recipient"

Consulting man mail indicates that -r is deprecated and the 'From' sender address should now be set directly using -S "variable=value".

In these and subsequent examples, I'm defining $sender as "Sender Name <[email protected]>" and $recipients as "[email protected]" as I do in my bash script.

You may then find, as I did, that when you try to generate the email's body content in your script at the point of sending the email, you encounter a strange behaviour where the email body is instead attached as a binary file ("ATT00001.bin", "application/octet-stream" or "noname", depending on client).

This behaviour is how Heirloom mailx handles unrecognised / control characters in text input. (More info: https://access.redhat.com/solutions/1136493, which itself references the mailx man page for the solution.)

To get around this, I used a method which pipes the generated output through tr before passing to mail, and also specifies the charset of the email:

echo -e "$body" | tr -d \\r | mail -s "$subject" -S "from=$sender" -S "sendcharsets=utf-8,iso-8859-1" "$recipients"

In my script, I'm also explicitly delaring the locale beforehand as it's run as a cronjob (and cron doesn't inherit environmental variables):

LANG="en_GB.UTF8" ; export LANG ;

(An alternate method of setting locales for cronjobs is discussed here)

More info on these workarounds via https://stackoverflow.com/a/29826988/253139 and https://stackoverflow.com/a/3120227/253139.

SQL distinct for 2 fields in a database

If you still want to group only by one column (as I wanted) you can nest the query:

select c1, count(*) from (select distinct c1, c2 from t) group by c1

How to convert an integer to a string in any base?

You could use baseconv.py from my project: https://github.com/semente/python-baseconv

Sample usage:

>>> from baseconv import BaseConverter
>>> base20 = BaseConverter('0123456789abcdefghij')
>>> base20.encode(1234)
'31e'
>>> base20.decode('31e')
'1234'
>>> base20.encode(-1234)
'-31e'
>>> base20.decode('-31e')
'-1234'
>>> base11 = BaseConverter('0123456789-', sign='$')
>>> base11.encode('$1234')
'$-22'
>>> base11.decode('$-22')
'$1234'

There is some bultin converters as for example baseconv.base2, baseconv.base16 and baseconv.base64.

How to delete from select in MySQL?

SELECT (sub)queries return result sets. So you need to use IN, not = in your WHERE clause.

Additionally, as shown in this answer you cannot modify the same table from a subquery within the same query. However, you can either SELECT then DELETE in separate queries, or nest another subquery and alias the inner subquery result (looks rather hacky, though):

DELETE FROM posts WHERE id IN (
    SELECT * FROM (
        SELECT id FROM posts GROUP BY id HAVING ( COUNT(id) > 1 )
    ) AS p
)

Or use joins as suggested by Mchl.

What is the default initialization of an array in Java?

From the Java Language Specification:

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):

    • For type byte, the default value is zero, that is, the value of (byte)0.
    • For type short, the default value is zero, that is, the value of (short)0.
    • For type int, the default value is zero, that is, 0.
    • For type long, the default value is zero, that is, 0L.
    • For type float, the default value is positive zero, that is, 0.0f.
    • For type double, the default value is positive zero, that is, 0.0d.
    • For type char, the default value is the null character, that is, '\u0000'.
    • For type boolean, the default value is false.
    • For all reference types (§4.3), the default value is null.

Check if datetime instance falls in between other two datetime objects

Write yourself a Helper function:

public static bool IsBewteenTwoDates(this DateTime dt, DateTime start, DateTime end)
{
    return dt >= start && dt <= end;
}

Then call: .IsBewteenTwoDates(DateTime.Today ,new DateTime(,,));

Run chrome in fullscreen mode on Windows

  • Right click the Google Chrome icon and select Properties.
  • Copy the value of Target, for example: "C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe".
  • Create a shortcut on your Desktop.
  • Paste the value into Location of the item, and append --kiosk <your url>:

    "C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe" --kiosk http://www.google.com
    
  • Press Apply, then OK.

  • To start Chrome at Windows startup, copy this shortcut and paste it into the Startup folder (Start -> Program -> Startup).

HttpContext.Current.Request.Url.Host what it returns?

Try this:

string callbackurl = Request.Url.Host != "localhost" 
    ? Request.Url.Host : Request.Url.Authority;

This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.

Is there a way to add/remove several classes in one single instruction with classList?

Assume that you have an array of classes to being added, you can use ES6 spread syntax:

let classes = ['first', 'second', 'third']; elem.classList.add(...classes);

How do I check particular attributes exist or not in XML?

You can actually index directly into the Attributes collection (if you are using C# not VB):

foreach (XmlNode xNode in nodeListName)
{
  XmlNode parent = xNode.ParentNode;
  if (parent.Attributes != null
     && parent.Attributes["split"] != null)
  {
     parentSplit = parent.Attributes["split"].Value;
  }
}

RSpec: how to test if a method was called?

it "should call 'bar' with appropriate arguments" do
  expect(subject).to receive(:bar).with("an argument I want")
  subject.foo
end

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

if you want that not contains any of a-z and A-Z:

SELECT * FROM mytable WHERE NOT REGEXP_LIKE(column_1, '[A-Za-z]')

something like:

"98763045098" or "!%436%$7%$*#"

or other languages like persian, arabic and ... like this:

"???? ????"

How to var_dump variables in twig templates?

{{ dump() }} doesn't work for me. PHP chokes. Nesting level too deep I guess.

All you really need to debug Twig templates if you're using a debugger is an extension like this.

Then it's just a matter of setting a breakpoint and calling {{ inspect() }} wherever you need it. You get the same info as with {{ dump() }} but in your debugger.

Run a single test method with maven

What I do with my TestNG, (sorry, JUnit doesn't support this) test cases is I can assign a group to the test I want to run

@Test(groups="broken")

And then simply run 'mvn -Dgroups=broken'.

Check if current date is between two dates Oracle SQL

You don't need to apply to_date() to sysdate. It is already there:

select 1
from dual 
WHERE sysdate BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY');

If you are concerned about the time component on the date, then use trunc():

select 1
from dual 
WHERE trunc(sysdate) BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND
                             TO_DATE('20/06/2014', 'DD/MM/YYYY');

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

How to make join queries using Sequelize on Node.js

Model1.belongsTo(Model2, { as: 'alias' })

Model1.findAll({include: [{model: Model2  , as: 'alias'  }]},{raw: true}).success(onSuccess).error(onError);

Best way to do a split pane in HTML

You can use absolute of fixed positioning. This CSS for example will dock a 2em-bar on the left side of your page:

body {
    padding-left: 2.5em;
}
body > #bar {
    position:fixed;
    top:0; left:0;
    width: 2em;
    height: 100%;
    border-right: 2px solid #55F; background: #ddd;
}

(Demo at jsfiddle.net)

jQuery 'each' loop with JSON array

Brief code but full-featured

The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.

The jquery each runs the inner loop; I needed the regular JavaScript for on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.

This is only 5 main lines of code but wrapped onto multiple lines for display:

$.get("data.php", function(data){

    for (var propTitle in data) {

        $('<div></div>') 
            .addClass('heading')
            .insertBefore('#contentHere')
            .text(propTitle);

            $(data[propTitle]).each(function(iRec, oRec) {

                $('<div></div>')
                    .addClass(oRec.textType)
                    .attr('id', 'T'+oRec.textId)
                    .insertBefore('#contentHere')
                    .text(oRec.text);
            });
    }

});

Produces the output

(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")

<div class="heading">
    justIn
</div>
<div id="T123" class="Greeting">
    1Hello
</div>
<div id="T514" class="Question">
    1What's up?
</div>
<div id="T122" class="Order">
    1Come over here
</div>
<div class="heading">
    recent
</div>
<div id="T1255" class="Greeting">
    2Hello
</div>
<div id="T6564" class="Question">
    2What's up?
</div>
<div id="T0192" class="Order">
    2Come over here
</div>
<div class="heading">
    old
</div>
<div id="T5213" class="Greeting">
    3Hello
</div>
<div id="T9758" class="Question">
    3What's up?
</div>
<div id="T7655" class="Order">
    3Come over here
</div>
<div id="contentHere"></div>

Apply a style sheet

<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>

to get a "beautiful" looking set of data

alt text

More Info
The JSON data was used in the following way:

for each category (key name the array is held under):

  • the key name is used as the section heading (e.g. justIn)

for each object held inside an array:

  • 'text' becomes the content of a div
  • 'textType' becomes the class of the div (hooked into a style sheet)
  • 'textId' becomes the id of the div
  • e.g. <div id="T122" class="Order">Come over here</div>

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

It is because you set the width:100% which by definition only spans the width of the screen. You want to set the min-width:100% which sets it to the width of the screen... with the ability to grow beyond that.

Also make sure you set min-width:100% for body and html.

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

I run netstat -nao | findstr 5037 in cmd.

enter image description here

As you see there is a process with id 3888. I kill it with taskkill /f /pid 3888 if you have more than one, kill all.

enter image description here

after that run adb with adb start-server, my adb run sucessfully.

enter image description here

What does CultureInfo.InvariantCulture mean?

For things like numbers (decimal points, commas in amounts), they are usually preferred in the specific culture.

A appropriate way to do this would be set it at the culture level (for German) like this:

Thread.CurrentThread.CurrentCulture.NumberFormat = new CultureInfo("de").NumberFormat;

Difference between String replace() and replaceAll()

Both replace() and replaceAll() replace all occurrences in the String.

Examples

I always find examples helpful to understand the differences.

replace()

Use replace() if you just want to replace some char with another char or some String with another String (actually CharSequence).

Example 1

Replace all occurrences of the character x with o.

String myString = "__x___x___x_x____xx_";

char oldChar = 'x';
char newChar = 'o';

String newString = myString.replace(oldChar, newChar);
// __o___o___o_o____oo_

Example 2

Replace all occurrences of the string fish with sheep.

String myString = "one fish, two fish, three fish";

String target = "fish";
String replacement = "sheep";

String newString = myString.replace(target, replacement);
// one sheep, two sheep, three sheep

replaceAll()

Use replaceAll() if you want to use a regular expression pattern.

Example 3

Replace any number with an x.

String myString = "__1_6____3__6_345____0";

String regex = "\\d";
String replacement = "x";

String newString = myString.replaceAll(regex, replacement); 
// __x_x____x__x_xxx____x

Example 4

Remove all whitespace.

String myString = "   Horse         Cow\n\n   \r Camel \t\t Sheep \n Goat        ";

String regex = "\\s";
String replacement = "";

String newString = myString.replaceAll(regex, replacement); 
// HorseCowCamelSheepGoat

See also

Documentation

Regular Expressions

How can I have two fixed width columns with one flexible column in the center?

Instead of using width (which is a suggestion when using flexbox), you could use flex: 0 0 230px; which means:

  • 0 = don't grow (shorthand for flex-grow)
  • 0 = don't shrink (shorthand for flex-shrink)
  • 230px = start at 230px (shorthand for flex-basis)

which means: always be 230px.

See fiddle, thanks @TylerH

Oh, and you don't need the justify-content and align-items here.

img {
    max-width: 100%;
}
#container {
    display: flex;
    x-justify-content: space-around;
    x-align-items: stretch;
    max-width: 1200px;
}
.column.left {
    width: 230px;
    flex: 0 0 230px;
}
.column.right {
    width: 230px;
    flex: 0 0 230px;
    border-left: 1px solid #eee;
}
.column.center {
    border-left: 1px solid #eee;
}

Can you put two conditions in an xslt test attribute?

From XML.com:

Like xsl:if instructions, xsl:when elements can have more elaborate contents between their start- and end-tags—for example, literal result elements, xsl:element elements, or even xsl:if and xsl:choose elements—to add to the result tree. Their test expressions can also use all the tricks and operators that the xsl:if element's test attribute can use, such as and, or, and function calls, to build more complex boolean expressions.

How to play a sound using Swift?

Game style:

file Sfx.swift

import AVFoundation

public let sfx = Sfx.shared
public final class Sfx: NSObject {
    
    static let shared = Sfx()
    
    var apCheer: AVAudioPlayer? = nil
    
    private override init() {
        guard let s = Bundle.main.path(forResource: "cheer", ofType: "mp3") else {
            return  print("Sfx woe")
        }
        do {
            apComment = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: s))
        } catch {
            return  print("Sfx woe")
        }
    }
    
    func cheer() { apCheer?.play() }
    func plonk() { apPlonk?.play() }
    func crack() { apCrack?.play() } .. etc
}

Anywhere at all in code

sfx.explosion()
sfx.cheer()

check if a file is open in Python

I assume that you're writing to the file, then close it (so the user can open it in Excel), and then, before re-opening it for append/write operations, you want to check that the file isn't still open in Excel?

This is how you could do that:

while True:   # repeat until the try statement succeeds
    try:
        myfile = open("myfile.csv", "r+") # or "a+", whatever you need
        break                             # exit the loop
    except IOError:
        input("Could not open file! Please close Excel. Press Enter to retry.")
        # restart the loop

with myfile:
    do_stuff()

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

How can I convert NSDictionary to NSData and vice versa?

Use NSJSONSerialization:

NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
                                                             options:NSJSONReadingAllowFragments
                                                               error:&error];

The latest returns id, so its a good idea to check the returned object type after you cast (here i casted to NSDictionary).

Simplest way to throw an error/exception with a custom message in Swift 2?

@nick-keets's solution is most elegant, but it did break down for me in test target with the following compile time error:

Redundant conformance of 'String' to protocol 'Error'

Here's another approach:

struct RuntimeError: Error {
    let message: String

    init(_ message: String) {
        self.message = message
    }

    public var localizedDescription: String {
        return message
    }
}

And to use:

throw RuntimeError("Error message.")

Today's Date in Perl in MM/DD/YYYY format

If you like doing things the hard way:

my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon)  == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";

Update Item to Revision vs Revert to Revision

Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent. This is used to test a specific rev purpose, if your test has done, you can use this command to test another rev or use SVN Update to get HEAD

If you want to undo an earlier change permanently, use Revert to this revision instead.

-- from TSVN help doc

If you Update your working copy to an earlier rev, this is only affect your own working copy, after you do some change, and want to commit, you will fail,TSVN will alert you to update your WC to latest revision first If you Revert to a rev, you can commit to repository.everyone will back to the rev after they do an update.

Printing a 2D array in C

...
for(int i=0;i<3;i++){ //Rows
for(int j=0;j<5;j++){ //Cols
 printf("%<...>\t",var);
}
printf("\n");
}
...

considering that <...> would be d,e,f,s,c... etc datatype... X)

sudo: docker-compose: command not found

I will leave this here as a possible fix, worked for me at least and might help others. Pretty sure this would be a linux only fix.

I decided to not go with the pip install and go with the github version (option one on the installation guide).

Instead of placing the copied docker-compose directory into /usr/local/bin/docker-compose from the curl/github command, I went with /usr/bin/docker-compose which is the location of Docker itself and will force the program to run in root. So it works in root and sudo but now won't work without sudo so the opposite effect which is what you want to run it as a user anyways.

Passing parameters to JavaScript files

If you need a way that passes CSP check (which prohibits unsafe-inline) then you have to use nonce method to add a unique value to both the script and the CSP directive or write your values into the html and read them again.

Nonce method for express.js:

const uuidv4 = require('uuid/v4')

app.use(function (req, res, next) {
  res.locals.nonce = uuidv4()
  next()
})

app.use(csp({
  directives: {
    scriptSrc: [
      "'self'",
      (req, res) => `'nonce-${res.locals.nonce}'`  // 'nonce-614d9122-d5b0-4760-aecf-3a5d17cf0ac9'
    ]
  }
}))

app.use(function (req, res) {
  res.end(`<script nonce="${res.locals.nonce}">alert(1 + 1);</script>`)
})

or write values to html method. in this case using Jquery:

<div id="account" data-email="{{user.email}}"></div>
...


$(document).ready(() => {
    globalThis.EMAIL = $('#account').data('email');
}

How to fix "could not find a base address that matches schema http"... in WCF

There should be a way to solve this pretty easily with external config sections and an extra deployment step that drops a deployment specific external .config file into a known location. We typically use this solution to handle the different server configurations for our different deployment environments (Staging, QA, production, etc) with our "dev box" being the default if no special copy occurs.

What key shortcuts are to comment and uncomment code?

Use the keys CtrlK,C to comment out the line and CtrlK,U to uncomment the line.

CSS: background image on background color

You can also use short trick to use image and color both like this :-

body {
     background:#000 url('images/checked.png');
 }

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

Can a constructor in Java be private?

Can a constructor be private? How is a private constructor useful?

Yes it can. I consider this another example of it being useful:

//... ErrorType.java
public enum ErrorType {
    X,
    Y,
    Z
}

//... ErrorTypeException.java
import java.util.*;
import java.lang.*;
import java.io.*;

//Translates ErrorTypes only
abstract public class ErrorTypeException extends Exception {
    private ErrorTypeException(){}

    //I don't want to expose thse
    static private class Xx extends ErrorTypeException {}
    static private class Yx extends ErrorTypeException {}
    static private class Zx extends ErrorTypeException {}

    // Want translation without exposing underlying type
    public static Exception from(ErrorType errorType) {
        switch (errorType) {
            case X:
                return new Xx();    
            case Y:
                return new Yx();
            default:
                return new Zx();
        }
    }

    // Want to get hold of class without exposing underlying type
    public static Class<? extends ErrorTypeException> toExceptionClass(ErrorType errorType) {
        switch (errorType) {
            case X:
                return Xx.class;    
            case Y:
                return Yx.class;
            default:
                return Zx.class;
        }
    }
}

In the case here above, it prevents the abstract class from being instantiated by any derived class other than it's static inner classes. Abstract classes cannot be final, but in this case the private constructor makes it effectively final to all classes that aren't inner classes

Checking Value of Radio Button Group via JavaScript?

To get the value you would do this:

document.getElementById("genderf").value;

But to check, whether the radio button is checked or selected:

document.getElementById("genderf").checked;

How can I create numbered map markers in Google Maps V3?

Based on @dave1010 answer but with updated https links.

Numbered marker:

https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000

Text marker:

https://chart.googleapis.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|Marker

How to print a debug log?

You can also write to a file like this:

$logFilePath = '../logs/debug.text';
ob_start();

// if you want to concatenate:
if (file_exists($logFilePath)) {
    include($logFilePath);
}
// for timestamp
$currentTime = date(DATE_RSS);

// echo log statement(s) here
echo "\n\n$currentTime - [log statement here]";

$logFile = fopen($logFilePath, 'w');
fwrite($logFile, ob_get_contents());
fclose($logFile);
ob_end_flush();

Make sure the proper permissions are set so php can access and write to the file (775).

Using %f with strftime() in Python to get microseconds

If you want an integer, try this code:

import datetime
print(datetime.datetime.now().strftime("%s%f")[:13])

Output:

1545474382803

Django optional url parameters

Django > 2.0 version:

The approach is essentially identical with the one given in Yuji 'Tomita' Tomita's Answer. Affected, however, is the syntax:

# URLconf
...

urlpatterns = [
    path(
        'project_config/<product>/',
        views.get_product, 
        name='project_config'
    ),
    path(
        'project_config/<product>/<project_id>/',
        views.get_product,
        name='project_config'
    ),
]


# View (in views.py)
def get_product(request, product, project_id='None'):
    # Output the appropriate product
    ...

Using path() you can also pass extra arguments to a view with the optional argument kwargs that is of type dict. In this case your view would not need a default for the attribute project_id:

    ...
    path(
        'project_config/<product>/',
        views.get_product,
        kwargs={'project_id': None},
        name='project_config'
    ),
    ...

For how this is done in the most recent Django version, see the official docs about URL dispatching.

refresh div with jquery

I want to just refresh the div, without refreshing the page ... Is this possible?

Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.

If you just want the graphical fade-in effect, simply remove the .html(data) call:

$("#panel").hide().fadeIn('fast');

Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/

It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.

html:

<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?

javascript:

$("#changePanel").click(function() {
    var data = "foobar";
    $("#panel").hide().html(data).fadeIn('fast');
});?

css:

div {
    padding: 1em;
    background-color: #00c000;
}

input {
    padding: .25em 1em;
}?

Using R to list all files with a specified extension

Peg the pattern to find "\\.dbf" at the end of the string using the $ character:

list.files(pattern = "\\.dbf$")

How to round up a number to nearest 10?

We can "cheat" via round with

$rounded = round($roundee / 10) * 10;

We can also avoid going through floating point division with

function roundToTen($roundee)
{
  $r = $roundee % 10;
  return ($r <= 5) : $roundee - $r : $roundee + (10 - $r);
}

Edit: I didn't know (and it's not well documented on the site) that round now supports "negative" precision, so you can more easily use

$round = round($roundee, -1);

Edit again: If you always want to round up, you can try

function roundUpToTen($roundee)
{
  $r = $roundee % 10;
  if ($r == 0)
    return $roundee;
  return $roundee + 10 - $r;    
}

Set background image in CSS using jquery

Use :

 $(this).parent().css("background-image", "url(/images/r-srchbg_white.png) no-repeat;");

instead of

 $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat;");

More examples you cand see here

Pause Console in C++ program

(My answer is partially based on that from Yoank, and partially on a comment by Justin Time on another question.)

cout << endl << "Press <Enter> to continue...";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.get();

How to add background-image using ngStyle (angular2)?

Use Instead

[ngStyle]="{'background-image':' url(' + instagram?.image + ')'}"

How to read a file in other directory in python

Looks like you are trying to open a directory for reading as if it's a regular file. Many OSs won't let you do that. You don't need to anyway, because what you want (judging from your description) is

x_file = open(os.path.join(direct, "5_1.txt"), "r")  

or simply

x_file = open(direct+"/5_1.txt", "r")

Retrieve list of tasks in a queue in Celery

I've come to the conclusion the best way to get the number of jobs on a queue is to use rabbitmqctl as has been suggested several times here. To allow any chosen user to run the command with sudo I followed the instructions here (I did skip editing the profile part as I don't mind typing in sudo before the command.)

I also grabbed jamesc's grep and cut snippet and wrapped it up in subprocess calls.

from subprocess import Popen, PIPE
p1 = Popen(["sudo", "rabbitmqctl", "list_queues", "-p", "[name of your virtula host"], stdout=PIPE)
p2 = Popen(["grep", "-e", "^celery\s"], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(["cut", "-f2"], stdin=p2.stdout, stdout=PIPE)
p1.stdout.close()
p2.stdout.close()
print("number of jobs on queue: %i" % int(p3.communicate()[0]))

Android: Reverse geocoding - getFromLocation

It looks like there's two things happening here.

1) You've missed the new keyword from before calling the constructor.

2) The parameter you're passing in to the Geocoder constructor is incorrect. You're passing in a Locale where it's expecting a Context.

There are two Geocoder constructors, both of which require a Context, and one also taking a Locale:

Geocoder(Context context, Locale locale)
Geocoder(Context context)

Solution

Modify your code to pass in a valid Context and include new and you should be good to go.

Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());   
List<Address> myList = myLocation.getFromLocation(latPoint, lngPoint, 1);

Note

If you're still having problems it may be a permissioning issue. Geocoding implicitly uses the Internet to perform the lookups, so your application will require an INTERNET uses-permission tag in your manifest.

Add the following uses-permission node within the manifest node of your manifest.

<uses-permission android:name="android.permission.INTERNET" />

Find Number of CPUs and Cores per CPU using Command Prompt

Based upon your comments - your path statement has been changed/is incorrect or the path variable is being incorrectly used for another purpose.

Avoiding "resource is out of sync with the filesystem"

You can enable this in Window - Preferences - General - Workspace - Refresh Automatically (called Refresh using native hooks or polling in newer builds)

Eclipse Preferences "Refresh using native hooks or polling" - Screenshot

The only reason I can think why this isn't enabled by default is performance related.

For example, refreshing source folders automatically might trigger a build of the workspace. Perhaps some people want more control over this.

There is also an article on the Eclipse site regarding auto refresh.

Basically, there is no external trigger that notifies Eclipse of files changed outside the workspace. Rather a background thread is used by Eclipse to monitor file changes that can possibly lead to performance issues with large workspaces.

How can I initialize C++ object member variables in the constructor?

I know this is 5 years later, but the replies above don't address what was wrong with your software. (Well, Yuushi's does, but I didn't realise until I had typed this - doh!). They answer the question in the title How can I initialize C++ object member variables in the constructor? This is about the other questions: Am I using the right approach but the wrong syntax? Or should I be coming at this from a different direction?

Programming style is largely a matter of opinion, but an alternative view to doing as much as possible in a constructor is to keep constructors down to a bare minimum, often having a separate initialization function. There is no need to try to cram all initialization into a constructor, never mind trying to force things at times into the constructors initialization list.

So, to the point, what was wrong with your software?

private:
    ThingOne* ThingOne;
    ThingTwo* ThingTwo;

Note that after these lines, ThingOne (and ThingTwo) now have two meanings, depending on context.

Outside of BigMommaClass, ThingOne is the class you created with #include "ThingOne.h"

Inside BigMommaClass, ThingOne is a pointer.

That is assuming the compiler can even make sense of the lines and doesn't get stuck in a loop thinking that ThingOne is a pointer to something which is itself a pointer to something which is a pointer to ...

Later, when you write

this->ThingOne = ThingOne(100);
this->ThingTwo = ThingTwo(numba1, numba2);

bear in mind that inside of BigMommaClass your ThingOne is a pointer.

If you change the declarations of the pointers to include a prefix (p)

private:
    ThingOne* pThingOne;
    ThingTwo* pThingTwo;

Then ThingOne will always refer to the class and pThingOne to the pointer.

It is then possible to rewrite

this->ThingOne = ThingOne(100);
this->ThingTwo = ThingTwo(numba1, numba2);

as

pThingOne = new ThingOne(100);
pThingTwo = new ThingTwo(numba1, numba2);

which corrects two problems: the double meaning problem, and the missing new. (You can leave this-> if you like!)

With that in place, I can add the following lines to a C++ program of mine and it compiles nicely.

class ThingOne{public:ThingOne(int n){};};
class ThingTwo{public:ThingTwo(int x, int y){};};

class BigMommaClass {

    public:
            BigMommaClass(int numba1, int numba2);

    private:
            ThingOne* pThingOne;
            ThingTwo* pThingTwo;
};

BigMommaClass::BigMommaClass(int numba1, int numba2)
{
    pThingOne = new ThingOne(numba1 + numba2);
    pThingTwo = new ThingTwo(numba1, numba2);
};

When you wrote

this->ThingOne = ThingOne(100);
this->ThingTwo = ThingTwo(numba1, numba2);

the use of this-> tells the compiler that the left hand side ThingOne is intended to mean the pointer. However we are inside BigMommaClass at the time and it's not necessary.

The problem is with the right hand side of the equals where ThingOne is intended to mean the class. So another way to rectify your problems would have been to write

this->ThingOne = new ::ThingOne(100);
this->ThingTwo = new ::ThingTwo(numba1, numba2);

or simply

ThingOne = new ::ThingOne(100);
ThingTwo = new ::ThingTwo(numba1, numba2);

using :: to change the compiler's interpretation of the identifier.

How do I use CREATE OR REPLACE?

There is no create or replace table in Oracle.

You must:

DROP TABLE foo;
CREATE TABLE foo (....);

Calculate difference between two datetimes in MySQL

USE TIMESTAMPDIFF MySQL function. For example, you can use:

SELECT TIMESTAMPDIFF(SECOND, '2012-06-06 13:13:55', '2012-06-06 15:20:18')

In your case, the third parameter of TIMSTAMPDIFF function would be the current login time (NOW()). Second parameter would be the last login time, which is already in the database.

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

I had tried almost all the above methods.

Finally fixed it by including the

script src="{%static 'App/js/jquery.js' %}"

just after loading the staticfiles i.e {% load staticfiles %} in base.html

Github: error cloning my private repository

On Linux, I had this error and fixed it by running sudo update-ca-certificates.

How to restore/reset npm configuration to default values?

To reset user defaults

Run this in the command line (or git bash on windows):

echo "" > $(npm config get userconfig)
npm config edit

To reset global defaults

echo "" > $(npm config get globalconfig)
npm config --global edit

If you need sudo then run this instead:

sudo sh -c 'echo "" > $(npm config get globalconfig)'

IIS AppPoolIdentity and file system write access permissions

I tried this to fix access issues to an IIS website, which manifested as something like the following in the Event Logs ? Windows ? Application:

Log Name:      Application
Source:        ASP.NET 4.0.30319.0
Date:          1/5/2012 4:12:33 PM
Event ID:      1314
Task Category: Web Event
Level:         Information
Keywords:      Classic
User:          N/A
Computer:      SALTIIS01

Description:
Event code: 4008 
Event message: File authorization failed for the request. 
Event time: 1/5/2012 4:12:33 PM 
Event time (UTC): 1/6/2012 12:12:33 AM 
Event ID: 349fcb2ec3c24b16a862f6eb9b23dd6c 
Event sequence: 7 
Event occurrence: 3 
Event detail code: 0 

Application information: 
    Application domain: /LM/W3SVC/2/ROOT/Application/SNCDW-19-129702818025409890 
    Trust level: Full 
    Application Virtual Path: /Application/SNCDW 
    Application Path: D:\Sites\WCF\Application\SNCDW\ 
    Machine name: SALTIIS01 

Process information: 
    Process ID: 1896 
    Process name: w3wp.exe 
    Account name: iisservice 

Request information: 
    Request URL: http://webservicestest/Application/SNCDW/PC.svc 
    Request path: /Application/SNCDW/PC.svc 
    User host address: 10.60.16.79 
    User: js3228 
    Is authenticated: True 
    Authentication Type: Negotiate 
    Thread account name: iisservice 

In the end I had to give the Windows Everyone group read access to that folder to get it to work properly.

Jquery, checking if a value exists in array or not

If you want to do it using .map() or just want to know how it works you can do it like this:

var added=false;
$.map(arr, function(elementOfArray, indexInArray) {
 if (elementOfArray.id == productID) {
   elementOfArray.price = productPrice;
   added = true;
 }
}
if (!added) {
  arr.push({id: productID, price: productPrice})
}

The function handles each element separately. The .inArray() proposed in other answers is probably the more efficient way to do it.

How do I create a self-signed certificate for code signing on Windows?

As of PowerShell 4.0 (Windows 8.1/Server 2012 R2) it is possible to make a certificate in Windows without makecert.exe.

The commands you need are New-SelfSignedCertificate and Export-PfxCertificate.

Instructions are in Creating Self Signed Certificates with PowerShell.

Java - Relative path of a file in a java web application

Many popular Java webapps, including Jenkins and Nexus, use this mechanism:

  1. Optionally, check a servlet context-param / init-param. This allows configuring multiple webapp instances per servlet container, using context.xml which can be done by modifying the WAR or by changing server settings (in case of Tomcat).

  2. Check an environment variable (using System.getenv), if it is set, then use that folder as your application data folder. e.g. Jenkins uses JENKINS_HOME and Nexus uses PLEXUS_NEXUS_WORK. This allows flexible configuration without any changes to WAR.

  3. Otherwise, use a subfolder inside user's home folder, e.g. $HOME/.yourapp. In Java code this will be:

    final File appFolder = new File(System.getProperty("user.home"), ".yourapp");
    

How do I execute a PowerShell script automatically using Windows task scheduler?

  1. Open the created task scheduler

  2. switch to the “Action” tab and select your created “Action”

  3. In the Edit section, using the browser you could select powershell.exe in your system32\WindowsPowerShell\v1.0 folder.

       Example -C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    
  4. Next, in the ‘Add arguments’ -File parameter, paste your script file path in your system.

        Example – c:\GetMFAStatus.ps1
    

This blog might help you to automate your Powershell scripts with windows task scheduler

Javascript split regex question

you could just use

date.split(/-/);

or

date.split('-');

What is [Serializable] and when should I use it?

What is it?

When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.

Uses for Serialization

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.

Apply SerializableAttribute to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute even if the class also implements the ISerializable interface to control the serialization process.

All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute to that field.

See MSDN for more details.

Edit 1

Any reason to not mark something as serializable

When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Get root password for Google Cloud Engine VM

This work at least in the Debian Jessie image hosted by Google:

The way to enable to switch from you regular to the root user (AKA “super user”) after authentificating with your Google Computer Engine (GCE) User in the local environment (your Linux server in GCE) is pretty straight forward, in fact it just involves just one command to enable it and another every time to use it:

$ sudo passwd
Enter the new UNIX password: <your new root password>
Retype the new UNIX password: <your new root password>
passwd: password updated successfully

After executing the previous command and once logged with your GCE User you will be able to switch to root anytime by just entering the following command:

$ su
Password: <your newly created root password>
root@intance:/#

As we say in economics “caveat emptor” or buyer be aware: Using the root user is far from a best practice in system’s administration. Using it can be the cause a lot of trouble, from wiping everything in your drives and boot disks without a hiccup to many other nasty stuff that would be laborious to backtrack, troubleshoot and rebuilt. On the other hand, I have never met a SysAdmin that doesn’t think he knows better and root more than he should.

REMEMBER: We humans are programmed in such a way that given enough time at one at some point or another are going to press enter without taking into account that we have escalated to root and I can assure you that it will great source of pain, regret and extra work. PLEASE USE ROOT PRIVILEGES SPARSELY AND WITH EXTREME CARE.

Having said all the boring stuff, Have fun, live on the edge, life is short, you only get to live it once, the more you break the more you learn.

Android - get children inside a View?

If you not only want to get all direct children but all children's children and so on, you have to do it recursively:

private ArrayList<View> getAllChildren(View v) {

    if (!(v instanceof ViewGroup)) {
        ArrayList<View> viewArrayList = new ArrayList<View>();
        viewArrayList.add(v);
        return viewArrayList;
    }

    ArrayList<View> result = new ArrayList<View>();

    ViewGroup vg = (ViewGroup) v;
    for (int i = 0; i < vg.getChildCount(); i++) {

        View child = vg.getChildAt(i);

        ArrayList<View> viewArrayList = new ArrayList<View>();
        viewArrayList.add(v);
        viewArrayList.addAll(getAllChildren(child));

        result.addAll(viewArrayList);
    }
    return result;
}

To use the result you could do something like this:

    // check if a child is set to a specific String
    View myTopView;
    String toSearchFor = "Search me";
    boolean found = false;
    ArrayList<View> allViewsWithinMyTopView = getAllChildren(myTopView);
    for (View child : allViewsWithinMyTopView) {
        if (child instanceof TextView) {
            TextView childTextView = (TextView) child;
            if (TextUtils.equals(childTextView.getText().toString(), toSearchFor)) {
                found = true;
            }
        }
    }
    if (!found) {
        fail("Text '" + toSearchFor + "' not found within TopView");
    }

JavaScript global event mechanism

I would recommend giving Trackjs a try.

It's error logging as a service.

It's amazingly simple to set up. Just add one <script> line to each page and that's it. This also means it will be amazingly simple to remove if you decide you don't like it.

There are other services like Sentry (which is open-source if you can host your own server), but it doesn't do what Trackjs does. Trackjs records the user's interaction between their browser and your webserver so that you can actually trace the user steps that led to the error, as opposed to just a file and line number reference (and maybe stack trace).

Auto reloading python Flask app upon code changes

Flask applications can optionally be executed in debug mode. In this mode, two very convenient modules of the development server called the reloader and the debugger are enabled by default. When the reloader is enabled, Flask watches all the source code files of your project and automatically restarts the server when any of the files are modified.

By default, debug mode is disabled. To enable it, set a FLASK_DEBUG=1 environment variable before invoking flask run:

(venv) $ export FLASK_APP=hello.py for Windows use > set FLASK_APP=hello.py

(venv) $ export FLASK_DEBUG=1 for Windows use > set FLASK_DEBUG=1

(venv) $ flask run

* Serving Flask app "hello"
* Forcing debug mode on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 273-181-528

Having a server running with the reloader enabled is extremely useful during development, because every time you modify and save a source file, the server automatically restarts and picks up the change.

Rounding to two decimal places in Python 2.7?

Rounding up to the next 0.05, I would do this way:

def roundup(x):
    return round(int(math.ceil(x / 0.05)) * 0.05,2)

Getting the current date in SQL Server?

As you are using SQL Server 2008, go with Martin's answer.

If you find yourself needing to do it in SQL Server 2005 where you don't have access to the Date column type, I'd use:

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

SQLFiddle

HashMap: One Key, multiple Values

I found the blog on random search, i think this will help for doing this: http://tomjefferys.blogspot.com.tr/2011/09/multimaps-google-guava.html

public class MutliMapTest {
public static void main(String... args) {
   Multimap<String, String> myMultimap = ArrayListMultimap.create();

   // Adding some key/value
   myMultimap.put("Fruits", "Bannana");
   myMultimap.put("Fruits", "Apple");
   myMultimap.put("Fruits", "Pear");
   myMultimap.put("Vegetables", "Carrot");

   // Getting the size
   int size = myMultimap.size();
   System.out.println(size);  // 4

   // Getting values
   Collection<String> fruits = myMultimap.get("Fruits");
   System.out.println(fruits); // [Bannana, Apple, Pear]

   Collection<string> vegetables = myMultimap.get("Vegetables");
   System.out.println(vegetables); // [Carrot]

   // Iterating over entire Mutlimap
   for(String value : myMultimap.values()) {
      System.out.println(value);
   }

   // Removing a single value
   myMultimap.remove("Fruits","Pear");
   System.out.println(myMultimap.get("Fruits")); // [Bannana, Pear]

   // Remove all values for a key
   myMultimap.removeAll("Fruits");
   System.out.println(myMultimap.get("Fruits")); // [] (Empty Collection!)
}
}

Very Long If Statement in Python

Here is the example directly from PEP 8 on limiting line length:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

JavaScript backslash (\) in variables is causing an error

You have to escape each \ to be \\:

var ttt = "aa ///\\\\\\";

Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.

because you had to show a message to user that user can't give a name which has (\) character.

I think the scenario is like:

var user_input_name = document.getElementById('the_name').value;

Then the asker wants to check if user_input_name contains any [\]. If so, then alert the user.

If user enters [aa ///\] in HTML input box, then if you alert(user_input_name), you will see [aaa ///\]. You don't need to escape, i.e. replace [\] to be [\\] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters in JavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.

I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:

var ttt = "aa ///\";

Hence, we assume the asker having problem with escaping.

If you want to simulate, you code must be valid at first place.

var ttt = "aa ///\\"; // <- This is correct
// var ttt = "aa ///\"; // <- This is not.

alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?

Now, you only need to do is

var user_input_name = document.getElementById('the_name').value;
if (user_input_name.indexOf("\\") >= 0) { // There is a [\] in the string
  alert("\\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
  do_something_else();
  }

Edit: I used [] to quote text to be shown, so it would be less confused than using "".

How can I produce an effect similar to the iOS 7 blur view?

You can find your solution from apple's DEMO in this page: WWDC 2013 , find out and download UIImageEffects sample code.

Then with @Jeremy Fox's code. I changed it to

- (UIImage*)getDarkBlurredImageWithTargetView:(UIView *)targetView
{
    CGSize size = targetView.frame.size;

    UIGraphicsBeginImageContext(size);
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(c, 0, 0);
    [targetView.layer renderInContext:c]; // view is the view you are grabbing the screen shot of. The view that is to be blurred.
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return [image applyDarkEffect];
}

Hope this will help you.

iOS application: how to clear notifications?

When you have repeated notifications at future, you do not want to cancel those notifications, you can clear the item in notification center by:

func clearNotificationCenter() {
    UIApplication.sharedApplication().applicationIconBadgeNumber = 1
    UIApplication.sharedApplication().applicationIconBadgeNumber = 0
}

You cannot clear notification when your app is open in the foreground by calling the method below immediately after receiving local notification, otherwise you will receive tens of hundreds of notifications. Maybe because the same notification apply again, and now is the time to fire, so you keep fire, apply again, fire, apply....:

[UIApplication sharedApplication].scheduledLocalNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

How to check if an object is defined?

If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.

If you have an instance, and you want to ensure it's not null, simply check for null:

if (value != null)
{
    // it's not null. 
}

Website screenshots

LAST EDIT: after 7 years I'm still getting upvotes for this answer, but I guess this one is now much more accurate.


Sure you can, but you'll need to render the page with something. If you really want to only use php, I suggest you HTMLTOPS, which renders the page and outputs it in a ps file (ghostscript), then, convert it in a .jpg, .png, .pdf.. can be little slower with complex pages (and don't support all the CSS).

Else, you can use wkhtmltopdf to output a html page in pdf, jpg, whatever.. Accept CSS2.0, use the webkit (safari's wrapper) to render the page.. so should be fine. You have to install it on your server, as well..

UPDATE Now, with new HTML5 and JS feature, is also possible to render the page into a canvas object using JavaScript. Here a nice library to do that: Html2Canvas and here is an implementation by the same author to get a feedback like G+. Once you have rendered the dom into the canvas, you can then send to the server via ajax and save it as a jpg.

EDIT: You can use the imagemagick tool for transforming pdf to png. My version of wkhtmltopdf does not support images. E.g. convert html.pdf -append html.png.

EDIT: This small shell script gives a simple / but working usage example on linux with php5-cli and the tools mentioned above.

EDIT: i noticed now that the wkhtmltopdf team is working on another project: wkhtmltoimage, that gives you the jpg directly

How to pass Multiple Parameters from ajax call to MVC Controller

I did that with helping from this question

jquery get querystring from URL

so let see how we will use this function

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

and now just use it in Ajax call

"ajax": {
    url: '/Departments/GetAllDepartments/',                     
    type: 'GET',                       
    dataType: 'json',                       
    data: getUrlVars()// here is the tricky part
},

thats all, but if you want know how to use this function or not send all the query string parameters back to actual answer

How to change the minSdkVersion of a project?

Set the min SDK version within your project's AndroidManifest.xml file:

<uses-sdk android:minSdkVersion="4"/>

What exactly causes the crash? Iron out all crashes/bugs in minimum version and then test in higher versions.

Tomcat manager/html is not available?

In my case, the folder was _Manager. After I renamed it to Manager it worked.

Now, I see login popup and I enter credentials from conf/tomcat-users.xml, It all works fine.

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I had the same problem. Please try this:

Sub deleteConn(xlBook)
    For Each Cn In xlBook.Connections
        Cn.Delete
    Next Cn

    For Each xlsheet In xlBook.Worksheets
        For Each Qt In xlsheet.QueryTables
            Qt.Delete
        Next Qt
    Next xlsheet

End Sub

jQuery: get parent, parent id?

Here are 3 examples:

_x000D_
_x000D_
$(document).on('click', 'ul li a', function (e) {_x000D_
    e.preventDefault();_x000D_
_x000D_
    var example1 = $(this).parents('ul:first').attr('id');_x000D_
    $('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');_x000D_
_x000D_
    var example2 = $(this).parents('ul:eq(0)').attr('id');_x000D_
    $('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');_x000D_
  _x000D_
    var example3 = $(this).closest('ul').attr('id');_x000D_
    $('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');_x000D_
  _x000D_
  _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<ul id ="myList">_x000D_
  <li><a href="www.example.com">Click here</a></li>_x000D_
</ul>_x000D_
_x000D_
<div id="results">_x000D_
  <h1>Results:</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Let me know whether it was helpful.

Docker CE on RHEL - Requires: container-selinux >= 2.9

Just install selinux latest version to fix it:
sudo yum install -y http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.107-3.el7.noarch.rpm

More versions at http://mirror.centos.org/centos/7/extras/x86_64/Packages/

Older versions of 2.9: http://ftp.riken.jp/Linux/cern/centos/7/extras/x86_64/Packages/

How should I use Outlook to send code snippets?

If you are using Outlook 2010, you can define your own style and select your formatting you want, in the Format options there is one option for Language, here you can specify the language and specify whether you want spell checker to ignore the text with this style.

With this style you can now paste the code as text and select your new style. Outlook will not correct the text and will not perform the spell check on it.

Below is the summary of the style I have defined for emailing the code snippets.

Do not check spelling or grammar, Border:
Box: (Single solid line, Orange,  0.5 pt Line width)
Pattern: Clear (Custom Color(RGB(253,253,217))), Style: Linked, Automatically update, Quick Style
Based on: HTML Preformatted

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

You don't need hibernate-entitymanager-xxx.jar, because of you use a Hibernate session approach (not JPA). You need to close the SessionFactory too and rollback a transaction on errors. But, the problem, of course, is not with those.

This is returned by a database

#
org.postgresql.util.PSQLException: FATAL: password authentication failed for user "sa"
#

Looks like you've provided an incorrect username or (and) password.

How to fix "containing working copy admin area is missing" in SVN?

I just did 'svn revert /blabla' and it worked, the folder is back and I can svn delete it

Filter items which array contains any of given values

You should use Terms Query

{
    "query" : {
        "terms" : {
            "tags" : ["c", "d"]
        }
    }
}

Setting the selected value on a Django forms.ChoiceField

I ran into this problem as well, and figured out that the problem is in the browser. When you refresh the browser is re-populating the form with the same values as before, ignoring the checked field. If you view source, you'll see the checked value is correct. Or put your cursor in your browser's URL field and hit enter. That will re-load the form from scratch.

The name 'model' does not exist in current context in MVC3

There is also another reason. In my case, I had copy an index.cshtml file to web root folder (outside the Views folder) as a backup from remote server.

So, I kept changing my /views/web.config, kept changing my /views/home/index.cshtml and error kept happening... until found out the /index.cshtml outside the views folder, deleted it and sure, it all went back to normal!

How to install multiple python packages at once using pip

Complementing the other answers, you can use the option --no-cache-dir to disable caching in pip. My virtual machine was crashing when installing many packages at once with pip install -r requirements.txt. What solved for me was:

pip install --no-cache-dir -r requirements.txt

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

Generate HTML table from 2D JavaScript array

Here's a version using template literals. It maps over the data creating new arrays of strings build from the template literals, and then adds them to the document with insertAdjacentHTML:

_x000D_
_x000D_
let data = [_x000D_
  ['Title', 'Artist', 'Duration', 'Created'],_x000D_
  ['hello', 'me', '2', '2019'],_x000D_
  ['ola', 'me', '3', '2018'],_x000D_
  ['Bob', 'them', '4.3', '2006']_x000D_
];_x000D_
_x000D_
function getCells(data, type) {_x000D_
  return data.map(cell => `<${type}>${cell}</${type}>`).join('');_x000D_
}_x000D_
_x000D_
function createBody(data) {_x000D_
  return data.map(row => `<tr>${getCells(row, 'td')}</tr>`).join('');_x000D_
}_x000D_
_x000D_
function createTable(data) {_x000D_
  const [headings, ...rows] = data;_x000D_
  return `_x000D_
    <table>_x000D_
      <thead>${getCells(headings, 'th')}</thead>_x000D_
      <tbody>${createBody(rows)}</tbody>_x000D_
    </table>_x000D_
  `;_x000D_
}_x000D_
_x000D_
document.body.insertAdjacentHTML('beforeend', createTable(data));
_x000D_
table { border-collapse: collapse; }_x000D_
tr { border: 1px solid #dfdfdf; }_x000D_
th, td { padding: 2px 5px 2px 5px;}
_x000D_
_x000D_
_x000D_

Allow only pdf, doc, docx format for file upload?

You can simply make it by REGEX:

Form:

<form method="post" action="" enctype="multipart/form-data">
    <div class="uploadExtensionError" style="display: none">Only PDF allowed!</div>
    <input type="file" name="item_file" />
    <input type="submit" id='submit' value="submit"/>
</form>

And java script validation:

<script>
    $('#submit').click(function(event) {
        var val = $('input[type=file]').val().toLowerCase();
        var regex = new RegExp("(.*?)\.(pdf|docx|doc)$");
        if(!(regex.test(val))) {
            $('.uploadExtensionError').show();
            event.preventDefault();
        }
    });
</script>

Cheers!

html script src="" triggering redirection with button

First you are linking the file that is here:

<script src="../Script/login.js"> 

Which would lead the website to a file in the Folder Script, but then in the second paragraph you are saying that the folder name is

and also i have onother folder named scripts that contains the the following login.js file

So, this won't work! Because you are not accessing the correct file. To do that please write the code as

<script src="/script/login.js"></script>

Try removing the .. from the beginning of the code too.

This way, you'll reach the js file where the function would run!

Just to make sure:

Just to make sure that the files are attached the HTML DOM, then please open Developer Tools (F12) and in the network workspace note each request that the browser makes to the server. This way you will learn which files were loaded and which weren't, and also why they were not!

Good luck.

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

This error is definite mismatch between the data that is advertised in the HTTP Headers and the data transferred over the wire.

It could come from the following:

  1. Server: If a server has a bug with certain modules that changes the content but don't update the content-length in the header or just doesn't work properly. It was the case for the Node HTTP Proxy at some point (see here)

  2. Proxy: Any proxy between you and your server could be modifying the request and not update the content-length header.

As far as I know, I haven't see those problem in IIS but mostly with custom written code.

Let me know if that helps.

ActiveRecord: size vs count

The following strategies all make a call to the database to perform a COUNT(*) query.

Model.count

Model.all.size

records = Model.all
records.count

The following is not as efficient as it will load all records from the database into Ruby, which then counts the size of the collection.

records = Model.all
records.size

If your models have associations and you want to find the number of belonging objects (e.g. @customer.orders.size), you can avoid database queries (disk reads). Use a counter cache and Rails will keep the cache value up to date, and return that value in response to the size method.

How to get records randomly from the oracle database?

In summary, two ways were introduced

1) using order by DBMS_RANDOM.VALUE clause
2) using sample([%]) function

The first way has advantage in 'CORRECTNESS' which means you will never fail get result if it actually exists, while in the second way you may get no result even though it has cases satisfying the query condition since information is reduced during sampling.

The second way has advantage in 'EFFICIENT' which mean you will get result faster and give light load to your database. I was given an warning from DBA that my query using the first way gives loads to the database

You can choose one of two ways according to your interest!

Creating a JSON array in C#

You're close. This should do the trick:

new {items = new [] {
    new {name = "command" , index = "X", optional = "0"}, 
    new {name = "command" , index = "X", optional = "0"}
}}

If your source was an enumerable of some sort, you might want to do this:

new {items = source.Select(item => new 
{
    name = item.Name, index = item.Index, options = item.Optional
})};

Detect Safari using jQuery

My best solution

function getBrowserInfo() {
  const ua = navigator.userAgent; let tem;
  let M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  if (/trident/i.test(M[1])) {
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    return { name: 'IE ', version: (tem[1] || '') };
  }
  if (M[1] === 'Chrome') {
    tem = ua.match(/\bOPR\/(\d+)/);
    if (tem != null) {
      return { name: 'Opera', version: tem[1] };
    }
  }
  M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
  tem = ua.match(/version\/(\d+)/i);
  if (tem != null) {
    M.splice(1, 1, tem[1]);
  }
  return {
    name: M[0],
    version: M[1],
  };
}

getBrowserInfo();

Best implementation for Key Value Pair Data Structure?

I think what you might be after (as a literal implementation of your question), is:

public class TokenTree
{
    public TokenTree()
    {
        tree = new Dictionary<string, IDictionary<string,string>>();
    }

    IDictionary<string, IDictionary<string, string>> tree; 
}

You did actually say a "list" of key-values in your question, so you might want to swap the inner IDictionary with a:

IList<KeyValuePair<string, string>>

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I had the same error and ended up solving it by upgrading my Oracle ojdbc driver to a version compatible with the Oracle database version

How do I run a Java program from the command line on Windows?

You can compile any java source using javac in command line ; eg, javac CopyFile.java. To run : java CopyFile. You can also compile all java files using javac *.java as long as they're in the same directory

If you're having an issue resulting with "could not find or load main class" you may not have jre in your path. Have a look at this question: Could not find or load main class

Breaking out of a nested loop

C# adaptation of approach often used in C - set value of outer loop's variable outside of loop conditions (i.e. for loop using int variable INT_MAX -1 is often good choice):

for (int i = 0; i < 100; i++)
{
    for (int j = 0; j < 100; j++)
    {
        if (exit_condition)
        {
            // cause the outer loop to break:
            // use i = INT_MAX - 1; otherwise i++ == INT_MIN < 100 and loop will continue 
            i = int.MaxValue - 1;
            Console.WriteLine("Hi");
            // break the inner loop
            break;
        }
    }
    // if you have code in outer loop it will execute after break from inner loop    
}

As note in code says break will not magically jump to next iteration of the outer loop - so if you have code outside of inner loop this approach requires more checks. Consider other solutions in such case.

This approach works with for and while loops but does not work for foreach. In case of foreach you won't have code access to the hidden enumerator so you can't change it (and even if you could IEnumerator doesn't have some "MoveToEnd" method).

Acknowledgments to inlined comments' authors:
i = INT_MAX - 1 suggestion by Meta
for/foreach comment by ygoe.
Proper IntMax by jmbpiano
remark about code after inner loop by blizpasta

android.view.InflateException: Binary XML file: Error inflating class fragment

This problem arises when you have a custom class that extends a different class (in this case a view) and does not import all the constructors required by the class.

For eg : public class CustomTextView extends TextView{}

This class would have 4 constructors and if you miss out on any one it would crash. For the matter of fact I missed out the last one which was used by Lollipop added that constructor and worked fine.

HashMaps and Null values?

Its a good programming practice to avoid having null values in a Map.

If you have an entry with null value, then it is not possible to tell whether an entry is present in the map or has a null value associated with it.

You can either define a constant for such cases (Example: String NOT_VALID = "#NA"), or you can have another collection storing keys which have null values.

Please check this link for more details.

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

viewport meta tag on mobile browser,

The initial-scale property controls the zoom level when the page is first loaded. The maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out.

What's the difference between a Python module and a Python package?

Any Python file is a module, its name being the file's base name without the .py extension. A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional __init__.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file.

The distinction between module and package seems to hold just at the file system level. When you import a module or a package, the corresponding object created by Python is always of type module. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules. As an example, consider the xml package in the Python standard library: its xml directory contains an __init__.py file and four sub-directories; the sub-directory etree contains an __init__.py file and, among others, an ElementTree.py file. See what happens when you try to interactively import package/modules:

>>> import xml
>>> type(xml)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>> import xml.etree
>>> type(xml.etree)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>> import xml.etree.ElementTree
>>> type(xml.etree.ElementTree)
<type 'module'>
>>> xml.etree.ElementTree.parse
<function parse at 0x00B135B0>

In Python there also are built-in modules, such as sys, that are written in C, but I don't think you meant to consider those in your question.

How to reload the datatable(jquery) data?

You can use a simple approach...

$('YourDataTableID').dataTable()._fnAjaxUpdate();

It will refresh the data by making an ajax request with the same parameters. Very simple.

python dataframe pandas drop column using int

If you have two columns with the same name. One simple way is to manually rename the columns like this:-

df.columns = ['column1', 'column2', 'column3']

Then you can drop via column index as you requested, like this:-

df.drop(df.columns[1], axis=1, inplace=True)

df.column[1] will drop index 1.

Remember axis 1 = columns and axis 0 = rows.

How to print jquery object/array

_x000D_
_x000D_
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];_x000D_
var data = arrofobject.map(arrofobject => arrofobject);_x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

for more details please look at jQuery.map()

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

Based on responses and comments below, the following was the simple solution for my issue and THIS WORKED. Now my app, Match4app, is fully compatible with latest iOS versions!

  1. Download Xcode 10.2 from a direct link (not from App Store). (Estimated Size: ~6Gb)
  2. From the downloaded version just copy/paste the DeviceSupport/12.2 directory into "Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport"
  3. You can discard the downloaded version now (we just need the small 12.2 directory!)

Hibernate Error executing DDL via JDBC Statement

Another sneaky issue related to this is naming your columns with - instead of _.

Something like this will trigger an error at the moment your tables are getting created.

@Column(name="verification-token")

How to create text file and insert data to that file on Android

Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This is the code :

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.

Environment.getExternalStorageState()

Working with time DURATION, not time of day

I don't know how to make the chart label the axis in the format "X1 min : X2 sec", but here's another way to get durations, in the format of minutes with decimals representing seconds (.5 = 30 sec, .25 = 15 sec, etc.)

Suppose in column A you have your time data, for example in cell A1 you have 12:03:06, which your 3min 6sec data misinterpreted as 3:06 past midnight, and column B is free.

In cell B1 enter this formula: =MINUTE(A1) + SECOND(A1)/60 and hit enter/return. Grab the lower right corner of cell B2 and drag as far down as the A column goes to apply the formula to all data in col A.

Last step, be sure to highlight all of column B and set it to Number format (the application of the formula may have automatically set format to Time).

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

Most popular C# Data Structures and Collections

  • Array
  • ArrayList
  • List
  • LinkedList
  • Dictionary
  • HashSet
  • Stack
  • Queue
  • SortedList

C#.NET has a lot of different data structures, for example, one of the most common ones is an Array. However C# comes with many more basic data structures. Choosing the correct data structure to use is part of writing a well structured and efficient program.

In this article I will go over the built-in C# data structures, including the new ones introduces in C#.NET 3.5. Note that many of these data structures apply for other programming languages.

Array

The perhaps simplest and most common data structure is the array. A C# array is basically a list of objects. Its defining traits are that all the objects are the same type (in most cases) and there is a specific number of them. The nature of an array allows for very fast access to elements based on their position within the list (otherwise known as the index). A C# array is defined like this:

[object type][] myArray = new [object type][number of elements]

Some examples:

 int[] myIntArray = new int[5];
 int[] myIntArray2 = { 0, 1, 2, 3, 4 };

As you can see from the example above, an array can be intialized with no elements or from a set of existing values. Inserting values into an array is simple as long as they fit. The operation becomes costly when there are more elements than the size of the array, at which point the array needs to be expanded. This takes longer because all the existing elements must be copied over to the new, bigger array.

ArrayList

The C# data structure, ArrayList, is a dynamic array. What that means is an ArrayList can have any amount of objects and of any type. This data structure was designed to simplify the processes of adding new elements into an array. Under the hood, an ArrayList is an array whose size is doubled every time it runs out of space. Doubling the size of the internal array is a very effective strategy that reduces the amount of element-copying in the long run. We won't get into the proof of that here. The data structure is very simple to use:

    ArrayList myArrayList = new ArrayList();
    myArrayList.Add(56);
    myArrayList.Add("String");
    myArrayList.Add(new Form());

The downside to the ArrayList data structure is one must cast the retrived values back into their original type:

int arrayListValue = (int)myArrayList[0]

Sources and more info you can find here :

Debug assertion failed. C++ vector subscript out of range

this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

//assign of data in to array
for(int i=0; i<10; i++){
   arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}

the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.

How to create helper file full of functions in react native?

An alternative is to create a helper file where you have a const object with functions as properties of the object. This way you only export and import one object.

helpers.js

const helpers = {
    helper1: function(){

    },
    helper2: function(param1){

    },
    helper3: function(param1, param2){

    }
}

export default helpers;

Then, import like this:

import helpers from './helpers';

and use like this:

helpers.helper1();
helpers.helper2('value1');
helpers.helper3('value1', 'value2');

Travel/Hotel API's?

After several days of searching found the EAN API - http://developer.ean.com/ - it is a very big one, but it provides really good information. Free demos, XML\JSON format. Looks good.

Convert alphabet letters to number in Python

This is a function I used to use for this purpose. Works for both uppercase and lowercase.

def convert_char(old):
    if len(old) != 1:
        return 0
    new = ord(old)
    if 65 <= new <= 90:
        # Upper case letter
        return new - 64
    elif 97 <= new <= 122:
        # Lower case letter
        return new - 96
    # Unrecognized character
    return 0

Change hover color on a button with Bootstrap customization

The color for your buttons comes from the btn-x classes (e.g., btn-primary, btn-success), so if you want to manually change the colors by writing your own custom css rules, you'll need to change:

/*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/
.btn-primary {
    color: #fff;
    background-color: #0495c9;
    border-color: #357ebd; /*set the color you want here*/
}
.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
    color: #fff;
    background-color: #00b3db;
    border-color: #285e8e; /*set the color you want here*/
}

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

I also had the same issue when I tried to install a Windows service, in my case I managed to resolved the issue by removing blank spaces in the folder path to the service .exe, below is the command worked for me in a command prompt

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

Press ENTER to change working directory

InstallUtil.exe C:\MyService\Release\ReminderService.exe

Press ENTER

How to query first 10 rows and next time query other 10 rows from table

<html>
<head>
    <title>Pagination</title>
</head>
<body>
<?php 

    $conn = mysqli_connect('localhost','root','','northwind');
    $data_per_page = 10;
    $select = "SELECT * FROM `customers`";  
    $select_run = mysqli_query($conn, $select);
    $records = mysqli_num_rows($select_run);
    // while ($result = mysqli_fetch_array($select_run)) {      
    //     echo $result['CompanyName'] . '<br>';        
    // }
    // $records;
    echo "<br>";
    $no_of_page = ceil($records / $data_per_page);
    if(!isset($_GET['page'])){
        $page = 1;
    }else{
        $page = $_GET['page'];
    }
    $page_limit_data = ($page - 1) * 10;
    $select = "SELECT * FROM customers LIMIT " . $page_limit_data . ',' . $data_per_page ;
    $select_run = mysqli_query($conn, $select);
    while ($row_select = mysqli_fetch_array($select_run)){
        echo $row_select['CompanyName'] . '<br>' ;
    }
    for($page=1; $page<= $no_of_page; $page++){ 
        echo "<a href='pagination.php?page=$page'> $page" . ', ';   
    }
?>
<br>
<h1> Testing Limit Functions Here  </h1>
<?php 
$limit = "SELECT CompanyName From customers LIMIT 10 OFFSET 5";
$limit_run = mysqli_query($conn , $limit);
while($limit_result = mysqli_fetch_array($limit_run)){
    echo $limit_result['CompanyName'] . '<br>';
}
?>
</body>
</html>

The easiest way to transform collection to array?

If you use Guava in your project you can use Iterables::toArray.

Foo[] foos = Iterables.toArray(x, Foo.class);

Using Linq select list inside list

You have to use the SelectMany extension method or its equivalent syntax in pure LINQ.

(from model in list
 where model.application == "applicationname"
 from user in model.users
 where user.surname == "surname"
 select new { user, model }).ToList();

How to add label in chart.js for pie chart

Use ChartNew.js instead of Chart.js

...

So, I have re-worked Chart.js. Most of the changes, are associated to requests in "GitHub" issues of Chart.js.

And here is a sample http://jsbin.com/lakiyu/2/edit

var newopts = {
    inGraphDataShow: true,
    inGraphDataRadiusPosition: 2,
    inGraphDataFontColor: 'white'
}
var pieData = [
    {
        value: 30,
        color: "#F38630",
    },
    {
       value: 30,
       color: "#F34353",
    },
    {
        value: 30,
        color: "#F34353",
    }
]
var pieCtx = document.getElementById('pieChart').getContext('2d');
new Chart(pieCtx).Pie(pieData, newopts);

It even provides a GUI editor http://charts.livegap.com/

So sweet.

What is the maximum length of a URL in different browsers?

In URL as UI Jakob Nielsen recommends:

the social interface to the Web relies on email when users want to recommend Web pages to each other, and email is the second-most common way users get to new sites (search engines being the most common): make sure that all URLs on your site are less than 78 characters long so that they will not wrap across a line feed.

This is not the maximum but I'd consider this a practical maximum if you want your URL to be shared.

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

'this' is undefined in JavaScript class methods

How are you calling the start function?

This should work (new is the key)

var o = new Request(destination, stay_open);
o.start();

If you directly call it like Request.prototype.start(), this will refer to the global context (window in browsers).

Also, if this is undefined, it results in an error. The if expression does not evaluate to false.

Update: this object is not set based on declaration, but by invocation. What it means is that if you assign the function property to a variable like x = o.start and call x(), this inside start no longer refers to o. This is what happens when you do setTimeout. To make it work, do this instead:

 var o = new Request(...);
 setTimeout(function() { o.start(); }, 1000);

Correct way to find max in an Array in Swift

var numbers = [1, 2, 7, 5];    
var val = sort(numbers){$0 > $1}[0];

How to hide app title in android?

You can do it programatically:

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class ActivityName extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // remove title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
    }
}

Or you can do it via your AndroidManifest.xml file:

<activity android:name=".ActivityName"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
</activity>

Edit: I added some lines so that you can show it in fullscreen, as it seems that's what you want.

'DataFrame' object has no attribute 'sort'

Pandas Sorting 101

sort has been replaced in v0.20 by DataFrame.sort_values and DataFrame.sort_index. Aside from this, we also have argsort.

Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.

# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})    
df                                                                                                                                        
   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

Sort by Single Column

For example, to sort df by column "A", use sort_values with a single column name:

df.sort_values(by='A')

   A  B
0  a  7
3  a  5
4  b  2
1  c  9
2  c  3

If you need a fresh RangeIndex, use DataFrame.reset_index.

Sort by Multiple Columns

For example, to sort by both col "A" and "B" in df, you can pass a list to sort_values:

df.sort_values(by=['A', 'B'])

   A  B
3  a  5
0  a  7
4  b  2
2  c  3
1  c  9

Sort By DataFrame Index

df2 = df.sample(frac=1)
df2

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

You can do this using sort_index:

df2.sort_index()

   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

df.equals(df2)                                                                                                                            
# False
df.equals(df2.sort_index())                                                                                                               
# True

Here are some comparable methods with their performance:

%timeit df2.sort_index()                                                                                                                  
%timeit df2.iloc[df2.index.argsort()]                                                                                                     
%timeit df2.reindex(np.sort(df2.index))                                                                                                   

605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sort by List of Indices

For example,

idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])

This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc will do.

df.iloc[idx]

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

How to change the default docker registry from docker.io to my private registry?

It seems it won't be supported due to the fragmentation it would create within the community (i.e. two users would get different images pulling ubuntu:latest). You simply have to add the host in front of the image name. See this github issue to join the discussion.

(Note, this is not intended as an opinionated comment, just a very short summary of the discussion that can be followed in the mentioned github issue.)

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

I also encountered the same problem, I was such a solution.

First of all to be clear: provisioning profile must choose "Automatic" to debug.

If provisioning profile is "adhoc", then you can not debug, and can only export the ".ipa" file, import to iTunes for installation.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

You haven't specify version in your maven dependency file may be thats why it is not picking the latest jar
As well as you need another deppendency with slf4j-log4j12 artifact id.
Include this in your pom file

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.5.6</version>
</dependency>

Let me know if error is still not resolved
I also recomend you to see this link

How to control size of list-style-type disc in CSS?

try to use diffrent font-size for li and a

.farParentDiv ul li {
   list-style-type: disc;
   font-size:20px;
}

.farParentDiv ul li a {
   font-size:10px;
}

this saved me from using images

Time part of a DateTime Field in SQL

This will return the time-Only

For SQL Server:

SELECT convert(varchar(8), getdate(), 108)

Explanation:

getDate() is giving current date and time.
108 is formatting/giving us the required portion i.e time in this case.
varchar(8) gives us the number of characters from that portion.
Like:
If you wrote varchar(7) there, it will give you 00:00:0
If you wrote varchar(6) there, it will give you 00:00:
If you wrote varchar(15) there, it will still give you 00:00:00 because it is giving output of just time portion. SQLFiddle Demo

For MySQL:

SELECT DATE_FORMAT(NOW(), '%H:%i:%s')

SQLFiddle Demo