Programs & Examples On #Persistent storage

The persistent storage describes a mechanism, that preserves the value of a variable over the lifetime of the executed script or program.

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

Get user location by IP address

Return country

static public string GetCountry()
{
    return new WebClient().DownloadString("http://api.hostip.info/country.php");
}

Usage:

Console.WriteLine(GetCountry()); // will return short code for your country

Return info

static public string GetInfo()
{
    return new WebClient().DownloadString("http://api.hostip.info/get_json.php");
}

Usage:

Console.WriteLine(GetInfo()); 
// Example:
// {
//    "country_name":"COUNTRY NAME",
//    "country_code":"COUNTRY CODE",
//    "city":"City",
//    "ip":"XX.XXX.XX.XXX"
// }

How to update large table with millions of rows in SQL Server?

I want share my experience. A few days ago I have to update 21 million records in table with 76 million records. My colleague suggested the next variant. For example, we have the next table 'Persons':

Id | FirstName | LastName | Email            | JobTitle
1  | John      |  Doe     | [email protected]     | Software Developer
2  | John1     |  Doe1    | [email protected]     | Software Developer
3  | John2     |  Doe2    | [email protected]     | Web Designer

Task: Update persons to the new Job Title: 'Software Developer' -> 'Web Developer'.

1. Create Temporary Table 'Persons_SoftwareDeveloper_To_WebDeveloper (Id INT Primary Key)'

2. Select into temporary table persons which you want to update with the new Job Title:

INSERT INTO Persons_SoftwareDeveloper_To_WebDeveloper SELECT Id FROM
Persons WITH(NOLOCK) --avoid lock 
WHERE JobTitle = 'Software Developer' 
OPTION(MAXDOP 1) -- use only one core

Depends on rows count, this statement will take some time to fill your temporary table, but it would avoid locks. In my situation it took about 5 minutes (21 million rows).

3. The main idea is to generate micro sql statements to update database. So, let's print them:

DECLARE @i INT, @pagesize INT, @totalPersons INT
    SET @i=0
    SET @pagesize=2000
    SELECT @totalPersons = MAX(Id) FROM Persons

    while @i<= @totalPersons
    begin
    Print '
    UPDATE persons 
      SET persons.JobTitle = ''ASP.NET Developer''
      FROM  Persons_SoftwareDeveloper_To_WebDeveloper tmp
      JOIN Persons persons ON tmp.Id = persons.Id
      where persons.Id between '+cast(@i as varchar(20)) +' and '+cast(@i+@pagesize as varchar(20)) +' 
        PRINT ''Page ' + cast((@i / @pageSize) as varchar(20))  + ' of ' + cast(@totalPersons/@pageSize as varchar(20))+'
     GO
     '
     set @i=@i+@pagesize
    end

After executing this script you will receive hundreds of batches which you can execute in one tab of MS SQL Management Studio.

4. Run printed sql statements and check for locks on table. You always can stop process and play with @pageSize to speed up or speed down updating(don't forget to change @i after you pause script).

5. Drop Persons_SoftwareDeveloper_To_AspNetDeveloper. Remove temporary table.

Minor Note: This migration could take a time and new rows with invalid data could be inserted during migration. So, firstly fix places where your rows adds. In my situation I fixed UI, 'Software Developer' -> 'Web Developer'.

Sleep function in C++

For Windows:

#include "windows.h" 
Sleep(10);

For Unix:

#include <unistd.h>
usleep(10)

Properties file with a list as the value for an individual key

If this is for some configuration file processing, consider using Apache configuration. https://commons.apache.org/proper/commons-configuration/javadocs/v1.10/apidocs/index.html?org/apache/commons/configuration/PropertiesConfiguration.html It has way to multiple values to single key- The format is bit different though

key=value1,value2,valu3 gives three values against same key.

python int( ) function

As the other answers have mentioned, the int operation will crash if the string input is not convertible to an int (such as a float or characters). What you can do is use a little helper method to try and interpret the string for you:

def interpret_string(s):
    if not isinstance(s, basestring):
        return str(s)
    if s.isdigit():
        return int(s)
    try:
        return float(s)
    except ValueError:
        return s

So it will take a string and try to convert it to int, then float, and otherwise return string. This is more just a general example of looking at the convertible types. It would be an error for your value to come back out of that function still being a string, which you would then want to report to the user and ask for new input.

Maybe a variation that returns None if its neither float nor int:

def interpret_string(s):
    if not isinstance(s, basestring):
        return None
    if s.isdigit():
        return int(s)
    try:
        return float(s)
    except ValueError:
        return None

val=raw_input("> ")
how_much=interpret_string(val)
if how_much is None:
    # ask for more input? Error?

ResourceDictionary in a separate assembly

I'm working with .NET 4.5 and couldn't get this working... I was using WPF Custom Control Library. This worked for me in the end...

<ResourceDictionary Source="/MyAssembly;component/mytheme.xaml" />

source: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/11a42336-8d87-4656-91a3-275413d3cc19

How to get the indices list of all NaN value in numpy array?

You can use np.where to match the boolean conditions corresponding to Nan values of the array and map each outcome to generate a list of tuples.

>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this:

 Select 
    Id, 
    Salt, 
    Password, 
    BannedEndDate, 
    (Select Count(*) 
        From LoginFails 
        Where username = '" + LoginModel.Username + "' And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')
 From Users 
 Where username = '" + LoginModel.Username + "'

And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!

Hope that helps!

Custom height Bootstrap's navbar

You need also to set .min-height: 0px; please see bellow:

.navbar-inner {
    min-height: 0px;
}

.navbar-brand,
.navbar-nav li a {
    line-height: 150px;
    height: 150px;
    padding-top: 0;
}

If you set .min-height: 0px; then you can choose any height you want!

Good Luck!

intellij incorrectly saying no beans of type found for autowired repository

And one last piece of important information - add the ComponentScan so that the app knows about the things it needs to wire. This is not relevant in the case of this question. However if no @autowiring is being performed at all then this is likely your solution.

@Configuration
@ComponentScan(basePackages = {
    "some_package",
})
public class someService {

Call static methods from regular ES6 class methods

I stumbled over this thread searching for answer to similar case. Basically all answers are found, but it's still hard to extract the essentials from them.

Kinds of Access

Assume a class Foo probably derived from some other class(es) with probably more classes derived from it.

Then accessing

  • from static method/getter of Foo
    • some probably overridden static method/getter:
      • this.method()
      • this.property
    • some probably overridden instance method/getter:
      • impossible by design
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • impossible by design
  • from instance method/getter of Foo
    • some probably overridden static method/getter:
      • this.constructor.method()
      • this.constructor.property
    • some probably overridden instance method/getter:
      • this.method()
      • this.property
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • not possible by intention unless using some workaround:
        • Foo.prototype.method.call( this )
        • Object.getOwnPropertyDescriptor( Foo.prototype,"property" ).get.call(this);

Keep in mind that using this isn't working this way when using arrow functions or invoking methods/getters explicitly bound to custom value.

Background

  • When in context of an instance's method or getter
    • this is referring to current instance.
    • super is basically referring to same instance, but somewhat addressing methods and getters written in context of some class current one is extending (by using the prototype of Foo's prototype).
    • definition of instance's class used on creating it is available per this.constructor.
  • When in context of a static method or getter there is no "current instance" by intention and so
    • this is available to refer to the definition of current class directly.
    • super is not referring to some instance either, but to static methods and getters written in context of some class current one is extending.

Conclusion

Try this code:

_x000D_
_x000D_
class A {_x000D_
  constructor( input ) {_x000D_
    this.loose = this.constructor.getResult( input );_x000D_
    this.tight = A.getResult( input );_x000D_
    console.log( this.scaledProperty, Object.getOwnPropertyDescriptor( A.prototype, "scaledProperty" ).get.call( this ) );_x000D_
  }_x000D_
_x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 100;_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return input * this.scale;_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 2;_x000D_
  }_x000D_
}_x000D_
_x000D_
class B extends A {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
    this.tight = B.getResult( input ) + " (of B)";_x000D_
  }_x000D_
  _x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 10000;_x000D_
  }_x000D_
_x000D_
  static get scale() {_x000D_
    return 4;_x000D_
  }_x000D_
}_x000D_
_x000D_
class C extends B {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 5;_x000D_
  }_x000D_
}_x000D_
_x000D_
class D extends C {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return super.getResult( input ) + " (overridden)";_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 10;_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
let instanceA = new A( 4 );_x000D_
console.log( "A.loose", instanceA.loose );_x000D_
console.log( "A.tight", instanceA.tight );_x000D_
_x000D_
let instanceB = new B( 4 );_x000D_
console.log( "B.loose", instanceB.loose );_x000D_
console.log( "B.tight", instanceB.tight );_x000D_
_x000D_
let instanceC = new C( 4 );_x000D_
console.log( "C.loose", instanceC.loose );_x000D_
console.log( "C.tight", instanceC.tight );_x000D_
_x000D_
let instanceD = new D( 4 );_x000D_
console.log( "D.loose", instanceD.loose );_x000D_
console.log( "D.tight", instanceD.tight );
_x000D_
_x000D_
_x000D_

Two Decimal places using c#

The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use

yournumber.ToString("0.00");

using OR and NOT in solr query

Putting together comments from a couple different answers here, in the Solr docs and on the other SO question, I found that the following syntax produces the correct result for my use case

(my_field=my_value or my_field is null):

(my_field:"my_value" OR (*:* NOT my_field:*))

This works for solr 4.1.0. This is slightly different than the use case in the OP; but, I thought that others would find it useful.

How can I initialize base class member variables in derived class constructor?

You can't initialize a and b in B because they are not members of B. They are members of A, therefore only A can initialize them. You can make them public, then do assignment in B, but that is not a recommended option since it would destroy encapsulation. Instead, create a constructor in A to allow B (or any subclass of A) to initialize them:

class A 
{
protected:
    A(int a, int b) : a(a), b(b) {} // Accessible to derived classes
    // Change "protected" to "public" to allow others to instantiate A.
private:
    int a, b; // Keep these variables private in A
};

class B : public A 
{
public:
    B() : A(0, 0) // Calls A's constructor, initializing a and b in A to 0.
    {
    } 
};

How to get the input from the Tkinter Text Widget?

Lets say that you have a Text widget called my_text_widget.

To get input from the my_text_widget you can use the get function.

Let's assume that you have imported tkinter. Lets define my_text_widget first, lets make it just a simple text widget.

my_text_widget = Text(self)

To get input from a text widget you need to use the get function, both, text and entry widgets have this.

input = my_text_widget.get()

The reason we save it to a variable is to use it in the further process, for example, testing for what's the input.

How do I check whether a file exists without exceptions?

import os
#Your path here e.g. "C:\Program Files\text.txt"
#For access purposes: "C:\\Program Files\\text.txt"
if os.path.exists("C:\..."):   
    print "File found!"
else:
    print "File not found!"

Importing os makes it easier to navigate and perform standard actions with your operating system.

For reference also see How to check whether a file exists using Python?

If you need high-level operations, use shutil.

Use String.split() with multiple delimiters

Try this regex "[-.]+". The + after treats consecutive delimiter chars as one. Remove plus if you do not want this.

Try-catch speeding up my code?

Well, the way you're timing things looks pretty nasty to me. It would be much more sensible to just time the whole loop:

var stopwatch = Stopwatch.StartNew();
for (int i = 1; i < 100000000; i++)
{
    Fibo(100);
}
stopwatch.Stop();
Console.WriteLine("Elapsed time: {0}", stopwatch.Elapsed);

That way you're not at the mercy of tiny timings, floating point arithmetic and accumulated error.

Having made that change, see whether the "non-catch" version is still slower than the "catch" version.

EDIT: Okay, I've tried it myself - and I'm seeing the same result. Very odd. I wondered whether the try/catch was disabling some bad inlining, but using [MethodImpl(MethodImplOptions.NoInlining)] instead didn't help...

Basically you'll need to look at the optimized JITted code under cordbg, I suspect...

EDIT: A few more bits of information:

  • Putting the try/catch around just the n++; line still improves performance, but not by as much as putting it around the whole block
  • If you catch a specific exception (ArgumentException in my tests) it's still fast
  • If you print the exception in the catch block it's still fast
  • If you rethrow the exception in the catch block it's slow again
  • If you use a finally block instead of a catch block it's slow again
  • If you use a finally block as well as a catch block, it's fast

Weird...

EDIT: Okay, we have disassembly...

This is using the C# 2 compiler and .NET 2 (32-bit) CLR, disassembling with mdbg (as I don't have cordbg on my machine). I still see the same performance effects, even under the debugger. The fast version uses a try block around everything between the variable declarations and the return statement, with just a catch{} handler. Obviously the slow version is the same except without the try/catch. The calling code (i.e. Main) is the same in both cases, and has the same assembly representation (so it's not an inlining issue).

Disassembled code for fast version:

 [0000] push        ebp
 [0001] mov         ebp,esp
 [0003] push        edi
 [0004] push        esi
 [0005] push        ebx
 [0006] sub         esp,1Ch
 [0009] xor         eax,eax
 [000b] mov         dword ptr [ebp-20h],eax
 [000e] mov         dword ptr [ebp-1Ch],eax
 [0011] mov         dword ptr [ebp-18h],eax
 [0014] mov         dword ptr [ebp-14h],eax
 [0017] xor         eax,eax
 [0019] mov         dword ptr [ebp-18h],eax
*[001c] mov         esi,1
 [0021] xor         edi,edi
 [0023] mov         dword ptr [ebp-28h],1
 [002a] mov         dword ptr [ebp-24h],0
 [0031] inc         ecx
 [0032] mov         ebx,2
 [0037] cmp         ecx,2
 [003a] jle         00000024
 [003c] mov         eax,esi
 [003e] mov         edx,edi
 [0040] mov         esi,dword ptr [ebp-28h]
 [0043] mov         edi,dword ptr [ebp-24h]
 [0046] add         eax,dword ptr [ebp-28h]
 [0049] adc         edx,dword ptr [ebp-24h]
 [004c] mov         dword ptr [ebp-28h],eax
 [004f] mov         dword ptr [ebp-24h],edx
 [0052] inc         ebx
 [0053] cmp         ebx,ecx
 [0055] jl          FFFFFFE7
 [0057] jmp         00000007
 [0059] call        64571ACB
 [005e] mov         eax,dword ptr [ebp-28h]
 [0061] mov         edx,dword ptr [ebp-24h]
 [0064] lea         esp,[ebp-0Ch]
 [0067] pop         ebx
 [0068] pop         esi
 [0069] pop         edi
 [006a] pop         ebp
 [006b] ret

Disassembled code for slow version:

 [0000] push        ebp
 [0001] mov         ebp,esp
 [0003] push        esi
 [0004] sub         esp,18h
*[0007] mov         dword ptr [ebp-14h],1
 [000e] mov         dword ptr [ebp-10h],0
 [0015] mov         dword ptr [ebp-1Ch],1
 [001c] mov         dword ptr [ebp-18h],0
 [0023] inc         ecx
 [0024] mov         esi,2
 [0029] cmp         ecx,2
 [002c] jle         00000031
 [002e] mov         eax,dword ptr [ebp-14h]
 [0031] mov         edx,dword ptr [ebp-10h]
 [0034] mov         dword ptr [ebp-0Ch],eax
 [0037] mov         dword ptr [ebp-8],edx
 [003a] mov         eax,dword ptr [ebp-1Ch]
 [003d] mov         edx,dword ptr [ebp-18h]
 [0040] mov         dword ptr [ebp-14h],eax
 [0043] mov         dword ptr [ebp-10h],edx
 [0046] mov         eax,dword ptr [ebp-0Ch]
 [0049] mov         edx,dword ptr [ebp-8]
 [004c] add         eax,dword ptr [ebp-1Ch]
 [004f] adc         edx,dword ptr [ebp-18h]
 [0052] mov         dword ptr [ebp-1Ch],eax
 [0055] mov         dword ptr [ebp-18h],edx
 [0058] inc         esi
 [0059] cmp         esi,ecx
 [005b] jl          FFFFFFD3
 [005d] mov         eax,dword ptr [ebp-1Ch]
 [0060] mov         edx,dword ptr [ebp-18h]
 [0063] lea         esp,[ebp-4]
 [0066] pop         esi
 [0067] pop         ebp
 [0068] ret

In each case the * shows where the debugger entered in a simple "step-into".

EDIT: Okay, I've now looked through the code and I think I can see how each version works... and I believe the slower version is slower because it uses fewer registers and more stack space. For small values of n that's possibly faster - but when the loop takes up the bulk of the time, it's slower.

Possibly the try/catch block forces more registers to be saved and restored, so the JIT uses those for the loop as well... which happens to improve the performance overall. It's not clear whether it's a reasonable decision for the JIT to not use as many registers in the "normal" code.

EDIT: Just tried this on my x64 machine. The x64 CLR is much faster (about 3-4 times faster) than the x86 CLR on this code, and under x64 the try/catch block doesn't make a noticeable difference.

Python: Remove division decimal

if val % 1 == 0:
    val = int(val)

else:
    val = float(val)

This worked for me.

How it works: if the remainder of the quotient of val and 1 is 0, val has to be an integer and can, therefore, be declared to be int without having to worry about losing decimal numbers.

Compare these two situations:

A:

val = 12.00

if val % 1 == 0:
    val = int(val)
else:
    val = float(val)

print(val)

In this scenario, the output is 12, because 12.00 divided by 1 has the remainder of 0. With this information we know, that val doesn't have any decimals and we can declare val to be int.

B:

val = 13.58

if val % 1 == 0:
    val = int(val)
else:
    val = float(val)

print(val)

This time the output is 13.58, because when val is divided by 1 there is a remainder (0.58) and therefore val is declared to be a float.

By just declaring the number to be an int (without testing the remainder) decimal numbers will be cut off.

This way there are no zeros in the end and no other than the zeros will be ignored.

Passing multiple values to a single PowerShell script parameter

Parameters take input before arguments. What you should do instead is add a parameter that accepts an array, and make it the first position parameter. ex:

param(
    [Parameter(Position = 0)]
    [string[]]$Hosts,
    [string]$VLAN
    )

foreach ($i in $Hosts)  
{ 
    Do-Stuff $i
}

Then call it like:

.\script.ps1 host1, host2, host3 -VLAN 2

Notice the comma between the values. This collects them in an array

Create an array with random values

Generators

An array of length 40 of 40 random possible values (0 - 39) without repeating values is better to shuffle it as @Phrogz and @Jared Beck explain. Another approach, just for the records, could be using generators. But this approach lacks of performance compared to other proposed solutions.

function* generateRandomIterable(n, range) {
  for (let i = 0; i < n; i++) {
    yield ~~(Math.random() * range);
  }
}
const randomArr = [...generateRandomIterable(40,40)];

Why is the jquery script not working?

Use noConflict() method

ex:jQuery.noConflict()

and Use jQuery via jQuery() instead of via $()

Ex:jQuery('#id').val(); instead of $('#id').val();

How to unstash only certain files?

As mentioned below, and detailed in "How would I extract a single file (or changes to a file) from a git stash?", you can apply use git checkout or git show to restore a specific file.

git checkout stash@{0} -- <filename>

With Git 2.23+ (August 2019), use git restore, which replaces the confusing git checkout command:

git restore -s stash@{0} -- <filename>

That does overwrite filename: make sure you didn't have local modifications, or you might want to merge the stashed file instead.

(As commented by Jaime M., for certain shell like tcsh where you need to escape the special characters, the syntax would be: git checkout 'stash@{0}' -- <filename>)

or to save it under another filename:

git show stash@{0}:<full filename>  >  <newfile>

(note that here <full filename> is full pathname of a file relative to top directory of a project (think: relative to stash@{0})).

yucer suggests in the comments:

If you want to select manually which changes you want to apply from that file:

git difftool stash@{0}..HEAD -- <filename>

Vivek adds in the comments:

Looks like "git checkout stash@{0} -- <filename>" restores the version of the file as of the time when the stash was performed -- it does NOT apply (just) the stashed changes for that file.
To do the latter:

git diff stash@{0}^1 stash@{0} -- <filename> | git apply

(as commented by peterflynn, you might need | git apply -p1 in some cases, removing one (p1) leading slash from traditional diff paths)


As commented: "unstash" (git stash pop), then:

  • add what you want to keep to the index (git add)
  • stash the rest: git stash --keep-index

The last point is what allows you to keep some file while stashing others.
It is illustrated in "How to stash only one file out of multiple files that have changed".

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

How to restart adb from root to user mode?

Try this to make sure you get your shell back:

enter adb shell (root). Then type below comamnd.

stop adbd && setprop service.adb.root 0 && start adbd &

This command will stop adbd, then setprop service.adb.root 0 if adbd has been successfully stopped, and finally restart adbd should the .root property have successfully been set to 0. And all this will be done in the background thanks to the last &.

PowerShell: Store Entire Text File Contents in Variable

On a side note, in PowerShell 3.0 you can use the Get-Content cmdlet with the new Raw switch:

$text = Get-Content .\file.txt -Raw 

MySQL "incorrect string value" error when save unicode string in Django

None of these answers solved the problem for me. The root cause being:

You cannot store 4-byte characters in MySQL with the utf-8 character set.

MySQL has a 3 byte limit on utf-8 characters (yes, it's wack, nicely summed up by a Django developer here)

To solve this you need to:

  1. Change your MySQL database, table and columns to use the utf8mb4 character set (only available from MySQL 5.5 onwards)
  2. Specify the charset in your Django settings file as below:

settings.py

DATABASES = {
    'default': {
        'ENGINE':'django.db.backends.mysql',
        ...
        'OPTIONS': {'charset': 'utf8mb4'},
    }
}

Note: When recreating your database you may run into the 'Specified key was too long' issue.

The most likely cause is a CharField which has a max_length of 255 and some kind of index on it (e.g. unique). Because utf8mb4 uses 33% more space than utf-8 you'll need to make these fields 33% smaller.

In this case, change the max_length from 255 to 191.

Alternatively you can edit your MySQL configuration to remove this restriction but not without some django hackery

UPDATE: I just ran into this issue again and ended up switching to PostgreSQL because I was unable to reduce my VARCHAR to 191 characters.

how to remove the bold from a headline?

Try font-weight:normal;

h1 {
    font-weight: normal;
}

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

I changed the header and footer of the PEM file to

-----BEGIN RSA PRIVATE KEY-----

and

-----END RSA PRIVATE KEY-----

Finally, it works!

git pull error :error: remote ref is at but expected

If you are running git under a file system that is not case sensitive (Windows or OS X) this will occur if there are two branches with the same name but different capitalisation, e.g. user_model_changes and User_model_changes as both of the remote branches will match the same tracking ref.

Delete the wrong remote branch (you shouldn't have branches that differ only by case) and then git remote prune origin and everything should work

How can I use grep to show just filenames on Linux?

For a simple file search you could use grep's -l and -r options:

grep -rl "mystring"

All the search is done by grep. Of course, if you need to select files on some other parameter, find is the correct solution:

find . -iname "*.php" -execdir grep -l "mystring" {} +

The execdir option builds each grep command per each directory, and concatenates filenames into only one command (+).

PHP Warning: Module already loaded in Unknown on line 0

For shared hosting, in cPanel I unchecked the Module in question under "Select PHP Version" > "Extensions" and the error disappeared for PHP 7.4.

JQuery Calculate Day Difference in 2 date textboxes

This should do the trick

var start = $('#start_date').val();
var end = $('#end_date').val();

// end - start returns difference in milliseconds 
var diff = new Date(end - start);

// get days
var days = diff/1000/60/60/24;

Example

var start = new Date("2010-04-01"),
    end   = new Date(),
    diff  = new Date(end - start),
    days  = diff/1000/60/60/24;

days; //=> 8.525845775462964

How to create a JQuery Clock / Timer

var timeInterval = 5;
    var blinkTime = 1;
    var open_signal = 'top_left';

    $(document).ready(function () {
        $('#div_top_left .timer').html(timeInterval);
        $('#div_top_right .timer').html(timeInterval);
        $('#div_bottom_right .timer').html(timeInterval * 2);
        $('#div_bottom_left .timer').html(timeInterval * 3);

        $('#div_top_left .green').css('background-color', 'green');
        $('#div_top_right .red').css('background-color', 'red');
        $('#div_bottom_right .red').css('background-color', 'red');
        $('#div_bottom_left .red').css('background-color', 'red');

        setInterval(function () {
            manageSignals();
        }, 1000);
    });

    function manageSignals() {
        var top_left_time = parseInt($('#div_top_left .timer').html()) - 1;
        var top_right_time = parseInt($('#div_top_right .timer').html()) - 1;
        var bottom_left_time = parseInt($('#div_bottom_left .timer').html()) - 1;
        var bottom_right_time = parseInt($('#div_bottom_right .timer').html()) - 1;

        if (top_left_time == -1 && open_signal == 'top_left') open_signal = 'top_right';
        else if (top_right_time == -1 && open_signal == 'top_right') open_signal = 'bottom_right';
        else if (bottom_right_time == -1 && open_signal == 'bottom_right') open_signal = 'bottom_left';
        else if (bottom_left_time == -1 && open_signal == 'bottom_left') open_signal = 'top_left';

        if (top_left_time == -1) {
            if (open_signal == 'top_right') {
                top_left_time = (timeInterval * 3) - 1;
                $('#div_top_left .red').css('background-color', 'red');
                $('#div_top_left .yellow').css('background-color', 'white');
                $('#div_top_left .green').css('background-color', 'white');
            }
            else if (open_signal == 'top_left') {
                top_left_time = timeInterval - 1;
                $('#div_top_left .red').css('background-color', 'white');
                $('#div_top_left .yellow').css('background-color', 'white');
                $('#div_top_left .green').css('background-color', 'green');
            }
        }

        if (top_right_time == -1) {
            if (open_signal == 'bottom_right') {
                top_right_time = (timeInterval * 3) - 1;
                $('#div_top_right .red').css('background-color', 'red');
                $('#div_top_right .yellow').css('background-color', 'white');
                $('#div_top_right .green').css('background-color', 'white');
            }
            else if (open_signal == 'top_right') {
                top_right_time = timeInterval - 1;
                $('#div_top_right .red').css('background-color', 'white');
                $('#div_top_right .yellow').css('background-color', 'white');
                $('#div_top_right .green').css('background-color', 'green');
            }
        }

        if (bottom_right_time == -1) {
            if (open_signal == 'bottom_left') {
                bottom_right_time = (timeInterval * 3) - 1;
                $('#div_bottom_right .red').css('background-color', 'red');
                $('#div_bottom_right .yellow').css('background-color', 'white');
                $('#div_bottom_right .green').css('background-color', 'white');
            }
            else if (open_signal == 'bottom_right') {
                bottom_right_time = timeInterval - 1;
                $('#div_bottom_right .red').css('background-color', 'white');
                $('#div_bottom_right .yellow').css('background-color', 'white');
                $('#div_bottom_right .green').css('background-color', 'green');
            }
        }

        if (bottom_left_time == -1) {
            if (open_signal == 'top_left') {
                bottom_left_time = (timeInterval * 3) - 1;
                $('#div_bottom_left .red').css('background-color', 'red');
                $('#div_bottom_left .yellow').css('background-color', 'white');
                $('#div_bottom_left .green').css('background-color', 'white');
            }
            else if (open_signal == 'bottom_left') {
                bottom_left_time = timeInterval - 1;
                $('#div_bottom_left .red').css('background-color', 'white');
                $('#div_bottom_left .yellow').css('background-color', 'white');
                $('#div_bottom_left .green').css('background-color', 'green');
            }
        }

        if (top_left_time == blinkTime && open_signal == 'top_left') {
            $('#div_top_left .yellow').css('background-color', 'yellow');
            $('#div_top_left .green').css('background-color', 'white');
        }
        if (top_right_time == blinkTime && open_signal == 'top_right') {
            $('#div_top_right .yellow').css('background-color', 'yellow');
            $('#div_top_right .green').css('background-color', 'white');
        }
        if (bottom_left_time == blinkTime && open_signal == 'bottom_left') {
            $('#div_bottom_left .yellow').css('background-color', 'yellow');
            $('#div_bottom_left .green').css('background-color', 'white');
        }
        if (bottom_right_time == blinkTime && open_signal == 'bottom_right') {
            $('#div_bottom_right .yellow').css('background-color', 'yellow');
            $('#div_bottom_right .green').css('background-color', 'white');
        }

        $('#div_top_left .timer').html(top_left_time);
        $('#div_top_right .timer').html(top_right_time);
        $('#div_bottom_left .timer').html(bottom_left_time);
        $('#div_bottom_right .timer').html(bottom_right_time);
    }

How to add multiple classes to a ReactJS Component?

Vanilla JS

No need for external libraries - just use ES6 template strings:

<i className={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>

Date only from TextBoxFor()

Don't be afraid of using raw HTML.

<input type="text" value="<%= Html.Encode(Model.SomeDate.ToShortDateString()) %>" />

Why does jQuery or a DOM method such as getElementById not find the element?

When I tried your code, it worked.

The only reason that your event is not working, may be that your DOM was not ready and your button with id "event-btn" was not yet ready. And your javascript got executed and tried to bind the event with that element.

Before using the DOM element for binding, that element should be ready. There are many options to do that.

Option1: You can move your event binding code within document ready event. Like:

document.addEventListener('DOMContentLoaded', (event) => {
  //your code to bind the event
});

Option2: You can use timeout event, so that binding is delayed for few seconds. like:

setTimeout(function(){
  //your code to bind the event
}, 500);

Option3: move your javascript include to the bottom of your page.

I hope this helps you.

Find provisioning profile in Xcode 5

It is not exactly for Xcode5 but this question links people who want to check where are provisioning profiles:
Following documentation https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/MaintainingCertificates/MaintainingCertificates.html

  1. Choose Xcode > Preferences.
  2. Click Accounts at the top of the window.
  3. Select the team you want to view, and click View Details. enter image description here In the dialog that appears, view your signing identities and provisioning profiles. If a Create button appears next to a certificate, it hasn’t been created yet. If a Download button appears next to a provisioning profile, it’s not on your Mac. enter image description here

Ten you can start context menu on each profile and click "Show in Finder" or "Move to Trash".

Applying .gitignore to committed files

After editing .gitignore to match the ignored files, you can do git ls-files -ci --exclude-standard to see the files that are included in the exclude lists; you can then do

  • Linux/MacOS: git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
  • Windows (PowerShell): git ls-files -ci --exclude-standard | % { git rm --cached "$_" }
  • Windows (cmd.exe): for /F "tokens=*" %a in ('git ls-files -ci --exclude-standard') do @git rm --cached "%a"

to remove them from the repository (without deleting them from disk).

Edit: You can also add this as an alias in your .gitconfig file so you can run it anytime you like. Just add the following line under the [alias] section (modify as needed for Windows or Mac):

apply-gitignore = !git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached

(The -r flag in xargs prevents git rm from running on an empty result and printing out its usage message, but may only be supported by GNU findutils. Other versions of xargs may or may not have a similar option.)

Now you can just type git apply-gitignore in your repo, and it'll do the work for you!

How to extract week number in sql

Use 'dd-mon-yyyy' if you are using the 2nd date format specified in your answer. Ex:

to_date(<column name>,'dd-mon-yyyy')

How to modify list entries during for loop?

You can do something like this:

a = [1,2,3,4,5]
b = [i**2 for i in a]

It's called a list comprehension, to make it easier for you to loop inside a list.

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

java_home environment variable should point to the location of the proper version of java installation directory, so that tomcat starts with the right version. for example it you built the project with java 1.7 , then make sure that JAVA_HOME environment variable points to the jdk 1.7 installation directory in your machine.

I had same problem , when i deploy the war in tomcat and run, the link throws the error. But pointing the variable - JAVA_HOME to jdk 1.7 resolved the issue, as my war file was built in java 1.7 environment.

How to implement a lock in JavaScript

Locks still have uses in JS. In my experience I only needed to use locks to prevent spam clicking on elements making AJAX calls. If you have a loader set up for AJAX calls then this isn't required (as well as disabling the button after clicking). But either way here is what I used for locking:

var LOCK_INDEX = [];
function LockCallback(key, action, manual) {
    if (LOCK_INDEX[key])
        return;
    LOCK_INDEX[key] = true;
    action(function () { delete LOCK_INDEX[key] });
    if (!manual)
        delete LOCK_INDEX[key];
}

Usage:

Manual unlock (usually for XHR)

LockCallback('someKey',(delCallback) => { 
    //do stuff
    delCallback(); //Unlock method
}, true)

Auto unlock

LockCallback('someKey',() => { 
    //do stuff
})

How to set scope property with ng-init?

You are trying to read the set value before Angular is done assigning.

Demo:

var testController = function ($scope, $timeout) {
    console.log('test');
    $timeout(function(){
        console.log($scope.testInput);
    },1000);
}

Ideally you should use $watch as suggested by @Beterraba to get rid of the timer:

var testController = function ($scope) {
    console.log('test');
    $scope.$watch("testInput", function(){
        console.log($scope.testInput);
    });
}

How to call a method after a delay in Android

Kotlin & Java Many Ways

1. Using Handler

Handler().postDelayed({
    TODO("Do something")
    }, 2000)

2. Using TimerTask

Timer().schedule(object : TimerTask() {
    override fun run() {
        TODO("Do something")
    }
}, 2000)

Or even shorter

Timer().schedule(timerTask {
    TODO("Do something")
}, 2000)

Or shortest would be

Timer().schedule(2000) {
    TODO("Do something")
}

3. Using Executors

Executors.newSingleThreadScheduledExecutor().schedule({
    TODO("Do something")
}, 2, TimeUnit.SECONDS)

In Java

1. Using Handler

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something
    }
}, 2000);

2. Using Timer

new Timer().schedule(new TimerTask() {          
    @Override
    public void run() {
        // Do something
    }
}, 2000);

3. Using ScheduledExecutorService

private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();

Runnable runnable = new Runnable() {
  public void run() {
      // Do something
  }
  };
worker.schedule(runnable, 2, TimeUnit.SECONDS);

Program to find largest and smallest among 5 numbers without using array

You could use list (or vector), which is not an array:

#include<list>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
    list<int> l;
    l.push_back(3); 
    l.push_back(9); 
    l.push_back(30);    
    l.push_back(0); 
    l.push_back(5); 

    list<int>::iterator it_max = max_element(l.begin(), l.end());
    list<int>::iterator it_min = min_element(l.begin(), l.end());

    cout << "Max: " << *it_max << endl;
    cout << "Min: " << *it_min << endl;
}

Replacing from match to end-of-line

awk

awk '{gsub(/two.*/,"")}1' file

Ruby

ruby -ne 'print $_.gsub(/two.*/,"")' file

Installing R with Homebrew

If you run

xcode-select --install

you do you not need to install gcc through brew, and you will not have to waste time compiling gcc. See https://stackoverflow.com/a/24967219/2668545 for more details.

After that, you can simply do

brew tap homebrew/science
brew install Caskroom/cask/xquartz
brew install r

How do you convert an entire directory with ffmpeg?

If you want a graphical interface to batch process with ffmpegX, try Quick Batcher. It's free and will take your last ffmpegX settings to convert files you drop into it.

Note that you can't drag-drop folders onto Quick Batcher. So select files and then put them through Quick Batcher.

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

I had this problem because I was calling a method

await myClass.myStaticMethod(myString);

but I was setting myString with

var myString = String.Format({some dynamic-type values})

which resulted in a dynamic type, not a string, thus when I tried to await on myClass.myStaticMethod(myString), the compiler thought I meant to call myClass.myStaticMethod(dynamic myString). This compiled fine because, again, in a dynamic context, it's all good until it blows up at run-time, which is what happened because there is no implementation of the dynamic version of myStaticMethod, and this error message didn't help whatsoever, and the fact that Intellisense would take me to the correct definition didn't help either.
Tricky!

However, by forcing the result type to string, like:

var myString = String.Format({some dynamic-type values})

to

string myString = String.Format({some dynamic-type values})

my call to myStaticMethod routed properly

Log all requests from the python-requests module

I'm using a logger_config.yaml file to configure my logging, and to get those logs to show up, all I had to do was to add a disable_existing_loggers: False to the end of it.

My logging setup is rather extensive and confusing, so I don't even know a good way to explain it here, but if someone's also using a YAML file to configure their logging, this might help.

https://docs.python.org/3/howto/logging.html#configuring-logging

Is there any way to specify a suggested filename when using data: URI?

No.

The entire purpose is that it's a datastream, not a file. The data source should not have any knowledge of the user agent handling it as a file... and it doesn't.

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

The iPhone 6+ renders internally using @3x assets at a virtual resolution of 2208×1242 (with 736x414 points), then samples that down for display. The same as using a scaled resolution on a Retina MacBook — it lets them hit an integral multiple for pixel assets while still having e.g. 12 pt text look the same size on the screen.

So, yes, the launch screens need to be that size.

The maths:

The 6, the 5s, the 5, the 4s and the 4 are all 326 pixels per inch, and use @2x assets to stick to the approximately 160 points per inch of all previous devices.

The 6+ is 401 pixels per inch. So it'd hypothetically need roughly @2.46x assets. Instead Apple uses @3x assets and scales the complete output down to about 84% of its natural size.

In practice Apple has decided to go with more like 87%, turning the 1080 into 1242. No doubt that was to find something as close as possible to 84% that still produced integral sizes in both directions — 1242/1080 = 2208/1920 exactly, whereas if you'd turned the 1080 into, say, 1286, you'd somehow need to render 2286.22 pixels vertically to scale well.

Auto-increment on partial primary key with Entity Framework Core

First of all you should not merge the Fluent Api with the data annotation so I would suggest you to use one of the below:

make sure you have correclty set the keys

modelBuilder.Entity<Foo>()
            .HasKey(p => new { p.Name, p.Id });
modelBuilder.Entity<Foo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

OR you can achieve it using data annotation as well

public class Foo
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key, Column(Order = 0)]
    public int Id { get; set; }

    [Key, Column(Order = 1)]
    public string Name{ get; set; }
}

How to resolve javax.mail.AuthenticationFailedException issue?

You need to implement a custom Authenticator

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;


class GMailAuthenticator extends Authenticator {
     String user;
     String pw;
     public GMailAuthenticator (String username, String password)
     {
        super();
        this.user = username;
        this.pw = password;
     }
    public PasswordAuthentication getPasswordAuthentication()
    {
       return new PasswordAuthentication(user, pw);
    }
}

Now use it in the Session

Session session = Session.getInstance(props, new GMailAuthenticator(username, password));

Also check out the JavaMail FAQ

docker-compose up for only certain containers

You can start containers by using:

$ docker-compose up -d client

This will run containers in the background and output will be avaiable from

$ docker-compose logs

and it will consist of all your started containers

Connect Java to a MySQL database

Short and Sweet code.

try {       
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("Driver Loaded");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
    //Database Name - testDB, Username - "root", Password - ""
    System.out.println("Connected...");         
} catch(Exception e) {
    e.printStackTrace();
}

For SQL server 2012

try {
    String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123"; 
    //KHILAN is Host    and 1433 is port number     
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    System.out.println("Driver Loaded");
    conn = DriverManager.getConnection(url);
    System.out.println("Connected...");
} catch(Exception e) {
    e.printStackTrace();
}

What does the "$" sign mean in jQuery or JavaScript?

The $ symbol simply invokes the jQuery library's selector functionality. So $("#Text") returns the jQuery object for the Text div which can then be modified.

require is not defined? Node.js

This can now also happen in Node.js as of version 14.

It happens when you declare your package type as module in your package.json. If you do this, certain CommonJS variables can't be used, including require.

To fix this, remove "type": "module" from your package.json and make sure you don't have any files ending with .mjs.

select a value where it doesn't exist in another table

select ID from A where ID not in (select ID from B);

or

select ID from A except select ID from B;

Your second question:

delete from A where ID not in (select ID from B);

install / uninstall APKs programmatically (PackageManager vs Intents)

According to Froyo source code, the Intent.EXTRA_INSTALLER_PACKAGE_NAME extra key is queried for the installer package name in the PackageInstallerActivity.

What is the difference between function and procedure in PL/SQL?

A function can be in-lined into a SQL statement, e.g.

select foo
      ,fn_bar (foo)
  from foobar

Which cannot be done with a stored procedure. The architecture of the query optimiser limits what can be done with functions in this context, requiring that they are pure (i.e. the same inputs always produce the same output). This restricts what can be done in the function, but allows it to be used in-line in the query if it is defined to be "pure".

Otherwise, a function (not necessarily deterministic) can return a variable or a result set. In the case of a function returning a result set, you can join it against some other selection in a query. However, you cannot use a non-deterministic function like this in a correlated subquery as the optimiser cannot predict what sort of result set will be returned (this is computationally intractable, like the halting problem).

Python Inverse of a Matrix

Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equation Ax = b for x directly than to calculate A inverse then multiply the inverse by B. Even if you need to solve Ax = b for many b values, it's not a good idea to invert A. If you have to solve the system for multiple b values, save the Cholesky factorization of A, but don't invert it.

See Don't invert that matrix.

Vim autocomplete for Python

I tried pydiction (didn't work for me) and the normal omnicompletion (too limited). I looked into Jedi as suggested but found it too complex to set up. I found python-mode, which in the end satisfied my needs. Thanks @klen.

Only local connections are allowed Chrome and Selenium webdriver

I was able to resolve the problem by following steps: a. upgrade to the latest chrome version, clear the cache and close the chrome browser b. Download latest Selenium 3.0

MySQL SELECT WHERE datetime matches day (and not necessarily time)

... WHERE date_column >='2012-12-25' AND date_column <'2012-12-26' may potentially work better(if you have an index on date_column) than DATE.

How to wait until an element is present in Selenium?

FluentWait throws a NoSuchElementException is case of the confusion

org.openqa.selenium.NoSuchElementException;     

with

java.util.NoSuchElementException

in

.ignoring(NoSuchElementException.class)

favicon not working in IE

Should anyone make it down to this answer:

Same issue: didn't work in IE (including IE 10), worked everywhere else.

Turns out that the file was not a "real" .ico file. I fixed this by uploading it to http://www.favicon.cc/ and then downloading it again.

First I tested it by generating a random .ico file on this site and using that instead of my original file. Saw that it worked.

What Java ORM do you prefer, and why?

Eclipse Link, for many reasons, but notably I feel like it has less bloat than other main stream solutions (at least less in-your-face bloat).

Oh and Eclipse Link has been chosen to be the reference implementation for JPA 2.0

Splitting on first occurrence

>>> s = "123mango abcd mango kiwi peach"
>>> s.split("mango", 1)
['123', ' abcd mango kiwi peach']
>>> s.split("mango", 1)[1]
' abcd mango kiwi peach'

Can .NET load and parse a properties file equivalent to Java Properties class?

No there is no built-in support for this.

You have to make your own "INIFileReader". Maybe something like this?

var data = new Dictionary<string, string>();
foreach (var row in File.ReadAllLines(PATH_TO_FILE))
  data.Add(row.Split('=')[0], string.Join("=",row.Split('=').Skip(1).ToArray()));

Console.WriteLine(data["ServerName"]);

Edit: Updated to reflect Paul's comment.

jQuery get the rendered height of an element?

I think the best way to do this in 2020 is to use vanilla js and getBoundingClientRect().height;

Here's an example

_x000D_
_x000D_
let div = document.querySelector('div');
let divHeight = div.getBoundingClientRect().height;

console.log(`Div Height: ${divHeight}`);
_x000D_
<div>
  How high am I? 
</div>
_x000D_
_x000D_
_x000D_

On top of getting height this way, we also have access to a bunch of other stuff about the div.

_x000D_
_x000D_
let div = document.querySelector('div');
let divInfo = div.getBoundingClientRect();

console.log(divInfo);
_x000D_
<div>What else am I? </div>
_x000D_
_x000D_
_x000D_

Fatal Error :1:1: Content is not allowed in prolog

Looks like you forgot adding correct headers to your get request (ask the REST API developer or you specific API description):

HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.header("Accept", "application/xml")
connection.setRequestMethod("GET");
connection.connect();

or

connection.header("Accept", "application/xml;version=1")

How to get the cursor to change to the hand when hovering a <button> tag

Just add this style:

cursor: pointer;

The reason it's not happening by default is because most browsers reserve the pointer for links only (and maybe a couple other things I'm forgetting, but typically not <button>s).

More on the cursor property: https://developer.mozilla.org/en/CSS/cursor

I usually apply this to <button> and <label> by default.

NOTE: I just caught this:

the button tags have an id of #more

It's very important that each element has it's own unique id, you cannot have duplicates. Use the class attribute instead, and change your selector from #more to .more. This is actually quite a common mistake that is the cause of many problems and questions asked here. The earlier you learn how to use id, the better.

How can I position my jQuery dialog to center?

Another thing that can give you hell with JQuery Dialog positioning, especially for documents larger than the browser view port - you must add the declaration

<!DOCTYPE html>

At the top of your document.

Without it, jquery tends to put the dialog on the bottom of the page and errors may occur when trying to drag it.

print variable and a string in python

By printing multiple values separated by a comma:

print "I have", card.price

The print statement will output each expression separated by spaces, followed by a newline.

If you need more complex formatting, use the ''.format() method:

print "I have: {0.price}".format(card)

or by using the older and semi-deprecated % string formatting operator.

How to clear variables in ipython?

Apart from the methods mentioned earlier. You can also use the command del to remove multiple variables

del variable1,variable2

How to clear cache of Eclipse Indigo

You can always create a new Eclipse workspace. The Eclipse.exe -clean option is not sufficient in some cases, for example, if the local history becomes a problem.

Edit:

Eclipse is mostly a collection of third party plugins. And each of those plugins can add some extra useful, useless or problematic information to the central Eclipse workspace meta-data folder.

The problem is that not every plugin participates during the user-issued cleanup routine. Therefore, I'd say that it is a problem in the system design of Eclipse, that it allows plugins to misbehave like this.

And therefore, I'd recommend to make yourself comfortable with the idea of using multiple workspaces and linking-in external project entities into each workspace. Because, this is the only workaround for the given system design, to handle faulty plugins that spam your workspace.

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays in JS have two types of properties:

Regular elements and associative properties (which are nothing but objects)

When you define a = new Array(), you are defining an empty array. Note that there are no associative objects yet

When you define b = new Array(2), you are defining an array with two undefined locations.

In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.

console.log (a) or console.log(b) prints the array elements i.e. [] and [undefined, undefined] respectively. But since a1/a2 and b1/b2 are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2) kind of syntax

Vue.js: Conditional class style binding

<i class="fa" v-bind:class="cravings"></i>

and add in computed :

computed: {
    cravings: function() {
        return this.content['cravings'] ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline';
    }
}

Unfinished Stubbing Detected in Mockito

You're nesting mocking inside of mocking. You're calling getSomeList(), which does some mocking, before you've finished the mocking for MyMainModel. Mockito doesn't like it when you do this.

Replace

@Test
public myTest(){
    MyMainModel mainModel =  Mockito.mock(MyMainModel.class);
    Mockito.when(mainModel.getList()).thenReturn(getSomeList()); --> Line 355
}

with

@Test
public myTest(){
    MyMainModel mainModel =  Mockito.mock(MyMainModel.class);
    List<SomeModel> someModelList = getSomeList();
    Mockito.when(mainModel.getList()).thenReturn(someModelList);
}

To understand why this causes a problem, you need to know a little about how Mockito works, and also be aware in what order expressions and statements are evaluated in Java.

Mockito can't read your source code, so in order to figure out what you are asking it to do, it relies a lot on static state. When you call a method on a mock object, Mockito records the details of the call in an internal list of invocations. The when method reads the last of these invocations off the list and records this invocation in the OngoingStubbing object it returns.

The line

Mockito.when(mainModel.getList()).thenReturn(someModelList);

causes the following interactions with Mockito:

  • Mock method mainModel.getList() is called,
  • Static method when is called,
  • Method thenReturn is called on the OngoingStubbing object returned by the when method.

The thenReturn method can then instruct the mock it received via the OngoingStubbing method to handle any suitable call to the getList method to return someModelList.

In fact, as Mockito can't see your code, you can also write your mocking as follows:

mainModel.getList();
Mockito.when((List<SomeModel>)null).thenReturn(someModelList);

This style is somewhat less clear to read, especially since in this case the null has to be casted, but it generates the same sequence of interactions with Mockito and will achieve the same result as the line above.

However, the line

Mockito.when(mainModel.getList()).thenReturn(getSomeList());

causes the following interactions with Mockito:

  1. Mock method mainModel.getList() is called,
  2. Static method when is called,
  3. A new mock of SomeModel is created (inside getSomeList()),
  4. Mock method model.getName() is called,

At this point Mockito gets confused. It thought you were mocking mainModel.getList(), but now you're telling it you want to mock the model.getName() method. To Mockito, it looks like you're doing the following:

when(mainModel.getList());
// ...
when(model.getName()).thenReturn(...);

This looks silly to Mockito as it can't be sure what you're doing with mainModel.getList().

Note that we did not get to the thenReturn method call, as the JVM needs to evaluate the parameters to this method before it can call the method. In this case, this means calling the getSomeList() method.

Generally it is a bad design decision to rely on static state, as Mockito does, because it can lead to cases where the Principle of Least Astonishment is violated. However, Mockito's design does make for clear and expressive mocking, even if it leads to astonishment sometimes.

Finally, recent versions of Mockito add an extra line to the error message above. This extra line indicates you may be in the same situation as this question:

3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

How to insert logo with the title of a HTML page?

It's called a favicon. It is inserted like this:

<link rel="shortcut icon" href="favicon.ico" />

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

I had the same error when tried to run my tests in a JSF project.

I´m using Eclipse IDE (kepler). So, I did "project > clean" and then ran the tests again of the same project.

It worked!

Create a file if one doesn't exist - C

If fptr is NULL, then you don't have an open file. Therefore, you can't freopen it, you should just fopen it.

FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
    fptr = fopen("scores.dat", "wb");
}

note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.

A complete example

int main()
{
    FILE *fptr;
    char there_was_error = 0;
    char opened_in_read  = 1;
    fptr = fopen("scores.dat", "rb+");
    if(fptr == NULL) //if file does not exist, create it
    {
        opened_in_read = 0;
        fptr = fopen("scores.dat", "wb");
        if (fptr == NULL)
            there_was_error = 1;
    }
    if (there_was_error)
    {
        printf("Disc full or no permission\n");
        return EXIT_FAILURE;
    }
    if (opened_in_read)
        printf("The file is opened in read mode."
               " Let's read some cached data\n");
    else
        printf("The file is opened in write mode."
               " Let's do some processing and cache the results\n");
    return EXIT_SUCCESS;
}

Getting list of parameter names inside python function

locals() returns a dictionary with local names:

def func(a,b,c):
    print(locals().keys())

prints the list of parameters. If you use other local variables those will be included in this list. But you could make a copy at the beginning of your function.

How to display UTF-8 characters in phpMyAdmin?

I had the same problem,

Set all text/varchar collations in phpMyAdmin to utf-8 and in php files add this:

mysql_set_charset("utf8", $your_connection_name);

This solved it for me.

Get full path of the files in PowerShell

This worked for me, and produces a list of names:

$Thisfile=(get-childitem -path 10* -include '*.JPG' -recurse).fullname

I found it by using get-member -membertype properties, an incredibly useful command. most of the options it gives you are appended with a .<thing>, like fullname is here. You can stick the same command;

  | get-member -membertype properties 

at the end of any command to get more information on the things you can do with them and how to access those:

get-childitem -path 10* -include '*.JPG' -recurse | get-member -membertype properties

Disable a Button

The way I do this is as follows:

@IBAction func pressButton(sender: AnyObject) {
    var disableMyButton = sender as? UIButton
    disableMyButton.enabled = false
}

The IBAction is connected to your button in the storyboard.

If you have your button setup as an Outlet:

    @IBOutlet weak var myButton: UIButton!

Then you can access the enabled properties by using the . notation on the button name:

    myButton.enabled = false

Best way to pretty print a hash

Easy to do with json if you trust your keys to be sane:

JSON.pretty_generate(a: 1, 2 => 3, 3 => nil).
  gsub(": null", ": nil").
  gsub(/(^\s*)"([a-zA-Z][a-zA-Z\d_]*)":/, "\\1\\2:"). # "foo": 1 -> foo: 1
  gsub(/(^\s*)(".*?"):/, "\\1\\2 =>") # "123": 1 -> "123" => 1

{
  a: 1,
  "2" => 3,
  "3" => nil
}

How to read AppSettings values from a .json file in ASP.NET Core

In addition to existing answers I'd like to mention that sometimes it might be useful to have extension methods for IConfiguration for simplicity's sake.

I keep JWT config in appsettings.json so my extension methods class looks as follows:

public static class ConfigurationExtensions
{
    public static string GetIssuerSigningKey(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Authentication:JwtBearer:SecurityKey");
        return result;
    }

    public static string GetValidIssuer(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Authentication:JwtBearer:Issuer");
        return result;
    }

    public static string GetValidAudience(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Authentication:JwtBearer:Audience");
        return result;
    }

    public static string GetDefaultPolicy(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Policies:Default");
        return result;
    }

    public static SymmetricSecurityKey GetSymmetricSecurityKey(this IConfiguration configuration)
    {
        var issuerSigningKey = configuration.GetIssuerSigningKey();
        var data = Encoding.UTF8.GetBytes(issuerSigningKey);
        var result = new SymmetricSecurityKey(data);
        return result;
    }

    public static string[] GetCorsOrigins(this IConfiguration configuration)
    {
        string[] result =
            configuration.GetValue<string>("App:CorsOrigins")
            .Split(",", StringSplitOptions.RemoveEmptyEntries)
            .ToArray();

        return result;
    }
}

It saves you a lot of lines and you just write clean and minimal code:

...
x.TokenValidationParameters = new TokenValidationParameters()
{
    ValidateIssuerSigningKey = true,
    ValidateLifetime = true,
    IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
    ValidAudience = _configuration.GetValidAudience(),
    ValidIssuer = _configuration.GetValidIssuer()
};

It's also possible to register IConfiguration instance as singleton and inject it wherever you need - I use Autofac container here's how you do it:

var appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
builder.Register(c => appConfiguration).As<IConfigurationRoot>().SingleInstance();

You can do the same with MS Dependency Injection:

services.AddSingleton<IConfigurationRoot>(appConfiguration);

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

Rxjs 5.5 “ Property ‘map’ does not exist on type Observable.

The problem was related to the fact that you need to add pipe around all operators.

Change this,

this.myObservable().map(data => {})

to this

this.myObservable().pipe(map(data => {}))

And

Import map like this,

import { map } from 'rxjs/operators';

It will solve your issues.

Is there a way to 'uniq' by column?

If you want to retain the last one of the duplicates you could use

 tac a.csv | sort -u -t, -r -k1,1 |tac

Which was my requirement

here

tac will reverse the file line by line

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

Pass Method as Parameter using C#

You need to use a delegate. In this case all your methods take a string parameter and return an int - this is most simply represented by the Func<string, int> delegate1. So your code can become correct with as simple a change as this:

public bool RunTheMethod(Func<string, int> myMethodName)
{
    // ... do stuff
    int i = myMethodName("My String");
    // ... do more stuff
    return true;
}

Delegates have a lot more power than this, admittedly. For example, with C# you can create a delegate from a lambda expression, so you could invoke your method this way:

RunTheMethod(x => x.Length);

That will create an anonymous function like this:

// The <> in the name make it "unspeakable" - you can't refer to this method directly
// in your own code.
private static int <>_HiddenMethod_<>(string x)
{
    return x.Length;
}

and then pass that delegate to the RunTheMethod method.

You can use delegates for event subscriptions, asynchronous execution, callbacks - all kinds of things. It's well worth reading up on them, particularly if you want to use LINQ. I have an article which is mostly about the differences between delegates and events, but you may find it useful anyway.


1 This is just based on the generic Func<T, TResult> delegate type in the framework; you could easily declare your own:

public delegate int MyDelegateType(string value)

and then make the parameter be of type MyDelegateType instead.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

Here's how you can check the contents of the EntityValidationErrors in Visual Studio (without writing any extra code) i.e. during Debugging in the IDE.

The Problem?

You are right, the Visual Studio debugger's View Details Popup doesn't show the actual errors inside the EntityValidationErrors collection .

enter image description here

The Solution!

Just add the following expression in a Quick Watch window and click Reevaluate.

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

In my case, see how I am able to expand into the ValidationErrors List inside the EntityValidationErrors collection

enter image description here

References: mattrandle.me blog post, @yoel's answer

How to allow download of .json file with ASP.NET

Just had this issue but had to find the config for IIS Express so I could add the mime types. For me, it was located at C:\Users\<username>\Documents\IISExpress\config\applicationhost.config and I was able to add in the correct "mime map" there.

$location / switching between html5 and hashbang mode / link rewriting

I wanted to be able to access my application with the HTML5 mode and a fixed token and then switch to the hashbang method (to keep the token so the user can refresh his page).

URL for accessing my app:

http://myapp.com/amazing_url?token=super_token

Then when the user loads the page:

http://myapp.com/amazing_url?token=super_token#/amazing_url

Then when the user navigates:

http://myapp.com/amazing_url?token=super_token#/another_url

With this I keep the token in the URL and keep the state when the user is browsing. I lost a bit of visibility of the URL, but there is no perfect way of doing it.

So don't enable the HTML5 mode and then add this controller:

.config ($stateProvider)->
    $stateProvider.state('home-loading', {
         url: '/',
         controller: 'homeController'
    })
.controller 'homeController', ($state, $location)->
    if window.location.pathname != '/'
        $location.url(window.location.pathname+window.location.search).replace()
    else
        $state.go('home', {}, { location: 'replace' })

Detect HTTP or HTTPS then force HTTPS in JavaScript

How about this?

if (window.location.protocol !== 'https:') {
    window.location = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;
}

Ideally you'd do it on the server side, though.

Java: Finding the highest value in an array

A shorter solution to have the max value of array:

double max = Arrays.stream(decMax).max(Double::compareTo).get();

How to serialize an object into a string

Simple Solution,worked for me

public static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}

How to overwrite styling in Twitter Bootstrap

You can just make sure your css file parses AFTER boostrap.css , like so:

<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/myFile.css" rel="stylesheet">

Altering column size in SQL Server

For Oracle For Database:

ALTER TABLE table_name MODIFY column_name VARCHAR2(255 CHAR);

Check if table exists

If using jruby, here is a code snippet to return an array of all tables in a db.

require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"

def get_database_tables(connection, db_name)
  md = connection.get_meta_data
  rs = md.get_tables(db_name, nil, '%',["TABLE"])

  tables = []
  count = 0
  while rs.next
    tables << rs.get_string(3)
  end #while
  return tables
end

How do I resolve a HTTP 414 "Request URI too long" error?

I have a simple workaround.

Suppose your URI has a string stringdata that is too long. You can simply break it into a number of parts depending on the limits of your server. Then submit the first one, in my case to write a file. Then submit the next ones to append to previously added data.

Heap space out of memory

No. The heap is cleared by the garbage collector whenever it feels like it. You can ask it to run (with System.gc()) but it is not guaranteed to run.

First try increasing the memory by setting -Xmx256m

tsc throws `TS2307: Cannot find module` for a local file

The vscode codebase does not use relative paths, but everything works fine for them

Really depends on your module loader. If you are using systemjs with baseurl then it would work. VSCode uses its own custom module loader (based on an old version of requirejs).

Recommendation

Use relative paths as that is what commonjs supports. If you move files around you will get a typescript compile time error (a good thing) so you will be better off than a great majority of pure js projects out there (on npm).

HTML5 Audio Looping

I did it this way,

<audio controls="controls" loop="loop">
<source src="someSound.ogg" type="audio/ogg" />
</audio>

and it looks like this

enter image description here

XMLHttpRequest status 0 (responseText is empty)

A browser request "127.0.0.1/somefile.html" arrives unchanged to the local webserver, while "localhost/somefile.html" may arrive as "0:0:0:0:0:0:0:1/somefile.html" if IPv6 is supported. So the latter can be processed as going from a domain to another.

Function stoi not declared

Add this option: -std=c++11 while compiling your code

g++ -std=c++11 my_cpp_code.cpp

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:

RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);

There, &rect is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.

The code should create a dynamic variable:

RectInvoice *rect =  new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);

There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.

Cheers

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

Alternative to mysql_real_escape_string without connecting to DB

Well, according to the mysql_real_escape_string function reference page: "mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which escapes the following characters: \x00, \n, \r, \, ', " and \x1a."

With that in mind, then the function given in the second link you posted should do exactly what you need:

function mres($value)
{
    $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a");
    $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");

    return str_replace($search, $replace, $value);
}

Check if input is number or letter javascript

Try this:

if(parseInt("0"+x, 10) > 0){/* x is integer */}

What's alternative to angular.copy in Angular

I have created a service to use with Angular 5 or higher, it uses the angular.copy() the base of angularjs, it works well for me. Additionally, there are other functions like isUndefined, etc. I hope it helps. Like any optimization, it would be nice to know. regards

_x000D_
_x000D_
import { Injectable } from '@angular/core';

@Injectable({providedIn: 'root'})
export class AngularService {

  private TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
  private stackSource = [];
  private stackDest = [];

  constructor() { }

  public isNumber(value: any): boolean {
    if ( typeof value === 'number' ) { return true; }
    else { return false; }
  }

  public isTypedArray(value: any) {
    return value && this.isNumber(value.length) && this.TYPED_ARRAY_REGEXP.test(toString.call(value));
  }

  public isArrayBuffer(obj: any) {
    return toString.call(obj) === '[object ArrayBuffer]';
  }

  public isUndefined(value: any) {return typeof value === 'undefined'; }

  public isObject(value: any) {  return value !== null && typeof value === 'object'; }

  public isBlankObject(value: any) {
    return value !== null && typeof value === 'object' && !Object.getPrototypeOf(value);
  }

  public isFunction(value: any) { return typeof value === 'function'; }

  public setHashKey(obj: any, h: any) {
    if (h) { obj.$$hashKey = h; }
    else { delete obj.$$hashKey; }
  }

  private isWindow(obj: any) { return obj && obj.window === obj; }

  private isScope(obj: any) { return obj && obj.$evalAsync && obj.$watch; }


  private copyRecurse(source: any, destination: any) {

    const h = destination.$$hashKey;

    if (Array.isArray(source)) {
      for (let i = 0, ii = source.length; i < ii; i++) {
        destination.push(this.copyElement(source[i]));
      }
    } else if (this.isBlankObject(source)) {
      for (const key of Object.keys(source)) {
        destination[key] = this.copyElement(source[key]);
      }
    } else if (source && typeof source.hasOwnProperty === 'function') {
      for (const key of Object.keys(source)) {
        destination[key] = this.copyElement(source[key]);
      }
    } else {
      for (const key of Object.keys(source)) {
        destination[key] = this.copyElement(source[key]);
      }
    }
    this.setHashKey(destination, h);
    return destination;
  }

  private copyElement(source: any) {

    if (!this.isObject(source)) {
      return source;
    }

    const index = this.stackSource.indexOf(source);

    if (index !== -1) {
      return this.stackDest[index];
    }

    if (this.isWindow(source) || this.isScope(source)) {
      throw console.log('Cant copy! Making copies of Window or Scope instances is not supported.');
    }

    let needsRecurse = false;
    let destination = this.copyType(source);

    if (destination === undefined) {
      destination = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));
      needsRecurse = true;
    }

    this.stackSource.push(source);
    this.stackDest.push(destination);

    return needsRecurse
      ? this.copyRecurse(source, destination)
      : destination;
  }

  private copyType = (source: any) => {

    switch (toString.call(source)) {
      case '[object Int8Array]':
      case '[object Int16Array]':
      case '[object Int32Array]':
      case '[object Float32Array]':
      case '[object Float64Array]':
      case '[object Uint8Array]':
      case '[object Uint8ClampedArray]':
      case '[object Uint16Array]':
      case '[object Uint32Array]':
        return new source.constructor(this.copyElement(source.buffer), source.byteOffset, source.length);

      case '[object ArrayBuffer]':
        if (!source.slice) {
          const copied = new ArrayBuffer(source.byteLength);
          new Uint8Array(copied).set(new Uint8Array(source));
          return copied;
        }
        return source.slice(0);

      case '[object Boolean]':
      case '[object Number]':
      case '[object String]':
      case '[object Date]':
        return new source.constructor(source.valueOf());

      case '[object RegExp]':
        const re = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
        re.lastIndex = source.lastIndex;
        return re;

      case '[object Blob]':
        return new source.constructor([source], {type: source.type});
    }

    if (this.isFunction(source.cloneNode)) {
      return source.cloneNode(true);
    }
  }

  public copy(source: any, destination?: any) {

    if (destination) {
      if (this.isTypedArray(destination) || this.isArrayBuffer(destination)) {
        throw console.log('Cant copy! TypedArray destination cannot be mutated.');
      }
      if (source === destination) {
        throw console.log('Cant copy! Source and destination are identical.');
      }

      if (Array.isArray(destination)) {
        destination.length = 0;
      } else {
        destination.forEach((value: any, key: any) => {
          if (key !== '$$hashKey') {
            delete destination[key];
          }
        });
      }

      this.stackSource.push(source);
      this.stackDest.push(destination);
      return this.copyRecurse(source, destination);
    }

    return this.copyElement(source);
  }
}
_x000D_
_x000D_
_x000D_

SQL Server table creation date query

In case you also want Schema:

SELECT CONCAT(ic.TABLE_SCHEMA, '.', st.name) as TableName
   ,st.create_date
   ,st.modify_date

FROM sys.tables st

JOIN INFORMATION_SCHEMA.COLUMNS ic ON ic.TABLE_NAME = st.name

GROUP BY ic.TABLE_SCHEMA, st.name, st.create_date, st.modify_date

ORDER BY st.create_date

How can I print variable and string on same line in Python?

use string format :

birth = 5.25487
print(f'''
{birth} 
''')

How do I exit a WPF application programmatically?

If you want to exit from another thread that didn't create the application object, use: System.Windows.Application.Current.Dispatcher.InvokeShutdown()

Regex to match URL end-of-line or "/" character

You've got a couple regexes now which will do what you want, so that's adequately covered.

What hasn't been mentioned is why your attempt won't work: Inside a character class, $ (as well as ^, ., and /) has no special meaning, so [/$] matches either a literal / or a literal $ rather than terminating the regex (/) or matching end-of-line ($).

How to set a timer in android

As I have seen it, java.util.Timer is the most used for implementing a timer.

For a repeating task:

new Timer().scheduleAtFixedRate(task, after, interval);

For a single run of a task:

new Timer().schedule(task, after);


task being the method to be executed
after the time to initial execution
(interval the time for repeating the execution)

Why do I get a warning icon when I add a reference to an MEF plugin project?

Check NETFramework of the referred dll & the Project where you are adding the DLL. Ex: DLL ==> supportedRuntime version="v4.0" Project ==> supportedRuntime version="v3.0"

You will get warning icon. Solution : Make dll version consistence across.

MVC 4 - how do I pass model data to a partial view?

I know question is specific to MVC4. But since we are way past MVC4 and if anyone looking for ASP.NET Core, you can use:

<partial name="_My_Partial" model="Model.MyInfo" />

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

How can I get zoom functionality for images?

UPDATE

I've just given TouchImageView a new update. It now includes Double Tap Zoom and Fling in addition to Panning and Pinch Zoom. The code below is very dated. You can check out the github project to get the latest code.

USAGE

Place TouchImageView.java in your project. It can then be used the same as ImageView. Example:

TouchImageView img = (TouchImageView) findViewById(R.id.img);

If you are using TouchImageView in xml, then you must provide the full package name, because it is a custom view. Example:

<com.example.touch.TouchImageView
    android:id="@+id/img”
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Note: I've removed my prior answer, which included some very old code and now link straight to the most updated code on github.

ViewPager

If you are interested in putting TouchImageView in a ViewPager, refer to this answer.

How to insert special characters into a database?

Are you escaping? Try the mysql_real_escape_string() function and it will handle the special characters.

Iterator Loop vs index loop

With a vector iterators do no offer any real advantage. The syntax is uglier, longer to type and harder to read.

Iterating over a vector using iterators is not faster and is not safer (actually if the vector is possibly resized during the iteration using iterators will put you in big troubles).

The idea of having a generic loop that works when you will change later the container type is also mostly nonsense in real cases. Unfortunately the dark side of a strictly typed language without serious typing inference (a bit better now with C++11, however) is that you need to say what is the type of everything at each step. If you change your mind later you will still need to go around and change everything. Moreover different containers have very different trade-offs and changing container type is not something that happens that often.

The only case in which iteration should be kept if possible generic is when writing template code, but that (I hope for you) is not the most frequent case.

The only problem present in your explicit index loop is that size returns an unsigned value (a design bug of C++) and comparison between signed and unsigned is dangerous and surprising, so better avoided. If you use a decent compiler with warnings enabled there should be a diagnostic on that.

Note that the solution is not to use an unsiged as the index, because arithmetic between unsigned values is also apparently illogical (it's modulo arithmetic, and x-1 may be bigger than x). You instead should cast the size to an integer before using it. It may make some sense to use unsigned sizes and indexes (paying a LOT of attention to every expression you write) only if you're working on a 16 bit C++ implementation (16 bit was the reason for having unsigned values in sizes).

As a typical mistake that unsigned size may introduce consider:

void drawPolyline(const std::vector<P2d>& points)
{
    for (int i=0; i<points.size()-1; i++)
        drawLine(points[i], points[i+1]);
}

Here the bug is present because if you pass an empty points vector the value points.size()-1 will be a huge positive number, making you looping into a segfault. A working solution could be

for (int i=1; i<points.size(); i++)
    drawLine(points[i - 1], points[i]);

but I personally prefer to always remove unsinged-ness with int(v.size()).

PS: If you really don't want to think by to yourself to the implications and simply want an expert to tell you then consider that a quite a few world recognized C++ experts agree and expressed opinions on that unsigned values are a bad idea except for bit manipulations.

Discovering the ugliness of using iterators in the case of iterating up to second-last is left as an exercise for the reader.

What is the difference between MySQL, MySQLi and PDO?

There are (more than) three popular ways to use MySQL from PHP. This outlines some features/differences PHP: Choosing an API:

  1. (DEPRECATED) The mysql functions are procedural and use manual escaping.
  2. MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements.
  3. PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases. It provides prepared statements, and significant flexibility in how data is returned.

I would recommend using PDO with prepared statements. It is a well-designed API and will let you more easily move to another database (including any that supports ODBC) if necessary.

Docker - Ubuntu - bash: ping: command not found

Every time you get this kind of error

bash: <command>: command not found
  • On a host with that command already working with this solution:

    dpkg -S $(which <command>)
    
  • Don't have a host with that package installed? Try this:

    apt-file search /bin/<command>
    

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

sure you can do that without using any addition, just pure javascript, by using this method of dns browser.dns.resolve("example.com"); but it is compatible just with FIREFOX 60 you can see more information on MDN https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/dns/resolve

How can I rename a project folder from within Visual Studio?

I was tryng to rename the folder within the visual studio community 2019 and could not find it.

However, I figured out that while the code is running you can not change the name of the folder.

The answer is:

  1. Stop your application from running;
  2. Then click on the folder with the right click and the rename name will be there.

How to install older version of node.js on Windows?

run:

npm install -g [email protected]

- or whatever version you want after the @ symbol (This works as of 2019)

Java Loop every minute

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();

Convert time fields to strings in Excel

This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:

I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM") , drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

Eureka ! Finally I found a solution on this.

This is caused by Windows update that stops any 32-bit processes from consuming more than 1200 MB on a 64-bit machine. The only way you can repair this is by using the System Restore option on Win 7.

Start >> All Programs >> Accessories >> System Tools >> System Restore.

And then restore to a date on which your Java worked fine. This worked for me. What is surprising here is Windows still pushes system updates under the name of "Critical Updates" even when you disable all windows updates. ^&%)#* Windows :-)

Javascript: How to loop through ALL DOM elements on a page?

from this link
javascript reference

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
function findhead1()
{
    var tag, tags;
    // or you can use var allElem=document.all; and loop on it
    tags = "The tags in the page are:"
    for(i = 0; i < document.all.length; i++)
    {
        tag = document.all(i).tagName;
        tags = tags + "\r" + tag;
    }
    document.write(tags);
}

//  -->
</script>
</head>
<body onload="findhead1()">
<h1>Heading One</h1>
</body>
</html>

UPDATE:EDIT

since my last answer i found better simpler solution

function search(tableEvent)
    {
        clearResults()

        document.getElementById('loading').style.display = 'block';

        var params = 'formAction=SearchStocks';

        var elemArray = document.mainForm.elements;
        for (var i = 0; i < elemArray.length;i++)
        {
            var element = elemArray[i];

            var elementName= element.name;
            if(elementName=='formAction')
                continue;
            params += '&' + elementName+'='+ encodeURIComponent(element.value);

        }

        params += '&tableEvent=' + tableEvent;


        createXmlHttpObject();

        sendRequestPost(http_request,'Controller',false,params);

        prepareUpdateTableContents();//function js to handle the response out of scope for this question

    }

onclick event pass <li> id or value

I prefer to use the HTML5 data API, check this documentation:

A example

_x000D_
_x000D_
$('#some-list li').click(function() {_x000D_
  var textLoaded = 'Loading element with id='_x000D_
         + $(this).data('id');_x000D_
   $('#loading-content').text(textLoaded);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul id='some-list'>_x000D_
  <li data-id='1'>One </li>_x000D_
  <li data-id='2'>Two </li>_x000D_
  <!-- ... more li -->_x000D_
  <li data-id='n'>Other</li>_x000D_
</ul>_x000D_
_x000D_
<h1 id='loading-content'></h1>
_x000D_
_x000D_
_x000D_

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

That's known as an Arrow Function, part of the ECMAScript 2015 spec...

_x000D_
_x000D_
var foo = ['a', 'ab', 'abc'];_x000D_
_x000D_
var bar = foo.map(f => f.length);_x000D_
_x000D_
console.log(bar); // 1,2,3
_x000D_
_x000D_
_x000D_

Shorter syntax than the previous:

_x000D_
_x000D_
// < ES6:_x000D_
var foo = ['a', 'ab', 'abc'];_x000D_
_x000D_
var bar = foo.map(function(f) {_x000D_
  return f.length;_x000D_
});_x000D_
console.log(bar); // 1,2,3
_x000D_
_x000D_
_x000D_

DEMO

The other awesome thing is lexical this... Usually, you'd do something like:

_x000D_
_x000D_
function Foo() {_x000D_
  this.name = name;_x000D_
  this.count = 0;_x000D_
  this.startCounting();_x000D_
}_x000D_
_x000D_
Foo.prototype.startCounting = function() {_x000D_
  var self = this;_x000D_
  setInterval(function() {_x000D_
    // this is the Window, not Foo {}, as you might expect_x000D_
    console.log(this); // [object Window]_x000D_
    // that's why we reassign this to self before setInterval()_x000D_
    console.log(self.count);_x000D_
    self.count++;_x000D_
  }, 1000)_x000D_
}_x000D_
_x000D_
new Foo();
_x000D_
_x000D_
_x000D_

But that could be rewritten with the arrow like this:

_x000D_
_x000D_
function Foo() {_x000D_
  this.name = name;_x000D_
  this.count = 0;_x000D_
  this.startCounting();_x000D_
}_x000D_
_x000D_
Foo.prototype.startCounting = function() {_x000D_
  setInterval(() => {_x000D_
    console.log(this); // [object Object]_x000D_
    console.log(this.count); // 1, 2, 3_x000D_
    this.count++;_x000D_
  }, 1000)_x000D_
}_x000D_
_x000D_
new Foo();
_x000D_
_x000D_
_x000D_

DEMO

MDN
More on Syntax

For more, here's a pretty good answer for when to use arrow functions.

Leverage browser caching, how on apache or .htaccess?

This is what I use to control headers/caching, I'm not an Apache pro, so let me know if there is room for improvement, but I know that this has been working well on all of my sites for some time now.

Mod_expires

http://httpd.apache.org/docs/2.2/mod/mod_expires.html

This module controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses. The expiration date can set to be relative to either the time the source file was last modified, or to the time of the client access.

These HTTP headers are an instruction to the client about the document's validity and persistence. If cached, the document may be fetched from the cache rather than from the source until this time has passed. After that, the cache copy is considered "expired" and invalid, and a new copy must be obtained from the source.

# BEGIN Expires
<ifModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 seconds"
ExpiresByType text/html "access plus 1 seconds"
ExpiresByType image/gif "access plus 2592000 seconds"
ExpiresByType image/jpeg "access plus 2592000 seconds"
ExpiresByType image/png "access plus 2592000 seconds"
ExpiresByType text/css "access plus 604800 seconds"
ExpiresByType text/javascript "access plus 216000 seconds"
ExpiresByType application/x-javascript "access plus 216000 seconds"
</ifModule>
# END Expires

Mod_headers

http://httpd.apache.org/docs/2.2/mod/mod_headers.html

This module provides directives to control and modify HTTP request and response headers. Headers can be merged, replaced or removed.

# BEGIN Caching
<ifModule mod_headers.c>
<filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
<filesMatch "\.(css)$">
Header set Cache-Control "max-age=604800, public"
</filesMatch>
<filesMatch "\.(js)$">
Header set Cache-Control "max-age=216000, private"
</filesMatch>
<filesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=216000, public, must-revalidate"
</filesMatch>
<filesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=1, private, must-revalidate"
</filesMatch>
</ifModule>
# END Caching

Cordova : Requirements check failed for JDK 1.8 or greater

I have (Open)JDK 8 and 11 installed on Windows 10 and I had the same problem. For me the following worked:

  1. Set JAVA_HOME to point to JDK 8. (Mentioned in many answers before.) AND
  2. Remove(!) JDK 11 from the PATH as it turned out that -- although displaying the JAVA_HOME path pointing to JDK 8 -- Cordova actually accessed JDK 11 that was included in the PATH, which made the Java version check fail.

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

My cause of issue seems very uncommon to me, not sure if anybody else gets the error under same condition, I found the cause by diffing previous commits, here you go :

Via my build.gradle I was using these 2 compiler options, and commenting out this line fixed the issue

//compileJava.options.compilerArgs = ['-Xlint:unchecked','-Xlint:deprecation']

Java HashMap: How to get a key and value by index?

You can use Kotlin extension function

fun LinkedHashMap<String, String>.getKeyByPosition(position: Int) =
        this.keys.toTypedArray()[position]


fun LinkedHashMap<String, String>.getValueByPosition(position: Int) =
        this.values.toTypedArray()[position]

List of all users that can connect via SSH

Any user whose login shell setting in /etc/passwd is an interactive shell can login. I don't think there's a totally reliable way to tell if a program is an interactive shell; checking whether it's in /etc/shells is probably as good as you can get.

Other users can also login, but the program they run should not allow them to get much access to the system. And users that aren't allowed to login at all should have /etc/false as their shell -- this will just log them out immediately.

jQuery function to open link in new window

Button click event only.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                $("#btnext").click(function () {                    
                    window.open("HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
                });
            });
</script>

Print text instead of value from C enum

Enumerations in C are numbers that have convenient names inside your code. They are not strings, and the names assigned to them in the source code are not compiled into your program, and so they are not accessible at runtime.

The only way to get what you want is to write a function yourself that translates the enumeration value into a string. E.g. (assuming here that you move the declaration of enum Days outside of main):

const char* getDayName(enum Days day) 
{
   switch (day) 
   {
      case Sunday: return "Sunday";
      case Monday: return "Monday";
      /* etc... */
   }
}

/* Then, later in main: */
printf("%s", getDayName(TheDay));

Alternatively, you could use an array as a map, e.g.

const char* dayNames[] = {"Sunday", "Monday", "Tuesday", /* ... etc ... */ };

/* ... */

printf("%s", dayNames[TheDay]);

But here you would probably want to assign Sunday = 0 in the enumeration to be safe... I'm not sure if the C standard requires compilers to begin enumerations from 0, although most do (I'm sure someone will comment to confirm or deny this).

How to get the xml node value in string

You should use .Load and not .LoadXML

MSDN Link

"The LoadXml method is for loading an XML string directly. You want to use the Load method instead."

ref : Link

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;
}

How to get value at a specific index of array In JavaScript?

Just use indexer

var valueAtIndex1 = myValues[1];

How to read .pem file to get private and public key

One option is to use bouncycastle's PEMParser:

Class for parsing OpenSSL PEM encoded streams containing X509 certificates, PKCS8 encoded keys and PKCS7 objects.

In the case of PKCS7 objects the reader will return a CMS ContentInfo object. Public keys will be returned as well formed SubjectPublicKeyInfo objects, private keys will be returned as well formed PrivateKeyInfo objects. In the case of a private key a PEMKeyPair will normally be returned if the encoding contains both the private and public key definition. CRLs, Certificates, PKCS#10 requests, and Attribute Certificates will generate the appropriate BC holder class.

Here is an example of using the Parser test code:

package org.bouncycastle.openssl.test;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.cms.CMSObjectIdentifiers;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMDecryptorProvider;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.openssl.PasswordFinder;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
import org.bouncycastle.util.test.SimpleTest;

/**
 * basic class for reading test.pem - the password is "secret"
 */
public class ParserTest
    extends SimpleTest
{
    private static class Password
        implements PasswordFinder
    {
        char[]  password;

        Password(
            char[] word)
        {
            this.password = word;
        }

        public char[] getPassword()
        {
            return password;
        }
    }

    public String getName()
    {
        return "PEMParserTest";
    }

    private PEMParser openPEMResource(
        String          fileName)
    {
        InputStream res = this.getClass().getResourceAsStream(fileName);
        Reader fRd = new BufferedReader(new InputStreamReader(res));
        return new PEMParser(fRd);
    }

    public void performTest()
        throws Exception
    {
        PEMParser       pemRd = openPEMResource("test.pem");
        Object          o;
        PEMKeyPair      pemPair;
        KeyPair         pair;

        while ((o = pemRd.readObject()) != null)
        {
            if (o instanceof KeyPair)
            {
                //pair = (KeyPair)o;

                //System.out.println(pair.getPublic());
                //System.out.println(pair.getPrivate());
            }
            else
            {
                //System.out.println(o.toString());
            }
        }

        // test bogus lines before begin are ignored.
        pemRd = openPEMResource("extratest.pem");

        while ((o = pemRd.readObject()) != null)
        {
            if (!(o instanceof X509CertificateHolder))
            {
                fail("wrong object found");
            }
        }

        //
        // pkcs 7 data
        //
        pemRd = openPEMResource("pkcs7.pem");
        ContentInfo d = (ContentInfo)pemRd.readObject();

        if (!d.getContentType().equals(CMSObjectIdentifiers.envelopedData))
        {
            fail("failed envelopedData check");
        }

        //
        // ECKey
        //
        pemRd = openPEMResource("eckey.pem");
        ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier)pemRd.readObject();
        X9ECParameters ecSpec = ECNamedCurveTable.getByOID(ecOID);

        if (ecSpec == null)
        {
            fail("ecSpec not found for named curve");
        }

        pemPair = (PEMKeyPair)pemRd.readObject();

        pair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemPair);

        Signature sgr = Signature.getInstance("ECDSA", "BC");

        sgr.initSign(pair.getPrivate());

        byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

        sgr.update(message);

        byte[]  sigBytes = sgr.sign();

        sgr.initVerify(pair.getPublic());

        sgr.update(message);

        if (!sgr.verify(sigBytes))
        {
            fail("EC verification failed");
        }

        if (!pair.getPublic().getAlgorithm().equals("ECDSA"))
        {
            fail("wrong algorithm name on public got: " + pair.getPublic().getAlgorithm());
        }

        if (!pair.getPrivate().getAlgorithm().equals("ECDSA"))
        {
            fail("wrong algorithm name on private");
        }

        //
        // ECKey -- explicit parameters
        //
        pemRd = openPEMResource("ecexpparam.pem");
        ecSpec = (X9ECParameters)pemRd.readObject();

        pemPair = (PEMKeyPair)pemRd.readObject();

        pair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemPair);

        sgr = Signature.getInstance("ECDSA", "BC");

        sgr.initSign(pair.getPrivate());

        message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

        sgr.update(message);

        sigBytes = sgr.sign();

        sgr.initVerify(pair.getPublic());

        sgr.update(message);

        if (!sgr.verify(sigBytes))
        {
            fail("EC verification failed");
        }

        if (!pair.getPublic().getAlgorithm().equals("ECDSA"))
        {
            fail("wrong algorithm name on public got: " + pair.getPublic().getAlgorithm());
        }

        if (!pair.getPrivate().getAlgorithm().equals("ECDSA"))
        {
            fail("wrong algorithm name on private");
        }

        //
        // writer/parser test
        //
        KeyPairGenerator      kpGen = KeyPairGenerator.getInstance("RSA", "BC");

        pair = kpGen.generateKeyPair();

        keyPairTest("RSA", pair);

        kpGen = KeyPairGenerator.getInstance("DSA", "BC");
        kpGen.initialize(512, new SecureRandom());
        pair = kpGen.generateKeyPair();

        keyPairTest("DSA", pair);

        //
        // PKCS7
        //
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        PEMWriter             pWrt = new PEMWriter(new OutputStreamWriter(bOut));

        pWrt.writeObject(d);

        pWrt.close();

        pemRd = new PEMParser(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())));
        d = (ContentInfo)pemRd.readObject();

        if (!d.getContentType().equals(CMSObjectIdentifiers.envelopedData))
        {
            fail("failed envelopedData recode check");
        }


        // OpenSSL test cases (as embedded resources)
        doOpenSslDsaTest("unencrypted");
        doOpenSslRsaTest("unencrypted");

        doOpenSslTests("aes128");
        doOpenSslTests("aes192");
        doOpenSslTests("aes256");
        doOpenSslTests("blowfish");
        doOpenSslTests("des1");
        doOpenSslTests("des2");
        doOpenSslTests("des3");
        doOpenSslTests("rc2_128");

        doOpenSslDsaTest("rc2_40_cbc");
        doOpenSslRsaTest("rc2_40_cbc");
        doOpenSslDsaTest("rc2_64_cbc");
        doOpenSslRsaTest("rc2_64_cbc");

        doDudPasswordTest("7fd98", 0, "corrupted stream - out of bounds length found");
        doDudPasswordTest("ef677", 1, "corrupted stream - out of bounds length found");
        doDudPasswordTest("800ce", 2, "unknown tag 26 encountered");
        doDudPasswordTest("b6cd8", 3, "DEF length 81 object truncated by 56");
        doDudPasswordTest("28ce09", 4, "DEF length 110 object truncated by 28");
        doDudPasswordTest("2ac3b9", 5, "DER length more than 4 bytes: 11");
        doDudPasswordTest("2cba96", 6, "DEF length 100 object truncated by 35");
        doDudPasswordTest("2e3354", 7, "DEF length 42 object truncated by 9");
        doDudPasswordTest("2f4142", 8, "DER length more than 4 bytes: 14");
        doDudPasswordTest("2fe9bb", 9, "DER length more than 4 bytes: 65");
        doDudPasswordTest("3ee7a8", 10, "DER length more than 4 bytes: 57");
        doDudPasswordTest("41af75", 11, "unknown tag 16 encountered");
        doDudPasswordTest("1704a5", 12, "corrupted stream detected");
        doDudPasswordTest("1c5822", 13, "unknown object in getInstance: org.bouncycastle.asn1.DERUTF8String");
        doDudPasswordTest("5a3d16", 14, "corrupted stream detected");
        doDudPasswordTest("8d0c97", 15, "corrupted stream detected");
        doDudPasswordTest("bc0daf", 16, "corrupted stream detected");
        doDudPasswordTest("aaf9c4d",17, "corrupted stream - out of bounds length found");

        doNoPasswordTest();

        // encrypted private key test
        InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().build("password".toCharArray());
        pemRd = openPEMResource("enckey.pem");

        PKCS8EncryptedPrivateKeyInfo encPrivKeyInfo = (PKCS8EncryptedPrivateKeyInfo)pemRd.readObject();
        JcaPEMKeyConverter   converter = new JcaPEMKeyConverter().setProvider("BC");

        RSAPrivateCrtKey privKey = (RSAPrivateCrtKey)converter.getPrivateKey(encPrivKeyInfo.decryptPrivateKeyInfo(pkcs8Prov));

        if (!privKey.getPublicExponent().equals(new BigInteger("10001", 16)))
        {
            fail("decryption of private key data check failed");
        }

        // general PKCS8 test

        pemRd = openPEMResource("pkcs8test.pem");

        Object privInfo;

        while ((privInfo = pemRd.readObject()) != null)
        {
            if (privInfo instanceof PrivateKeyInfo)
            {
                privKey = (RSAPrivateCrtKey)converter.getPrivateKey(PrivateKeyInfo.getInstance(privInfo));
            }
            else
            {
                privKey = (RSAPrivateCrtKey)converter.getPrivateKey(((PKCS8EncryptedPrivateKeyInfo)privInfo).decryptPrivateKeyInfo(pkcs8Prov));
            }
            if (!privKey.getPublicExponent().equals(new BigInteger("10001", 16)))
            {
                fail("decryption of private key data check failed");
            }
        }
    }

    private void keyPairTest(
        String   name,
        KeyPair pair) 
        throws IOException
    {
        PEMParser pemRd;
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        PEMWriter             pWrt = new PEMWriter(new OutputStreamWriter(bOut));

        pWrt.writeObject(pair.getPublic());

        pWrt.close();

        pemRd = new PEMParser(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())));

        SubjectPublicKeyInfo pub = SubjectPublicKeyInfo.getInstance(pemRd.readObject());
        JcaPEMKeyConverter   converter = new JcaPEMKeyConverter().setProvider("BC");

        PublicKey k = converter.getPublicKey(pub);

        if (!k.equals(pair.getPublic()))
        {
            fail("Failed public key read: " + name);
        }

        bOut = new ByteArrayOutputStream();
        pWrt = new PEMWriter(new OutputStreamWriter(bOut));

        pWrt.writeObject(pair.getPrivate());

        pWrt.close();

        pemRd = new PEMParser(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())));

        KeyPair kPair = converter.getKeyPair((PEMKeyPair)pemRd.readObject());
        if (!kPair.getPrivate().equals(pair.getPrivate()))
        {
            fail("Failed private key read: " + name);
        }

        if (!kPair.getPublic().equals(pair.getPublic()))
        {
            fail("Failed private key public read: " + name);
        }
    }

    private void doOpenSslTests(
        String baseName)
        throws IOException
    {
        doOpenSslDsaModesTest(baseName);
        doOpenSslRsaModesTest(baseName);
    }

    private void doOpenSslDsaModesTest(
        String baseName)
        throws IOException
    {
        doOpenSslDsaTest(baseName + "_cbc");
        doOpenSslDsaTest(baseName + "_cfb");
        doOpenSslDsaTest(baseName + "_ecb");
        doOpenSslDsaTest(baseName + "_ofb");
    }

    private void doOpenSslRsaModesTest(
        String baseName)
        throws IOException
    {
        doOpenSslRsaTest(baseName + "_cbc");
        doOpenSslRsaTest(baseName + "_cfb");
        doOpenSslRsaTest(baseName + "_ecb");
        doOpenSslRsaTest(baseName + "_ofb");
    }

    private void doOpenSslDsaTest(
        String name)
        throws IOException
    {
        String fileName = "dsa/openssl_dsa_" + name + ".pem";

        doOpenSslTestFile(fileName, DSAPrivateKey.class);
    }

    private void doOpenSslRsaTest(
        String name)
        throws IOException
    {
        String fileName = "rsa/openssl_rsa_" + name + ".pem";

        doOpenSslTestFile(fileName, RSAPrivateKey.class);
    }

    private void doOpenSslTestFile(
        String  fileName,
        Class   expectedPrivKeyClass)
        throws IOException
    {
        JcaPEMKeyConverter   converter = new JcaPEMKeyConverter().setProvider("BC");
        PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().setProvider("BC").build("changeit".toCharArray());
        PEMParser pr = openPEMResource("data/" + fileName);
        Object o = pr.readObject();

        if (o == null || !((o instanceof PEMKeyPair) || (o instanceof PEMEncryptedKeyPair)))
        {
            fail("Didn't find OpenSSL key");
        }

        KeyPair kp = (o instanceof PEMEncryptedKeyPair) ?
            converter.getKeyPair(((PEMEncryptedKeyPair)o).decryptKeyPair(decProv)) : converter.getKeyPair((PEMKeyPair)o);

        PrivateKey privKey = kp.getPrivate();

        if (!expectedPrivKeyClass.isInstance(privKey))
        {
            fail("Returned key not of correct type");
        }
    }

    private void doDudPasswordTest(String password, int index, String message)
    {
        // illegal state exception check - in this case the wrong password will
        // cause an underlying class cast exception.
        try
        {
            PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().setProvider("BC").build(password.toCharArray());

            PEMParser pemRd = openPEMResource("test.pem");
            Object o;

            while ((o = pemRd.readObject()) != null)
            {
                if (o instanceof PEMEncryptedKeyPair)
                {
                    ((PEMEncryptedKeyPair)o).decryptKeyPair(decProv);
                }
            }

            fail("issue not detected: " + index);
        }
        catch (IOException e)
        {
            if (e.getCause() != null && !e.getCause().getMessage().endsWith(message))
            {
               fail("issue " + index + " exception thrown, but wrong message");
            }
            else if (e.getCause() == null && !e.getMessage().equals(message))
            {
                               e.printStackTrace();
               fail("issue " + index + " exception thrown, but wrong message");
            }
        }
    }

    private void doNoPasswordTest()
        throws IOException
    {
        PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().setProvider("BC").build("".toCharArray());

        PEMParser pemRd = openPEMResource("smimenopw.pem");
        Object o;
        PrivateKeyInfo key = null;

        while ((o = pemRd.readObject()) != null)
        {
             key = (PrivateKeyInfo)o;
        }

        if (key == null)
        {
            fail("private key not detected");
        }
    }

    public static void main(
        String[]    args)
    {
        Security.addProvider(new BouncyCastleProvider());

        runTest(new ParserTest());
    }
}

CSS set li indent

Also try:

ul {
  list-style-position: inside;
}

Converting a double to an int in C#

ToInt32 rounds. Casting to int just throws away the non-integer component.

Extracting time from POSIXct

There have been previous answers that showed the trick. In essence:

  • you must retain POSIXct types to take advantage of all the existing plotting functions

  • if you want to 'overlay' several days worth on a single plot, highlighting the intra-daily variation, the best trick is too ...

  • impose the same day (and month and even year if need be, which is not the case here)

which you can do by overriding the day-of-month and month components when in POSIXlt representation, or just by offsetting the 'delta' relative to 0:00:00 between the different days.

So with times and val as helpfully provided by you:

## impose month and day based on first obs
ntimes <- as.POSIXlt(times)    # convert to 'POSIX list type'
ntimes$mday <- ntimes[1]$mday  # and $mon if it differs too
ntimes <- as.POSIXct(ntimes)   # convert back

par(mfrow=c(2,1))
plot(times,val)   # old times
plot(ntimes,val)  # new times

yields this contrasting the original and modified time scales:

enter image description here

PHP code to convert a MySQL query to CSV

If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine)

These functions setup the headers:

function setExcelContentType() {
    if(headers_sent())
        return false;

    header('Content-type: application/vnd.ms-excel');
    return true;
}

function setDownloadAsHeader($filename) {
    if(headers_sent())
        return false;

    header('Content-disposition: attachment; filename=' . $filename);
    return true;
}

This one sends a CSV to a stream using a mysql result

function csvFromResult($stream, $result, $showColumnHeaders = true) {
    if($showColumnHeaders) {
        $columnHeaders = array();
        $nfields = mysql_num_fields($result);
        for($i = 0; $i < $nfields; $i++) {
            $field = mysql_fetch_field($result, $i);
            $columnHeaders[] = $field->name;
        }
        fputcsv($stream, $columnHeaders);
    }

    $nrows = 0;
    while($row = mysql_fetch_row($result)) {
        fputcsv($stream, $row);
        $nrows++;
    }

    return $nrows;
}

This one uses the above function to write a CSV to a file, given by $filename

function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
    $fp = fopen($filename, 'w');
    $rc = csvFromResult($fp, $result, $showColumnHeaders);
    fclose($fp);
    return $rc;
}

And this is where the magic happens ;)

function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
    setExcelContentType();
    setDownloadAsHeader($asFilename);
    return csvFileFromResult('php://output', $result, $showColumnHeaders);
}

For example:

$result = mysql_query("SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'");
csvToExcelDownloadFromResult($result);

How to get SLF4J "Hello World" working with log4j?

Following is an example. You can see the details http://jkssweetlife.com/configure-slf4j-working-various-logging-frameworks/ and download the full codes here.

  • Add following dependency to your pom if you are using maven, otherwise, just download the jar files and put on your classpath

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
    </dependency>
    
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>
    
  • Configure log4j.properties

    log4j.rootLogger=TRACE, stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.SSS} %-5p [%c] - %m%n
    
  • Java example

    public class Slf4jExample {
        public static void main(String[] args) {
    
            Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
    
            final String message = "Hello logging!";
            logger.trace(message);
            logger.debug(message);
            logger.info(message);
            logger.warn(message);
            logger.error(message);
        }
    }
    

How do I validate a date string format in python?

The Python dateutil library is designed for this (and more). It will automatically convert this to a datetime object for you and raise a ValueError if it can't.

As an example:

>>> from dateutil.parser import parse
>>> parse("2003-09-25")
datetime.datetime(2003, 9, 25, 0, 0)

This raises a ValueError if the date is not formatted correctly:

>>> parse("2003-09-251")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 720, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 317, in parse
    ret = default.replace(**repl)
ValueError: day is out of range for month

dateutil is also extremely useful if you start needing to parse other formats in the future, as it can handle most known formats intelligently and allows you to modify your specification: dateutil parsing examples.

It also handles timezones if you need that.

Update based on comments: parse also accepts the keyword argument dayfirst which controls whether the day or month is expected to come first if a date is ambiguous. This defaults to False. E.g.

>>> parse('11/12/2001')
>>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12
>>> parse('11/12/2001', dayfirst=True)
>>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11

What is the difference between print and puts?

puts call the to_s of each argument and adds a new line to each string, if it does not end with new line. print just output each argument by calling their to_s.

for example: puts "one two": one two

{new line}

puts "one two\n": one two

{new line} #puts will not add a new line to the result, since the string ends with a new line

print "one two": one two

print "one two\n": one two

{new line}

And there is another way to output: p

For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

It is helpful to output debugging message. p "aa\n\t": aa\n\t

How to convert string to long

String s = "1";

try {
   long l = Long.parseLong(s);       
} catch (NumberFormatException e) {
   System.out.println("NumberFormatException: " + e.getMessage());
}

MySQL foreign key constraints, cascade delete

If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:

CREATE TABLE categories (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE products (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE categories_products (
    category_id int unsigned not null,
    product_id int unsigned not null,
    PRIMARY KEY (category_id, product_id),
    KEY pkey (product_id),
    FOREIGN KEY (category_id) REFERENCES categories (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
)Engine=InnoDB;

This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.

e.g.

products: boots, mittens, hats, coats
categories: red, green, blue, white, black

prod/cats: red boots, green mittens, red coats, black hats

If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.

The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.

comment followup:

you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.

Here's a more concrete example:

categories:     products:
+----+------+   +----+---------+
| id | name |   | id | name    |
+----+------+   +----+---------+
| 1  | red  |   | 1  | mittens |
| 2  | blue |   | 2  | boots   |
+---++------+   +----+---------+

products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 1          | 2           | // blue mittens
| 2          | 1           | // red boots
| 2          | 2           | // blue boots
+------------+-------------+

Let's say you delete category #2 (blue):

DELETE FROM categories WHERE (id = 2);

the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories, you end up with this table once the delete completes:

+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 2          | 1           | // red boots
+------------+-------------+

There's no foreign key defined in the products table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.

How to clear a chart from a canvas so that hover events cannot be triggered?

I couldn't get .destroy() to work either so this is what I'm doing. The chart_parent div is where I want the canvas to show up. I need the canvas to resize each time, so this answer is an extension of the above one.

HTML:

<div class="main_section" > <div id="chart_parent"></div> <div id="legend"></div> </div>

JQuery:

  $('#chart').remove(); // this is my <canvas> element
  $('#chart_parent').append('<label for = "chart">Total<br /><canvas class="chart" id="chart" width='+$('#chart_parent').width()+'><canvas></label>');

Suppress command line output

mysqldump doesn't work with: >nul 2>&1
Instead use: 2> nul
This suppress the stderr message: "Warning: Using a password on the command line interface can be insecure"

docker cannot start on windows

I too faced error which says

"Access is denied. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running."

Resolved this by running "powershell" in administrator mode.

This solution will help those who uses two users on one windows machine

Deprecated: mysql_connect()

That is because you are using PHP 5.5 or your webserver would have been upgraded to 5.5.0.

The mysql_* functions has been deprecated as of 5.5.0

enter image description here

Source

static constructors in C++? I need to initialize private static objects

Test::StaticTest() is called exactly once during global static initialization.

Caller only has to add one line to the function that is to be their static constructor.

static_constructor<&Test::StaticTest>::c; forces initialization of c during global static initialization.

template<void(*ctor)()>
struct static_constructor
{
    struct constructor { constructor() { ctor(); } };
    static constructor c;
};

template<void(*ctor)()>
typename static_constructor<ctor>::constructor static_constructor<ctor>::c;

/////////////////////////////

struct Test
{
    static int number;

    static void StaticTest()
    {
        static_constructor<&Test::StaticTest>::c;

        number = 123;
        cout << "static ctor" << endl;
    }
};

int Test::number;

int main(int argc, char *argv[])
{
    cout << Test::number << endl;
    return 0;
}

Plot yerr/xerr as shaded region rather than error bars

This is basically the same answer provided by Evert, but extended to show-off some cool options of fill_between

enter image description here

from matplotlib import pyplot as pl
import numpy as np

pl.clf()
pl.hold(1)

x = np.linspace(0, 30, 100)
y = np.sin(x) * 0.5
pl.plot(x, y, '-k')


x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape) +.1
y += np.random.normal(0, 0.1, size=y.shape)

pl.plot(x, y, 'k', color='#CC4F1B')
pl.fill_between(x, y-error, y+error,
    alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848')

y = np.cos(x/6*np.pi)    
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#1B2ACC')
pl.fill_between(x, y-error, y+error,
    alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
    linewidth=4, linestyle='dashdot', antialiased=True)



y = np.cos(x/6*np.pi)  + np.sin(x/3*np.pi)  
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#3F7F4C')
pl.fill_between(x, y-error, y+error,
    alpha=1, edgecolor='#3F7F4C', facecolor='#7EFF99',
    linewidth=0)



pl.show()

Filter by Dates in SQL

If your dates column does not contain time information, you could get away with:

WHERE dates BETWEEN '20121211' and '20121213'

However, given your dates column is actually datetime, you want this

WHERE dates >= '20121211'
  AND dates < '20121214'  -- i.e. 00:00 of the next day

Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:

WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'

Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.

Verify host key with pysftp

I've implemented auto_add_key in my pysftp github fork.

auto_add_key will add the key to known_hosts if auto_add_key=True
Once a key is present for a host in known_hosts this key will be checked.

Please reffer Martin Prikryl -> answer about security concerns.

Though for an absolute security, you should not retrieve the host key remotely, as you cannot be sure, if you are not being attacked already.

import pysftp as sftp

def push_file_to_server():
    s = sftp.Connection(host='138.99.99.129', username='root', password='pass', auto_add_key=True)
    local_path = "testme.txt"
    remote_path = "/home/testme.txt"

    s.put(local_path, remote_path)
    s.close()

push_file_to_server()

Note: Why using context manager

import pysftp
with pysftp.Connection(host, username="whatever", password="whatever", auto_add_key=True) as sftp:
    #do your stuff here
#connection closed

FIFO based Queue implementations?

ArrayDeque is probably the fastest object-based queue in the JDK; Trove has the TIntQueue interface, but I don't know where its implementations live.

PHP CURL DELETE request

switch ($method) {
    case "GET":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
        break;
    case "POST":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        break;
    case "PUT":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
        break;
    case "DELETE":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
        break;
}

Differences between cookies and sessions?

A cookie is simply a short text string that is sent back and forth between the client and the server. You could store name=bob; password=asdfas in a cookie and send that back and forth to identify the client on the server side. You could think of this as carrying on an exchange with a bank teller who has no short term memory, and needs you to identify yourself for each and every transaction. Of course using a cookie to store this kind information is horrible insecure. Cookies are also limited in size.

Now, when the bank teller knows about his/her memory problem, He/She can write down your information on a piece of paper and assign you a short id number. Then, instead of giving your account number and driver's license for each transaction, you can just say "I'm client 12"

Translating that to Web Servers: The server will store the pertinent information in the session object, and create a session ID which it will send back to the client in a cookie. When the client sends back the cookie, the server can simply look up the session object using the ID. So, if you delete the cookie, the session will be lost.

One other alternative is for the server to use URL rewriting to exchange the session id.

Suppose you had a link - www.myserver.com/myApp.jsp You could go through the page and rewrite every URL as www.myserver.com/myApp.jsp?sessionID=asdf or even www.myserver.com/asdf/myApp.jsp and exchange the identifier that way. This technique is handled by the web application container and is usually turned on by setting the configuration to use cookieless sessions.

jQuery add blank option to top of list and make selected to existing dropdown

This worked:

$("#theSelectId").prepend("<option value='' selected='selected'></option>");

Firebug Output:

<select id="theSelectId">
  <option selected="selected" value=""/>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You could also use .prependTo if you wanted to reverse the order:

?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????

Exception of type 'System.OutOfMemoryException' was thrown. Why?

Perhaps you're not disposing of the previous connection/ result classes from the previous run which means their still hanging around in memory.

Spring - applicationContext.xml cannot be opened because it does not exist

I also found this problem. What do did to solve this is to copy/paste this file everywhere and run, one file a time. Finally it compiled and ran successfully, and then delete the unnecessary ones. The correct place in my situation is: enter image description here

This is under the /src/ path (I am using Intellij Idea as the IDE). The other java source files are under /src/com/package/ path

Hope it helpes.

Using arrays or std::vectors in C++, what's the performance gap?

Vectors are arrays under the hood. The performance is the same.

One place where you can run into a performance issue, is not sizing the vector correctly to begin with.

As a vector fills, it will resize itself, and that can imply, a new array allocation, followed by n copy constructors, followed by about n destructor calls, followed by an array delete.

If your construct/destruct is expensive, you are much better off making the vector the correct size to begin with.

There is a simple way to demonstrate this. Create a simple class that shows when it is constructed/destroyed/copied/assigned. Create a vector of these things, and start pushing them on the back end of the vector. When the vector fills, there will be a cascade of activity as the vector resizes. Then try it again with the vector sized to the expected number of elements. You will see the difference.

Image comparison - fast algorithm

The best method I know of is to use a Perceptual Hash. There appears to be a good open source implementation of such a hash available at:

http://phash.org/

The main idea is that each image is reduced down to a small hash code or 'fingerprint' by identifying salient features in the original image file and hashing a compact representation of those features (rather than hashing the image data directly). This means that the false positives rate is much reduced over a simplistic approach such as reducing images down to a tiny thumbprint sized image and comparing thumbprints.

phash offers several types of hash and can be used for images, audio or video.

JNZ & CMP Assembly Instructions

You can read JNE/Z as *

Jump if the status is "Not set" on Equal/Zero flag

"Not set" is a status when "equal/zero flag" in the CPU is set to 0 which only happens when the condition is met or equally matched.

Extracting extension from filename in Python

Another solution with right split:

# to get extension only

s = 'test.ext'

if '.' in s: ext = s.rsplit('.', 1)[1]

# or, to get file name and extension

def split_filepath(s):
    """
    get filename and extension from filepath 
    filepath -> (filename, extension)
    """
    if not '.' in s: return (s, '')
    r = s.rsplit('.', 1)
    return (r[0], r[1])

What is the easiest way to remove all packages installed by pip?

In Command Shell of Windows, the command pip freeze | xargs pip uninstall -y won't work. So for those of you using Windows, I've figured out an alternative way to do so.

  1. Copy all the names of the installed packages of pip from the pip freeze command to a .txt file.
  2. Then, go the location of your .txt file and run the command pip uninstall -r *textfile.txt*

CSS force new line

or you can use:

a {
    display: inline-block;
  }

Cast object to T

You can presumably pass-in, as a parameter, a delegate which will convert from string to T.

eslint: error Parsing error: The keyword 'const' is reserved

If using Visual Code one option is to add this to the settings.json file:

"eslint.options": {
    "useEslintrc": false,
    "parserOptions": {
        "ecmaVersion": 2017
    },
    "env": {
        "es6": true
    }
}

how to call a variable in code behind to aspx page

You need to declare your clients variable as public, e.g.

public string clients;

but you should probably do it as a Property, e.g.

private string clients;
public string Clients{ get{ return clients; } set {clients = value;} }

And then you can call it in your .aspx page like this:

<%=Clients%>

Variables in C# are private by default. Read more on access modifiers in C# on MSDN and properties in C# on MSDN

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

Tools -> Build System -> New Build System. The type following as your OS, save as Chrome.sublime-build

Windows OS

  {
        "cmd": ["C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "$file"]
  }

MAC Os

{
   "cmd": ["open", "-a", "/Applications/Google Chrome.app", "$file"]
}

Save the file - Chrome.sublime-build in location

C:\Users\xnivirro\Downloads\Software-Installed\Sublime-2\Data\Packages\User

Sublime View in Browswer - https://github.com/adampresley/sublime-view-in-browser (Tried with Linux and it works)

How to remove duplicate values from an array in PHP

It can be done through function I made three function duplicate returns the values which are duplicate in array.

Second function single return only those values which are single mean not repeated in array and third and full function return all values but not duplicated if any value is duplicated it convert it to single;

function duplicate($arr) {
    $duplicate;
    $count = array_count_values($arr);
    foreach($arr as $key => $value) {
        if ($count[$value] > 1) {
            $duplicate[$value] = $value;
        }
    }
    return $duplicate;
}
function single($arr) {
    $single;
    $count = array_count_values($arr);
    foreach($arr as $key => $value) {
        if ($count[$value] == 1) {
            $single[$value] = $value;
        }
    }
    return $single;
}
function full($arr, $arry) {
    $full = $arr + $arry;
    sort($full);
    return $full;
}

PHP using Gettext inside <<<EOF string

As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:

<p>Hello</p>
<p><?= _("World"); ?></p>

Viewing contents of a .jar file

You can open them with most decompression utilities these days, then just get something like DJ Java Decompiler if you want to view the source.

RuntimeWarning: invalid value encountered in divide

I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

For more details see:

Remove scroll bar track from ScrollView in Android

try this is your activity onCreate:

ScrollView sView = (ScrollView)findViewById(R.id.deal_web_view_holder);
// Hide the Scollbar
sView.setVerticalScrollBarEnabled(false);
sView.setHorizontalScrollBarEnabled(false);

http://developer.android.com/reference/android/view/View.html#setVerticalScrollBarEnabled%28boolean%29

How to fade changing background image

Opacity serves your purpose?

If so, try this:

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

Chart.js canvas resize

If anyone is having problems, I found a solution that doesn't involve sacrificing responsiveness etc.

Simply wrap your canvas in a div container (no styling) and reset the contents of the div to an empty canvas with ID before calling the Chart constructor.

Example:

HTML:

<div id="chartContainer">
    <canvas id="myChart"></canvas>
</div>

JS:

$("#chartContainer").html('<canvas id="myChart"></canvas>');
//call new Chart() as usual

Eclipse interface icons very small on high resolution screen in Windows 8.1

I have looked up solutions for this issue for the last month, but I have not found an ideal solution yet. It seems there should be a way around it, but I just can't find it.

I use a laptop with a 2560x1600 screen with the 200% magnification setting in Windows 8.1 (which makes it looking like a 1280x800 screen but clearer).

Applications that support such "HiDPI" mode look just gorgeous, but the ones that don't (e.g. Eclipse) show tiny icons that are almost unreadable.

I also use an outdated version of Visual Studio. That has not been updated for HiDPI (obviously MS wants me to use a newer version of VS), but it still works kind of ok with HiDPI screens since it just scales things up twice -- the sizes of icons and letters are normal but they look lower-resolution.

After I saw how VS works, I began looking up a way to launch Eclipse in the same mode since it would not be technically very hard to just scale things up like how VS does. I thought there would be an option I could set to launch Eclipse in that mode. I couldn't find it though.

After all, I ended up lowering the screen resolution to 1/4 (from 2560x1600 to 1280x800) with no magnification (from 200% to 100%) and not taking advantage of the high-resolution screen until Eclipse gets updated to support it since I had to do some work, but I am desparately waiting for an answer to this issue.

Bootstrap Navbar toggle button not working

Your code looks great, the only thing i see is that you did not include the collapsed class in your button selector. http://www.bootply.com/cpHugxg2f8 Note: Requires JavaScript plugin If JavaScript is disabled and the viewport is narrow enough that the navbar collapses, it will be impossible to expand the navbar and view the content within the .navbar-collapse.

The responsive navbar requires the collapse plugin to be included in your version of Bootstrap.

<div class="navbar-wrapper">
      <div class="container">

        <nav class="navbar navbar-inverse navbar-static-top">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">Project name</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
              <ul class="nav navbar-nav">
                    <li><a href="">Page 1</a>
                    </li>
                    <li><a href="">Page 2</a>
                    </li>
                    <li><a href="">Page 3</a>
                    </li>

              </ul>
            </div>
          </div>
        </nav>

      </div>
    </div>

Passing a variable to a powershell script via command line

Declare the parameter in test.ps1:

 Param(
                [Parameter(Mandatory=$True,Position=1)]
                [string]$input_dir,
                [Parameter(Mandatory=$True)]
                [string]$output_dir,
                [switch]$force = $false
                )

Run the script from Run OR Windows Task Scheduler:

powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"

or,

 powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"

Javascript search inside a JSON object

You can try this:

function search(data,search) {
    var obj = [], index=0;
    for(var i=0; i<data.length; i++) {
      for(key in data[i]){
         if(data[i][key].toString().toLowerCase().indexOf(search.toLowerCase())!=-1) {
                obj[index] = data[i];
                index++;
                break;
         }
     }
     return obj;
}
console.log(search(obj.list,'my Name'));

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

CSS selector:

Use a CSS selector of img[src='images/toolbar/b_edit.gif']

This says select element(s) with img tag with attribute src having value of 'images/toolbar/b_edit.gif'


CSS query:

CSS query


VBA:

You can apply the selector with the .querySelector method of document.

IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click

How to find all links / pages on a website

If you have the developer console (JavaScript) in your browser, you can type this code in:

urls = document.querySelectorAll('a'); for (url in urls) console.log(urls[url].href);

Shortened:

n=$$('a');for(u in n)console.log(n[u].href)

What's the difference between 'r+' and 'a+' when open file in python?

Python opens files almost in the same way as in C:

  • r+ Open for reading and writing. The stream is positioned at the beginning of the file.

  • a+ Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is appended to the end of the file (but in some Unix systems regardless of the current seek position).

Setting up redirect in web.config file

You probably want to look at something like URL Rewrite to rewrite URLs to more user friendly ones rather than using a simple httpRedirect. You could then make a rule like this:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Rewrite to Category">
        <match url="^Category/([_0-9a-z-]+)/([_0-9a-z-]+)" />
        <action type="Rewrite" url="category.aspx?cid={R:2}" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

Can't import Numpy in Python

The following command worked for me:

python.exe -m pip install numpy

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.