Programs & Examples On #Pojo

POJO is an acronym for Plain Old Java Object. The name is used to emphasize that a given object is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean.

Spring Data JPA map the native query result to Non-Entity POJO

You can write your native or non-native query the way you want, and you can wrap JPQL query results with instances of custom result classes. Create a DTO with the same names of columns returned in query and create an all argument constructor with same sequence and names as returned by the query. Then use following way to query the database.

@Query("SELECT NEW example.CountryAndCapital(c.name, c.capital.name) FROM Country AS c")

Create DTO:

package example;

public class CountryAndCapital {
    public String countryName;
    public String capitalName;

    public CountryAndCapital(String countryName, String capitalName) {
        this.countryName = countryName;
        this.capitalName = capitalName;
    }
}

What is the difference between a JavaBean and a POJO?

POJOS with certain conventions (getter/setter,public no-arg constructor ,private variables) and are in action(ex. being used for reading data by form) are JAVABEANS.

How to create a POJO?

According to Martin Fowler

The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk, we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it’s caught on very nicely.

Generally, a POJO is not bound to any restriction and any Java object can be called a POJO but there are some directions. A well-defined POJO should follow below directions.

  1. Each variable in a POJO should be declared as private.
  2. Default constructor should be overridden with public accessibility.
  3. Each variable should have its Setter-Getter method with public accessibility.
  4. Generally POJO should override equals(), hashCode() and toString() methods of Object (but it's not mandatory).
  5. Overriding compare() method of Comparable interface used for sorting (Preferable but not mandatory).

And according to Java Language Specification, a POJO should not have to

  1. Extend pre-specified classes
  2. Implement pre-specified interfaces
  3. Contain pre-specified annotations

However, developers and frameworks describe a POJO still requires the use prespecified annotations to implement features like persistence, declarative transaction management etc. So the idea is that if the object was a POJO before any annotations were added would return to POJO status if the annotations are removed then it can still be considered a POJO.

A JavaBean is a special kind of POJO that is Serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.

Read more on Plain Old Java Object (POJO) Explained.

What is the difference between field, variable, attribute, and property in Java POJOs?

  • variable - named storage address. Every variable has a type which defines a memory size, attributes and behaviours. There are for types of Java variables: class variable, instance variable, local variable, method parameter
//pattern
<Java_type> <name> ;

//for example
int myInt;
String myString;
CustomClass myCustomClass;
  • field - member variable or data member. It is a variable inside a class(class variable or instance variable)

  • attribute - in some articles you can find that attribute it is an object representation of class variable. Object operates by attributes which define a set of characteristics.

CustomClass myCustomClass = new CustomClass();
myCustomClass.myAttribute = "poor fantasy"; //`myAttribute` is an attribute of `myCustomClass` object with a "poor fantasy" value
  • property - field + bounded getter/setter. It has a field syntax but uses methods under the hood. Java does not support it in pure form. Take a look at Objective-C, Swift, Kotlin

For example Kotlin sample:

//field - Backing Field
class Person {
    var name: String = "default name"
        get() = field
        set(value) { field = value }
}

//using
val person = Person()
person.name = "Alex"    // setter is used
println(person.name)    // getter is used

[Swift variable, property...]

Date format Mapping to JSON Jackson

Since Jackson v2.0, you can use @JsonFormat annotation directly on Object members;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm a z")
private Date date;

Convert a Map<String, String> to a POJO

The answers provided so far using Jackson are so good, but still you could have a util function to help you convert different POJOs as follows:

    public static <T> T convert(Map<String, Object> aMap, Class<T> t) {
        try {
            return objectMapper
                    .convertValue(aMap, objectMapper.getTypeFactory().constructType(t));
        } catch (Exception e) {
            log.error("converting failed! aMap: {}, class: {}", getJsonString(aMap), t.getClass().getSimpleName(), e);
        }
        return null;
    }

ArrayList - How to modify a member of an object?

You can do this:

myList.get(3).setEmail("new email");

What is java pojo class, java bean, normal class?

  1. Normal Class: A Java class

  2. Java Beans:

    • All properties private (use getters/setters)
    • A public no-argument constructor
    • Implements Serializable.
  3. Pojo: Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to

    • Extend prespecified classes
    • Implement prespecified interface
    • Contain prespecified annotations

How to convert POJO to JSON and vice versa?

If you are aware of Jackson 2, there is a great tutorial at mkyong.com on how to convert Java Objects to JSON and vice versa. The following code snippets have been taken from that tutorial.

Convert Java object to JSON, writeValue(...):

ObjectMapper mapper = new ObjectMapper();
Staff obj = new Staff();

//Object to JSON in file
mapper.writeValue(new File("c:\\file.json"), obj);

//Object to JSON in String
String jsonInString = mapper.writeValueAsString(obj);

Convert JSON to Java object, readValue(...):

ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";

//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);

//JSON from URL to Object
Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);

//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);

Jackson 2 Dependency:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

For the full tutorial, please go to the link given above.

Difference between DTO, VO, POJO, JavaBeans?

JavaBeans

A JavaBean is a class that follows the JavaBeans conventions as defined by Sun. Wikipedia has a pretty good summary of what JavaBeans are:

JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods.

In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behavior. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans.

The required conventions are:

  • The class must have a public default constructor. This allows easy instantiation within editing and activation frameworks.
  • The class properties must be accessible using get, set, and other methods (so-called accessor methods and mutator methods), following a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties.
  • The class should be serializable. This allows applications and frameworks to reliably save, store, and restore the bean's state in a fashion that is independent of the VM and platform.

Because these requirements are largely expressed as conventions rather than by implementing interfaces, some developers view JavaBeans as Plain Old Java Objects that follow specific naming conventions.

POJO

A Plain Old Java Object or POJO is a term initially introduced to designate a simple lightweight Java object, not implementing any javax.ejb interface, as opposed to heavyweight EJB 2.x (especially Entity Beans, Stateless Session Beans are not that bad IMO). Today, the term is used for any simple object with no extra stuff. Again, Wikipedia does a good job at defining POJO:

POJO is an acronym for Plain Old Java Object. The name is used to emphasize that the object in question is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean (especially before EJB 3). The term was coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie in September 2000:

"We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely."

The term continues the pattern of older terms for technologies that do not use fancy new features, such as POTS (Plain Old Telephone Service) in telephony, and PODS (Plain Old Data Structures) that are defined in C++ but use only C language features, and POD (Plain Old Documentation) in Perl.

The term has most likely gained widespread acceptance because of the need for a common and easily understood term that contrasts with complicated object frameworks. A JavaBean is a POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods. An Enterprise JavaBean is not a single class but an entire component model (again, EJB 3 reduces the complexity of Enterprise JavaBeans).

As designs using POJOs have become more commonly-used, systems have arisen that give POJOs some of the functionality used in frameworks and more choice about which areas of functionality are actually needed. Hibernate and Spring are examples.

Value Object

A Value Object or VO is an object such as java.lang.Integer that hold values (hence value objects). For a more formal definition, I often refer to Martin Fowler's description of Value Object:

In Patterns of Enterprise Application Architecture I described Value Object as a small object such as a Money or date range object. Their key property is that they follow value semantics rather than reference semantics.

You can usually tell them because their notion of equality isn't based on identity, instead two value objects are equal if all their fields are equal. Although all fields are equal, you don't need to compare all fields if a subset is unique - for example currency codes for currency objects are enough to test equality.

A general heuristic is that value objects should be entirely immutable. If you want to change a value object you should replace the object with a new one and not be allowed to update the values of the value object itself - updatable value objects lead to aliasing problems.

Early J2EE literature used the term value object to describe a different notion, what I call a Data Transfer Object. They have since changed their usage and use the term Transfer Object instead.

You can find some more good material on value objects on the wiki and by Dirk Riehle.

Data Transfer Object

Data Transfer Object or DTO is a (anti) pattern introduced with EJB. Instead of performing many remote calls on EJBs, the idea was to encapsulate data in a value object that could be transfered over the network: a Data Transfer Object. Wikipedia has a decent definition of Data Transfer Object:

Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.

The difference between data transfer objects and business objects or data access objects is that a DTO does not have any behaviour except for storage and retrieval of its own data (accessors and mutators).

In a traditional EJB architecture, DTOs serve dual purposes: first, they work around the problem that entity beans are not serializable; second, they implicitly define an assembly phase where all data to be used by the view is fetched and marshalled into the DTOs before returning control to the presentation tier.


So, for many people, DTOs and VOs are the same thing (but Fowler uses VOs to mean something else as we saw). Most of time, they follow the JavaBeans conventions and are thus JavaBeans too. And all are POJOs.

Programmatically go back to previous ViewController in Swift

For questions regarding how to embed your viewController to a navigationController in the storyboard:

  1. Open your storyboard where your different viewController are located
  2. Tap the viewController you would like your navigation controller to start from
  3. On the top of Xcode, tap "Editor"
  4. -> Tap embed in
  5. -> Tap "Navigation Controller

Python logging: use milliseconds in time format

A simple expansion that doesn't require the datetime module and isn't handicapped like some other solutions is to use simple string replacement like so:

import logging
import time

class MyFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            if "%F" in datefmt:
                msec = "%03d" % record.msecs
                datefmt = datefmt.replace("%F", msec)
            s = time.strftime(datefmt, ct)
        else:
            t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
            s = "%s,%03d" % (t, record.msecs)
        return s

This way a date format can be written however you want, even allowing for region differences, by using %F for milliseconds. For example:

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

sh = logging.StreamHandler()
log.addHandler(sh)

fm = MyFormatter(fmt='%(asctime)s-%(levelname)s-%(message)s',datefmt='%H:%M:%S.%F')
sh.setFormatter(fm)

log.info("Foo, Bar, Baz")
# 03:26:33.757-INFO-Foo, Bar, Baz

How to Export-CSV of Active Directory Objects?

HI you can try this...

Try..

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq ""}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\ceridian\NoClockNumber_2013_02_12.csv -NoTypeInformation

Or

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq $null}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\cer

Hope it works for you.

How to properly seed random number generator

just to toss it out for posterity: it can sometimes be preferable to generate a random string using an initial character set string. This is useful if the string is supposed to be entered manually by a human; excluding 0, O, 1, and l can help reduce user error.

var alpha = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"

// generates a random string of fixed size
func srand(size int) string {
    buf := make([]byte, size)
    for i := 0; i < size; i++ {
        buf[i] = alpha[rand.Intn(len(alpha))]
    }
    return string(buf)
}

and I typically set the seed inside of an init() block. They're documented here: http://golang.org/doc/effective_go.html#init

Add and remove multiple classes in jQuery

Add multiple classes:

$("p").addClass("class1 class2 class3");

or in cascade:

$("p").addClass("class1").addClass("class2").addClass("class3");

Very similar also to remove more classes:

$("p").removeClass("class1 class2 class3");

or in cascade:

$("p").removeClass("class1").removeClass("class2").removeClass("class3");

Crop image in android

Can you use default android Crop functionality?

Here is my code

private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties here
        cropIntent.putExtra("crop", true);
        // indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        // indicate output X and Y
        cropIntent.putExtra("outputX", 128);
        cropIntent.putExtra("outputY", 128);
        // retrieve data on return
        cropIntent.putExtra("return-data", true);
        // start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, PIC_CROP);
    }
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        // display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

declare:

final int PIC_CROP = 1;

at top.

In onActivity result method, writ following code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PIC_CROP) {
        if (data != null) {
            // get the returned data
            Bundle extras = data.getExtras();
            // get the cropped bitmap
            Bitmap selectedBitmap = extras.getParcelable("data");

            imgView.setImageBitmap(selectedBitmap);
        }
    }
}

It is pretty easy for me to implement and also shows darken areas.

How to use Git?

I think gitready is a great starting point. I'm using git for a project now and that site pretty much got the ball rolling for me.

Measuring execution time of a function in C++

  • It is a very easy to use method in C++11.
  • We can use std::chrono::high_resolution_clock from header
  • We can write a method to print the method execution time in a much readable form.

For example, to find the all the prime numbers between 1 and 100 million, it takes approximately 1 minute and 40 seconds. So the execution time get printed as:

Execution Time: 1 Minutes, 40 Seconds, 715 MicroSeconds, 715000 NanoSeconds

The code is here:

#include <iostream>
#include <chrono>

using namespace std;
using namespace std::chrono;

typedef high_resolution_clock Clock;
typedef Clock::time_point ClockTime;

void findPrime(long n, string file);
void printExecutionTime(ClockTime start_time, ClockTime end_time);

int main()
{
    long n = long(1E+8);  // N = 100 million

    ClockTime start_time = Clock::now();

    // Write all the prime numbers from 1 to N to the file "prime.txt"
    findPrime(n, "C:\\prime.txt"); 

    ClockTime end_time = Clock::now();

    printExecutionTime(start_time, end_time);
}

void printExecutionTime(ClockTime start_time, ClockTime end_time)
{
    auto execution_time_ns = duration_cast<nanoseconds>(end_time - start_time).count();
    auto execution_time_ms = duration_cast<microseconds>(end_time - start_time).count();
    auto execution_time_sec = duration_cast<seconds>(end_time - start_time).count();
    auto execution_time_min = duration_cast<minutes>(end_time - start_time).count();
    auto execution_time_hour = duration_cast<hours>(end_time - start_time).count();

    cout << "\nExecution Time: ";
    if(execution_time_hour > 0)
    cout << "" << execution_time_hour << " Hours, ";
    if(execution_time_min > 0)
    cout << "" << execution_time_min % 60 << " Minutes, ";
    if(execution_time_sec > 0)
    cout << "" << execution_time_sec % 60 << " Seconds, ";
    if(execution_time_ms > 0)
    cout << "" << execution_time_ms % long(1E+3) << " MicroSeconds, ";
    if(execution_time_ns > 0)
    cout << "" << execution_time_ns % long(1E+6) << " NanoSeconds, ";
}

position: fixed doesn't work on iPad and iPhone

This seems to work for Ionic5 on iphone 6 Plus on iOS 12.4.2

.large_player {
    float: left;
      bottom: 0;
      width: 100%;
      position: fixed;
      background-color: white;
      border-top: black 1px solid;    
      height: 14rem;
      z-index: 100;
      transform: translate3d(0,0,0);
  }

The transform tag makes it work, but it also seems a little clunky in how the scroll works, it is seems to redraw the 'on top' element after it's all moved and sort of resets and makes it jump a little.

Or, you could also use this tag option as well, position: -webkit-sticky;, but then you won't get, or may run in to trouble with WPA/browser or Android builds while having to do version checking and have multiple CSS tags.

.large_player {
    float: left;
      bottom: 0;
      width: 100%;
      position: -webkit-sticky;
      background-color: white;
      border-top: black 1px solid;    
      height: 14rem;
      z-index: 100; 
  }

I don't know at what point it was fixed, but later iOS phones work without the transform tag. I don't know if it's the iOS version, or the phone.

As most iOS devices are usually on the most recent iOS version, it's pretty safe with go with a weird work around - such as using the transform tag, rather than building in a quirky detection routine for the sake of less than 1% of users.

Update:

After thinking about this answer further, this is just another way of doing this by platform for ionic5+:

.TS

import {Platform } from '@ionic/angular';

constructor(
public platform: Platform 
) 
{  
    // This next bit is so that the CSS is shown correctly for each platform    

    platform.ready().then(() => {
    if (this.platform.is('android')) {
        console.log("running on Android device!");
        this.css_iOS = false;
    }
    if (this.platform.is('ios')) {
        console.log("running on iOS device!");
        this.css_iOS = true;
    }     
    if (this.platform.is('ipad')) {
        console.log("running on iOS device!");
        this.css_iOS = true;
    }
    });
}
css_iOS: boolean = false;

.HTML

<style *ngIf="css_iOS">
    .small_player {
      position: -webkit-sticky !important;
    }
    .large_player {
      position: -webkit-sticky !important;
    }
    </style>
    
    
    <style>
    .small_player {
    float: left;
      bottom: 0;
      width: 100%;
      position: fixed;
      background-color: white;
      border-top: black 1px solid;    
      height: 4rem;
      z-index: 100;
      /*transform: translate3d(0,0,0);*/
    }
    
    .large_player {
    float: left;
      bottom: 0;
      width: 100%;
      position: fixed;
      background-color: white;
      border-top: black 1px solid;    
      height: 14rem;
      z-index: 100;
      /*transform: translate3d(0,0,0);*/
    }
    </style>

How to get JSON from URL in JavaScript?

Define a function like:

fetchRestaurants(callback) {
    fetch(`http://www.restaurants.com`)
       .then(response => response.json())
       .then(json => callback(null, json.restaurants))
       .catch(error => callback(error, null))
}

Then use it like this:

fetchRestaurants((error, restaurants) => {
    if (error) 
        console.log(error)
    else 
        console.log(restaurants[0])

});

RE error: illegal byte sequence on Mac OS X

Does anyone know how to get sed to print the position of the illegal byte sequence? Or does anyone know what the illegal byte sequence is?

$ uname -a
Darwin Adams-iMac 18.7.0 Darwin Kernel Version 18.7.0: Tue Aug 20 16:57:14 PDT 2019; root:xnu-4903.271.2~2/RELEASE_X86_64 x86_64

I got part of the way to answering the above just by using tr.

I have a .csv file that is a credit card statement and I am trying to import it into Gnucash. I am based in Switzerland so I have to deal with words like Zürich. Suspecting Gnucash does not like " " in numeric fields, I decide to simply replace all

; ;

with

;;

Here goes:

$ head -3 Auswertungen.csv | tail -1 | sed -e 's/; ;/;;/g'
sed: RE error: illegal byte sequence

I used od to shed some light: Note the 374 halfway down this od -c output

$ head -3 Auswertungen.csv | tail -1 | od -c
0000000    1   6   8   7       9   6   1   9       7   1   2   2   ;   5
0000020    4   6   8       8   7   X   X       X   X   X   X       2   6
0000040    6   0   ;   M   Y       N   A   M   E       I   S   X   ;   1
0000060    4   .   0   2   .   2   0   1   9   ;   9   5   5   2       -
0000100        M   i   t   a   r   b   e   i   t   e   r   r   e   s   t
0000120                Z 374   r   i   c   h                            
0000140    C   H   E   ;   R   e   s   t   a   u   r   a   n   t   s   ,
0000160        B   a   r   s   ;   6   .   2   0   ;   C   H   F   ;    
0000200    ;   C   H   F   ;   6   .   2   0   ;       ;   1   5   .   0
0000220    2   .   2   0   1   9  \n                                    
0000227

Then I thought I might try to persuade tr to substitute 374 for whatever the correct byte code is. So first I tried something simple, which didn't work, but had the side effect of showing me where the troublesome byte was:

$ head -3 Auswertungen.csv | tail -1 | tr . .  ; echo
tr: Illegal byte sequence
1687 9619 7122;5468 87XX XXXX 2660;MY NAME ISX;14.02.2019;9552 - Mitarbeiterrest   Z

You can see tr bails at the 374 character.

Using perl seems to avoid this problem

$ head -3 Auswertungen.csv | tail -1 | perl -pne 's/; ;/;;/g'
1687 9619 7122;5468 87XX XXXX 2660;ADAM NEALIS;14.02.2019;9552 - Mitarbeiterrest   Z?rich       CHE;Restaurants, Bars;6.20;CHF;;CHF;6.20;;15.02.2019

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

This is a great sample:

String base64String = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAA...";
String base64Image = base64String.split(",")[1];
byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte);

Sample found at: https://freakycoder.com/android-notes-44-how-to-convert-base64-string-to-bitmap-53f98d5e57af

This is the only code that worked for me in the past.

.NET Events - What are object sender & EventArgs e?

sender refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.

EventArgs is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.

When you implement your own events, use an EventHandler or EventHandler<T> as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).

Oracle ORA-12154: TNS: Could not resolve service name Error?

We resolved our issues by re-installing the Oracle Database Client. Somehow the installation wasn't successful on 1 of the workstations (even though there was no logging), however when comparing size/files/folders of the Oracle directory to a working client workstation, there was a significant amount of files that were missing. Once we performed a clean install, everything worked perfectly.

What is the instanceof operator in JavaScript?

There's an important facet to instanceof that does not seem to be covered in any of the comments thus far: inheritance. A variable being evaluated by use of instanceof could return true for multiple "types" due to prototypal inheritance.

For example, let's define a type and a subtype:

function Foo(){ //a Foo constructor
    //assign some props
    return this;
}

function SubFoo(){ //a SubFoo constructor
    Foo.call( this ); //inherit static props
    //assign some new props
    return this;
}

SubFoo.prototype = Object.create(Foo.prototype); // Inherit prototype
SubFoo.prototype.constructor = SubFoo;

Now that we have a couple of "classes" lets make some instances, and find out what they're instances of:

var 
    foo = new Foo()
,   subfoo = new SubFoo()
;

alert( 
    "Q: Is foo an instance of Foo? "
+   "A: " + ( foo instanceof Foo ) 
); // -> true

alert( 
    "Q: Is foo an instance of SubFoo? " 
+   "A: " + ( foo instanceof SubFoo ) 
); // -> false

alert( 
    "Q: Is subfoo an instance of Foo? "
+   "A: " + ( subfoo instanceof Foo ) 
); // -> true

alert( 
    "Q: Is subfoo an instance of SubFoo? "
+   "A: " + ( subfoo instanceof SubFoo ) 
); // -> true

alert( 
    "Q: Is subfoo an instance of Object? "
+   "A: " + ( subfoo instanceof Object ) 
); // -> true

See that last line? All "new" calls to a function return an object that inherits from Object. This holds true even when using object creation shorthand:

alert( 
    "Q: Is {} an instance of Object? "
+   "A: " + ( {} instanceof Object ) 
); // -> true

And what about the "class" definitions themselves? What are they instances of?

alert( 
    "Q: Is Foo an instance of Object? "
+   "A:" + ( Foo instanceof Object) 
); // -> true

alert( 
    "Q: Is Foo an instance of Function? "
+   "A:" + ( Foo instanceof Function) 
); // -> true

I feel that understanding that any object can be an instance of MULTIPLE types is important, since you my (incorrectly) assume that you could differentiate between, say and object and a function by use of instanceof. As this last example clearly shows a function is an object.

This is also important if you are using any inheritance patterns and want to confirm the progeny of an object by methods other than duck-typing.

Hope that helps anyone exploring instanceof.

Git: How to remove file from index without deleting files from any repository

I do not think a Git commit can record an intention like “stop tracking this file, but do not delete it”.

Enacting such an intention will require intervention outside Git in any repositories that merge (or rebase onto) a commit that deletes the file.


Save a Copy, Apply Deletion, Restore

Probably the easiest thing to do is to tell your downstream users to save a copy of the file, pull your deletion, then restore the file. If they are pulling via rebase and are ‘carrying’ modifications to the file, they will get conflicts. To resolve such conflicts, use git rm foo.conf && git rebase --continue (if the conflicting commit has changes besides those to the removed file) or git rebase --skip (if the conflicting commit has only changed to the removed file).

Restore File as Untracked After Pulling a Commit That Deletes It

If they have already pulled your deletion commit, they can still recover the previous version of the file with git show:

git show @{1}:foo.conf >foo.conf

Or with git checkout (per comment by William Pursell; but remember to re-remove it from the index!):

git checkout @{1} -- foo.conf && git rm --cached foo.conf

If they have taken other actions since pulling your deletion (or they are pulling with rebase into a detached HEAD), they may need something other than @{1}. They could use git log -g to find the commit just before they pulled your deletion.


In a comment, you mention that the file you want to “untrack, but keep” is some kind of configuration file that is required for running the software (directly out of a repository).

Keep File as a ‘Default’ and Manually/Automatically Activate It

If it is not completely unacceptable to continue to maintain the configuration file's content in the repository, you might be able to rename the tracked file from (e.g.) foo.conf to foo.conf.default and then instruct your users to cp foo.conf.default foo.conf after applying the rename commit. Or, if the users already use some existing part of the repository (e.g. a script or some other program configured by content in the repository (e.g. Makefile or similar)) to launch/deploy your software, you could incorporate a defaulting mechanism into the launch/deploy process:

test -f foo.conf || test -f foo.conf.default &&
    cp foo.conf.default foo.conf

With such a defaulting mechanism in place, users should be able to pull a commit that renames foo.conf to foo.conf.default without having to do any extra work. Also, you avoid having to manually copy a configuration file if you make additional installations/repositories in the future.

Rewriting History Requires Manual Intervention Anyway…

If it is unacceptable to maintain the content in the repository then you will likely want to completely eradicate it from history with something like git filter-branch --index-filter …. This amounts to rewriting history, which will require manual intervention for each branch/repository (see “Recovering From Upstream Rebase” section in the git rebase manpage). The special treatment required for your configuration file would be just another step that one must perform while recovering from the rewrite:

  1. Save a copy of the configuration file.
  2. Recover from the rewrite.
  3. Restore the configuration file.

Ignore It to Prevent Recurrence

Whatever method you use, you will probably want to include the configuration filename in a .gitignore file in the repository so that no one can inadvertently git add foo.conf again (it is possible, but requires -f/--force). If you have more than one configuration file, you might consider ‘moving’ them all into a single directory and ignoring the whole thing (by ‘moving’ I mean changing where the program expects to find its configuration files, and getting the users (or the launch/deploy mechanism) to copy/move the files to to their new location; you obviously would not want to git mv a file into a directory that you will be ignoring).

jQuery UI Slider (setting programmatically)

If you need change slider values from several input, use it:

html:

<input type="text" id="amount">
<input type="text" id="amount2">
<div id="slider-range"></div>

js:

    $( "#slider-range" ).slider({
    range: true,
    min: 0,
    max: 217,
    values: [ 0, 217 ],
    slide: function( event, ui ) {
        $( "#amount" ).val( ui.values[ 0 ] );
        $( "#amount2" ).val( ui.values[ 1 ] );
    }
    });

$("#amount").change(function() {
    $("#slider-range").slider('values',0,$(this).val());
});
$("#amount2").change(function() {
    $("#slider-range").slider('values',1,$(this).val());
});

https://jsfiddle.net/brhuman/uvx6pdc1/1/

How to check if text fields are empty on form submit using jQuery?

var save_val = $("form").serializeArray();
$(save_val).each(function( index, element ) {
    alert(element.name);
    alert(element.val);
});

What's the fastest way of checking if a point is inside a polygon in python

If speed is what you need and extra dependencies are not a problem, you maybe find numba quite useful (now it is pretty easy to install, on any platform). The classic ray_tracing approach you proposed can be easily ported to numba by using numba @jit decorator and casting the polygon to a numpy array. The code should look like:

@jit(nopython=True)
def ray_tracing(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside

The first execution will take a little longer than any subsequent call:

%%time
polygon=np.array(polygon)
inside1 = [numba_ray_tracing_method(point[0], point[1], polygon) for 
point in points]

CPU times: user 129 ms, sys: 4.08 ms, total: 133 ms
Wall time: 132 ms

Which, after compilation will decrease to:

CPU times: user 18.7 ms, sys: 320 µs, total: 19.1 ms
Wall time: 18.4 ms

If you need speed at the first call of the function you can then pre-compile the code in a module using pycc. Store the function in a src.py like:

from numba import jit
from numba.pycc import CC
cc = CC('nbspatial')


@cc.export('ray_tracing',  'b1(f8, f8, f8[:,:])')
@jit(nopython=True)
def ray_tracing(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


if __name__ == "__main__":
    cc.compile()

Build it with python src.py and run:

import nbspatial

import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in 
np.linspace(0,2*np.pi,lenpoly)[:-1]]

# random points set of points to test 
N = 10000
# making a list instead of a generator to help debug
points = zip(np.random.random(N),np.random.random(N))

polygon = np.array(polygon)

%%time
result = [nbspatial.ray_tracing(point[0], point[1], polygon) for point in points]

CPU times: user 20.7 ms, sys: 64 µs, total: 20.8 ms
Wall time: 19.9 ms

In the numba code I used: 'b1(f8, f8, f8[:,:])'

In order to compile with nopython=True, each var needs to be declared before the for loop.

In the prebuild src code the line:

@cc.export('ray_tracing' , 'b1(f8, f8, f8[:,:])')

Is used to declare the function name and its I/O var types, a boolean output b1 and two floats f8 and a two-dimensional array of floats f8[:,:] as input.

Edit Jan/4/2021

For my use case, I need to check if multiple points are inside a single polygon - In such a context, it is useful to take advantage of numba parallel capabilities to loop over a series of points. The example above can be changed to:

from numba import jit, njit
import numba
import numpy as np 

@jit(nopython=True)
def pointinpolygon(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in numba.prange(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
    D = np.empty(len(points), dtype=numba.boolean) 
    for i in numba.prange(0, len(D)):
        D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
    return D    

Note: pre-compiling the above code will not enable the parallel capabilities of numba (parallel CPU target is not supported by pycc/AOT compilation) see: https://github.com/numba/numba/issues/3336

Test:


import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]
polygon = np.array(polygon)
N = 10000
points = np.random.uniform(-1.5, 1.5, size=(N, 2))

For N=10000 on a 72 core machine, returns:

%%timeit
parallelpointinpolygon(points, polygon)
# 480 µs ± 8.19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Edit 17 Feb '21:

  • fixing loop to start from 0 instead of 1 (thanks @mehdi):

for i in numba.prange(0, len(D))

Edit 20 Feb '21:

Follow-up on the comparison made by @mehdi, I am adding a GPU-based method below. It uses the point_in_polygon method, from the cuspatial library:

    import numpy as np
    import cudf
    import cuspatial

    N = 100000002
    lenpoly = 1000
    polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in 
    np.linspace(0,2*np.pi,lenpoly)]
    polygon = np.array(polygon)
    points = np.random.uniform(-1.5, 1.5, size=(N, 2))


    x_pnt = points[:,0]
    y_pnt = points[:,1]
    x_poly =polygon[:,0]
    y_poly = polygon[:,1]
    result = cuspatial.point_in_polygon(
        x_pnt,
        y_pnt,
        cudf.Series([0], index=['geom']),
        cudf.Series([0], name='r_pos', dtype='int32'), 
        x_poly, 
        y_poly,
    )

Following @Mehdi comparison. For N=100000002 and lenpoly=1000 - I got the following results:

 time_parallelpointinpolygon:         161.54760098457336 
 time_mpltPath:                       307.1664695739746 
 time_ray_tracing_numpy_numba:        353.07356882095337 
 time_is_inside_sm_parallel:          37.45389246940613 
 time_is_inside_postgis_parallel:     127.13793849945068 
 time_is_inside_rapids:               4.246025562286377

point in poligon methods comparison, #poins: 10e07

hardware specs:

  • CPU Intel xeon E1240
  • GPU Nvidia GTX 1070

Notes:

  • The cuspatial.point_in_poligon method, is quite robust and powerful, it offers the ability to work with multiple and complex polygons (I guess at the expense of performance)

  • The numba methods can also be 'ported' on the GPU - it will be interesting to see a comparison which includes a porting to cuda of fastest method mentioned by @Mehdi (is_inside_sm).

How to access child's state in React?

Just before I go into detail about how you can access the state of a child component, please make sure to read Markus-ipse's answer regarding a better solution to handle this particular scenario.

If you do indeed wish to access the state of a component's children, you can assign a property called ref to each child. There are now two ways to implement references: Using React.createRef() and callback refs.

Using React.createRef()

This is currently the recommended way to use references as of React 16.3 (See the docs for more info). If you're using an earlier version then see below regarding callback references.

You'll need to create a new reference in the constructor of your parent component and then assign it to a child via the ref attribute.

class FormEditor extends React.Component {
  constructor(props) {
    super(props);
    this.FieldEditor1 = React.createRef();
  }
  render() {
    return <FieldEditor ref={this.FieldEditor1} />;
  }
}

In order to access this kind of ref, you'll need to use:

const currentFieldEditor1 = this.FieldEditor1.current;

This will return an instance of the mounted component so you can then use currentFieldEditor1.state to access the state.

Just a quick note to say that if you use these references on a DOM node instead of a component (e.g. <div ref={this.divRef} />) then this.divRef.current will return the underlying DOM element instead of a component instance.

Callback Refs

This property takes a callback function that is passed a reference to the attached component. This callback is executed immediately after the component is mounted or unmounted.

For example:

<FieldEditor
    ref={(fieldEditor1) => {this.fieldEditor1 = fieldEditor1;}
    {...props}
/>

In these examples the reference is stored on the parent component. To call this component in your code, you can use:

this.fieldEditor1

and then use this.fieldEditor1.state to get the state.

One thing to note, make sure your child component has rendered before you try to access it ^_^

As above, if you use these references on a DOM node instead of a component (e.g. <div ref={(divRef) => {this.myDiv = divRef;}} />) then this.divRef will return the underlying DOM element instead of a component instance.

Further Information

If you want to read more about React's ref property, check out this page from Facebook.

Make sure you read the "Don't Overuse Refs" section that says that you shouldn't use the child's state to "make things happen".

Hope this helps ^_^

Edit: Added React.createRef() method for creating refs. Removed ES5 code.

How to use log levels in java

The java.util.logging.Level documentation does a good job of defining when to use a log level and the target audience of that log level.

Most of the confusion with java.util.logging is in the tracing methods. It should be in the class level documentation but instead the Level.FINE field provides a good overview:

FINE is a message level providing tracing information. All of FINE, FINER, and FINEST are intended for relatively detailed tracing. The exact meaning of the three levels will vary between subsystems, but in general, FINEST should be used for the most voluminous detailed output, FINER for somewhat less detailed output, and FINE for the lowest volume (and most important) messages. In general the FINE level should be used for information that will be broadly interesting to developers who do not have a specialized interest in the specific subsystem. FINE messages might include things like minor (recoverable) failures. Issues indicating potential performance problems are also worth logging as FINE.

One important thing to understand which is not mentioned in the level documentation is that call-site tracing information is logged at FINER.

  • Logger#entering A LogRecord with message "ENTRY", log level FINER, ...
  • Logger#throwing The logging is done using the FINER level...The LogRecord's message is set to "THROW"
  • Logger#exiting A LogRecord with message "RETURN", log level FINER...

If you log a message as FINE you will be able to configure logging system to see the log output with or without tracing log records surrounding the log message. So use FINE only when tracing log records are not required as context to understand the log message.

FINER indicates a fairly detailed tracing message. By default logging calls for entering, returning, or throwing an exception are traced at this level.

In general, most use of FINER should be left to call of entering, exiting, and throwing. That will for the most part reserve FINER for call-site tracing when verbose logging is turned on. When swallowing an expected exception it makes sense to use FINER in some cases as the alternative to calling trace throwing method since the exception is not actually thrown. This makes it look like a trace when it isn't a throw or an actual error that would be logged at a higher level.

FINEST indicates a highly detailed tracing message.

Use FINEST when the tracing log message you are about to write requires context information about program control flow. You should also use FINEST for tracing messages that produce large amounts of output data.

CONFIG messages are intended to provide a variety of static configuration information, to assist in debugging problems that may be associated with particular configurations. For example, CONFIG message might include the CPU type, the graphics depth, the GUI look-and-feel, etc.

The CONFIG works well for assisting system admins with the items listed above.

Typically INFO messages will be written to the console or its equivalent. So the INFO level should only be used for reasonably significant messages that will make sense to end users and system administrators.

Examples of this are tracing program startup and shutdown.

In general WARNING messages should describe events that will be of interest to end users or system managers, or which indicate potential problems.

An example use case could be exceptions thrown from AutoCloseable.close implementations.

In general SEVERE messages should describe events that are of considerable importance and which will prevent normal program execution. They should be reasonably intelligible to end users and to system administrators.

For example, if you have transaction in your program where if any one of the steps fail then all of the steps voided then SEVERE would be appropriate to use as the log level.

Environment variables in Jenkins

What ultimately worked for me was the following steps:

  1. Configure the Environment Injector Plugin: https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin
  2. Goto to the /job//configure screen
  3. In Build Environment section check "Inject environment variables to the build process"
  4. In "Properties Content" specified: TZ=America/New_York

What is the maximum length of a Push Notification alert text?

It should be 236 bytes. There is no restriction on the size of the alert text as far as I know, but only the total payload size. So considering if the payload is minimal and only contains the alert information, it should look like:

{"aps":{"alert":""}}

That takes up 20 characters (20 bytes), leaving 236 bytes to put inside the alert string. With ASCII that will be 236 characters, and could be lesser with UTF8 and UTF16.

Running conda with proxy

I was able to get it working without putting in the username and password:

conda config --set proxy_servers.https https://address:port

How to make HTML element resizable using pure Javascript?

_x000D_
_x000D_
// import
function get_difference(pre, mou) {
  return {
    x: mou.x - pre.x,
    y: mou.y - pre.y
  };
}

/*
if your panel is in a nested environment, which the parent container's width and height does not equa to document width 
and height, for example, in an element `canvas`, then edit it to

function oMousePos(e) {
  var rc = canvas.getBoundingClientRect();
  return {
    x: e.clientX - rc.left,
    y: e.clientY - rc.top,
  };
}
*/

function oMousePos(e) {
  return {
    x: e.clientX,
    y: e.clientY,
  };
}

function render_element(styles, el) {
  for (const [kk, vv] of Object.entries(styles)) {
    el.style[kk] = vv;
  }
}

class MoveablePanel {

  /*
  prevent an element from moving out of window
  */
  constructor(container, draggable, left, top) {
    this.container = container;
    this.draggable = draggable;
    this.left = left;
    this.top = top;
    let rect = container.getBoundingClientRect();
    this.width = rect.width;
    this.height = rect.height;
    this.status = false;

    // initial position of the panel, should not be changed
    this.original = {
      left: left,
      top: top
    };

    // current left and top postion
    // {this.left, this.top}

    // assign the panel to initial position
    // initalize in registration
    this.default();

    if (!MoveablePanel._instance) {
      MoveablePanel._instance = [];
    }
    MoveablePanel._instance.push(this);
  }

  mousedown(e) {
    this.status = true;
    this.previous = oMousePos(e)
  }

  mousemove(e) {
    if (!this.status) {
      return;
    }
    let pos = oMousePos(e);
    let vleft = this.left + pos.x - this.previous.x;
    let vtop = this.top + pos.y - this.previous.y;
    let kleft, ktop;

    if (vleft < 0) {
      kleft = 0;
    } else if (vleft > window.innerWidth - this.width) {
      kleft = window.innerWidth - this.width;
    } else {
      kleft = vleft;
    }

    if (vtop < 0) {
      ktop = 0;
    } else if (vtop > window.innerHeight - this.height) {
      ktop = window.innerHeight - this.height;
    } else {
      ktop = vtop;
    }
    this.container.style.left = `${kleft}px`;
    this.container.style.top = `${ktop}px`;
  }

  /*
  sometimes user move the cursor too fast which mouseleave is previous than mouseup
  to prevent moving too fast and break the control, mouseleave is handled the same as mouseup
  */

  mouseupleave(e) {
    if (!this.status) {
      return null;
    }
    this.status = false;
    let pos = oMousePos(e);
    let vleft = this.left + pos.x - this.previous.x;
    let vtop = this.top + pos.y - this.previous.y;

    if (vleft < 0) {
      this.left = 0;
    } else if (vleft > window.innerWidth - this.width) {
      this.left = window.innerWidth - this.width;
    } else {
      this.left = vleft;
    }

    if (vtop < 0) {
      this.top = 0;
    } else if (vtop > window.innerHeight - this.height) {
      this.top = window.innerHeight - this.height;
    } else {
      this.top = vtop;
    }

    this.show();
    return true;
  }

  default () {
    this.container.style.left = `${this.original.left}px`;
    this.container.style.top = `${this.original.top}px`;
  }

  /*
  panel with a higher z index will interupt drawing
  therefore if panel is not displaying, set it with a lower z index that canvas

  change index doesn't work, if panel is hiding, then we move it out
  hide: record current position, move panel out
  show: assign to recorded position

  notice this position has nothing to do panel drag movement
  they cannot share the same variable
  */

  hide() {
    // move to the right bottom conner
    this.container.style.left = `${window.screen.width}px`;
    this.container.style.top = `${window.screen.height}px`;
  }

  show() {
    this.container.style.left = `${this.left}px`;
    this.container.style.top = `${this.top}px`;
  }
}
// end of import

class DotButton{
    constructor(
        width_px, 
        styles, // mainly pos, padding and margin, e.g. {top: 0, left: 0, margin: 0},
        color, 
        color_hover,
        border, // boolean
        border_dismiss, // boolean: dismiss border when hover
    ){
        this.width = width_px;
        this.styles = styles;
        this.color = color;
        this.color_hover = color_hover;
        this.border = border;
        this.border_dismiss = border_dismiss;
    }

    create(_styles=null){
        var el = document.createElement('div');
        Object.keys(this.styles).forEach(kk=>{
            el.style[kk] = `${this.styles[kk]}px`;
        });
        if(_styles){
            Object.keys(_styles).forEach(kk=>{
                el.style[kk] = `${this.styles[kk]}px`;
            });
        }
        el.style.width = `${this.width}px`
        el.style.height = `${this.width}px`
        el.style.position = 'absolute';
        el.style.left = `${this.left_px}px`;
        el.style.top = `${this.top_px}px`;
        el.style.background = this.color;
        if(this.border){
            el.style.border = '1px solid'; 
        }
        el.style.borderRadius = `${this.width}px`;

        el.addEventListener('mouseenter', ()=>{
            el.style.background = this.color_hover;
            if(this.border_dismiss){
                el.style.border = `1px solid ${this.color_hover}`; 
            }
        });
        el.addEventListener('mouseleave', ()=>{
            el.style.background = this.color;
            if(this.border_dismiss){
                el.style.border = '1px solid'; 
            }
        });
        return el;
    }
}

function cursor_hover(el, default_cursor, to_cursor){
    el.addEventListener('mouseenter', function(){
        this.style.cursor = to_cursor;
    }.bind(el));


    el.addEventListener('mouseleave', function(){
        this.style.cursor = default_cursor;
    }.bind(el));
}

class FlexPanel extends MoveablePanel{
    constructor(
        parent_el,
        top_px,
        left_px,
        width_px, 
        height_px, 
        background,
        handle_width_px, 
        coner_vmin_ratio, 
        button_width_px, 
        button_margin_px, 
    ){
        super(
            (()=>{
                var el = document.createElement('div');
                render_element(
                    {
                        position: 'fixed', 
                        top: `${top_px}px`,
                        left: `${left_px}px`,
                        width: `${width_px}px`,
                        height: `${height_px}px`,
                        background: background, 
                    }, 
                    el,
                );
                return el;
            })(), // iife returns a container (panel el)
            new DotButton(button_width_px, {top: 0, right: 0, margin: button_margin_px}, 'green', 'lightgreen', false, false).create(), // draggable
            left_px, // left
            top_px, // top
        );

        this.draggable.addEventListener('mousedown', e => {
            e.preventDefault();
            this.mousedown(e);
        });

        this.draggable.addEventListener('mousemove', e => {
            e.preventDefault();
            this.mousemove(e);
        });

        this.draggable.addEventListener('mouseup', e => {
            e.preventDefault();
            this.mouseupleave(e);
        });

        this.draggable.addEventListener('mouseleave', e => {
            e.preventDefault();
            this.mouseupleave(e);
        });

        this.parent_el = parent_el;
        this.background = background;

        // parent
        this.width = width_px;
        this.height = height_px;

        this.handle_width_px = handle_width_px;
        this.coner_vmin_ratio = coner_vmin_ratio;

        this.panel_el = document.createElement('div');

        // styles that won't change 
        this.panel_el.style.position = 'absolute';
        this.panel_el.style.top = `${this.handle_width_px}px`;
        this.panel_el.style.left = `${this.handle_width_px}px`; 
        this.panel_el.style.background = this.background;
    
        this.handles = [
            this.handle_top,
            this.handle_left,
            this.handle_bottom,
            this.handle_right, 

            this.handle_lefttop,
            this.handle_topleft,
            this.handle_topright,
            this.handle_righttop, 
            this.handle_rightbottom, 
            this.handle_bottomright,
            this.handle_bottomleft,
            this.handle_leftbottom, 
        ] = Array.from({length: 12}, i => document.createElement('div'));

        this.handles.forEach(el=>{
            el.style.position = 'absolute';
        });

        this.handle_topleft.style.top = '0';
        this.handle_topleft.style.left = `${this.handle_width_px}px`;

        this.handle_righttop.style.right = '0';
        this.handle_righttop.style.top = `${this.handle_width_px}px`;

        this.handle_bottomright.style.bottom = '0';
        this.handle_bottomright.style.right = `${this.handle_width_px}px`;

        this.handle_leftbottom.style.left = '0';
        this.handle_leftbottom.style.bottom = `${this.handle_width_px}px`;


        this.handle_lefttop.style.left = '0';
        this.handle_lefttop.style.top = '0';

        this.handle_topright.style.top = '0';
        this.handle_topright.style.right = '0';

        this.handle_rightbottom.style.right = '0';
        this.handle_rightbottom.style.bottom = '0';

        this.handle_bottomleft.style.bottom = '0';
        this.handle_bottomleft.style.left = '0';

        this.update_ratio();

        [
            'ns-resize', // |
            'ew-resize', // -
            'ns-resize', // |
            'ew-resize', // -

            'nwse-resize', // \
            'nwse-resize', // \
            'nesw-resize', // /
            'nesw-resize', // /
            'nwse-resize', // \
            'nwse-resize', // \
            'nesw-resize', // /
            'nesw-resize', // /
        ].map((dd, ii)=>{
            cursor_hover(this.handles[ii], 'default', dd);
        });

        this.vtop = this.top;
        this.vleft = this.left;
        this.vwidth = this.width;
        this.vheight = this.height;

        this.update_ratio();

        this.handles.forEach(el=>{
            this.container.appendChild(el);
        });

        cursor_hover(this.draggable, 'default', 'move');

        this.panel_el.appendChild(this.draggable);
        this.container.appendChild(this.panel_el);
        this.parent_el.appendChild(this.container);

        [
            this.edgemousedown, 
            this.verticalmousemove,
            this.horizontalmousemove,
            this.nwsemousemove,
            this.neswmousemove,
            this.edgemouseupleave,
        ] = [
            this.edgemousedown.bind(this),
            this.verticalmousemove.bind(this),
            this.horizontalmousemove.bind(this),
            this.nwsemousemove.bind(this),
            this.neswmousemove.bind(this),
            this.edgemouseupleave.bind(this),
        ];

        this.handle_top.addEventListener('mousedown', e=>{this.edgemousedown(e, 'top')});
        this.handle_left.addEventListener('mousedown', e=>{this.edgemousedown(e, 'left')});
        this.handle_bottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottom')});
        this.handle_right.addEventListener('mousedown', e=>{this.edgemousedown(e, 'right')}); 
        this.handle_lefttop.addEventListener('mousedown', e=>{this.edgemousedown(e, 'lefttop')});
        this.handle_topleft.addEventListener('mousedown', e=>{this.edgemousedown(e, 'topleft')});
        this.handle_topright.addEventListener('mousedown', e=>{this.edgemousedown(e, 'topright')});
        this.handle_righttop.addEventListener('mousedown', e=>{this.edgemousedown(e, 'righttop')}); 
        this.handle_rightbottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'rightbottom')}); 
        this.handle_bottomright.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottomright')});
        this.handle_bottomleft.addEventListener('mousedown', e=>{this.edgemousedown(e, 'bottomleft')});
        this.handle_leftbottom.addEventListener('mousedown', e=>{this.edgemousedown(e, 'leftbottom')});

        this.handle_top.addEventListener('mousemove', this.verticalmousemove);
        this.handle_left.addEventListener('mousemove', this.horizontalmousemove);
        this.handle_bottom.addEventListener('mousemove', this.verticalmousemove);
        this.handle_right.addEventListener('mousemove', this.horizontalmousemove); 
        this.handle_lefttop.addEventListener('mousemove', this.nwsemousemove);
        this.handle_topleft.addEventListener('mousemove', this.nwsemousemove);
        this.handle_topright.addEventListener('mousemove', this.neswmousemove);
        this.handle_righttop.addEventListener('mousemove', this.neswmousemove); 
        this.handle_rightbottom.addEventListener('mousemove', this.nwsemousemove); 
        this.handle_bottomright.addEventListener('mousemove', this.nwsemousemove);
        this.handle_bottomleft.addEventListener('mousemove', this.neswmousemove);
        this.handle_leftbottom.addEventListener('mousemove', this.neswmousemove);

        this.handle_top.addEventListener('mouseup', e=>{this.verticalmousemove(e); this.edgemouseupleave()});
        this.handle_left.addEventListener('mouseup', e=>{this.horizontalmousemove(e); this.edgemouseupleave()});
        this.handle_bottom.addEventListener('mouseup', e=>{this.verticalmousemove(e); this.edgemouseupleave()});
        this.handle_right.addEventListener('mouseup', e=>{this.horizontalmousemove(e); this.edgemouseupleave()}); 
        this.handle_lefttop.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_topleft.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_topright.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
        this.handle_righttop.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()}); 
        this.handle_rightbottom.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()}); 
        this.handle_bottomright.addEventListener('mouseup', e=>{this.nwsemousemove(e); this.edgemouseupleave()});
        this.handle_bottomleft.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
        this.handle_leftbottom.addEventListener('mouseup', e=>{this.neswmousemove(e); this.edgemouseupleave()});
    
        this.handle_top.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_left.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottom.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_right.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_lefttop.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_topleft.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_topright.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_righttop.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_rightbottom.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottomright.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_bottomleft.addEventListener('mouseleave', this.edgemouseupleave);
        this.handle_leftbottom.addEventListener('mouseleave', this.edgemouseupleave);
    }

    // box size change triggers corner handler size change
    update_ratio(){
        this.container.style.top = `${this.vtop}px`;
        this.container.style.left = `${this.vleft}px`;
        this.container.style.width = `${this.vwidth}px`;
        this.container.style.height = `${this.vheight}px`;

        this.panel_el.style.width = `${this.vwidth - 2 * this.handle_width_px}px`;
        this.panel_el.style.height = `${this.vheight - 2 * this.handle_width_px}px`;

        this.ratio = this.vwidth < this.vheight ? this.coner_vmin_ratio * this.vwidth : this.coner_vmin_ratio * this.vheight;
        [
            this.handle_top,
            this.handle_bottom, 
        ].forEach(el=>{
            el.style.width = `${this.vwidth - 2 * this.ratio}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_left,
            this.handle_right, 
        ].forEach(el=>{
            el.style.height = `${this.vheight - 2 * this.ratio}px`;
            el.style.width = `${this.handle_width_px}px`;
        });

        this.handle_top.style.top = `0`;
        this.handle_top.style.left = `${this.ratio}px`;

        this.handle_left.style.top = `${this.ratio}px`;
        this.handle_left.style.left = `0`;

        this.handle_bottom.style.bottom = `0`;
        this.handle_bottom.style.right = `${this.ratio}px`;

        this.handle_right.style.bottom = `${this.ratio}px`;
        this.handle_right.style.right = `0`;

        [
            this.handle_topright,
            this.handle_bottomleft,
        ].forEach(el=>{
            el.style.width = `${this.ratio}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_lefttop,
            this.handle_rightbottom,
        ].forEach(el=>{
            el.style.width = `${this.handle_width_px}px`;
            el.style.height = `${this.ratio}px`;
        });

        [
            this.handle_topleft,
            this.handle_bottomright,
        ].forEach(el=>{
            el.style.width = `${this.ratio - this.handle_width_px}px`;
            el.style.height = `${this.handle_width_px}px`;
        });

        [
            this.handle_righttop,
            this.handle_leftbottom,
        ].forEach(el=>{
            el.style.height = `${this.handle_width_px}px`;
            el.style.width = `${this.ratio - this.handle_width_px}px`;
        });
    }

    edgemousedown(e, flag){
        this.previous = oMousePos(e);
        this.flag = flag;
        this.drag = true;
    }

    verticalmousemove(e){
        if(this.drag){
            // -
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            switch(this.flag){
                case 'top':
                    this.vtop = this.top + ydif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                    this.vwidth = this.width;
                break;

                case 'bottom':
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                    this.vwidth = this.width;
                break;
            }
            this.update_ratio();
        }
    }

    horizontalmousemove(e){
        if(this.drag){
            // |
            this.mouse = oMousePos(e);
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'left':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;

                    this.vtop = this.top;
                    this.vheight = this.height;
                break;

                case 'right':
                    this.vwidth = this.width + xdif;
                
                    this.vtop = this.top;
                    this.vleft = this.left;
                    this.vheight = this.height;
                break;
            }
            this.update_ratio();
        }
    }

    nwsemousemove(e){
        if(this.drag){
            // \
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'topleft':
                    this.vleft = this.left + xdif;
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height - ydif;
                break;

                case 'lefttop':
                    this.vleft = this.left + xdif;
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height - ydif;
                break;

                case 'bottomright':
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                break;

                case 'rightbottom':
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                    this.vleft = this.left;
                break;
            }
            this.update_ratio();
        }
    }

    neswmousemove(e){
        if(this.drag){
            // /
            this.mouse = oMousePos(e);
            var ydif = this.mouse.y - this.previous.y;
            var xdif = this.mouse.x - this.previous.x;
            switch(this.flag){
                case 'topright':
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                break;

                case 'righttop':
                    this.vtop = this.top + ydif;
                    this.vwidth = this.width + xdif;
                    this.vheight = this.height - ydif;

                    this.vleft = this.left;
                break;

                case 'bottomleft':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                break;

                case 'leftbottom':
                    this.vleft = this.left + xdif;
                    this.vwidth = this.width - xdif;
                    this.vheight = this.height + ydif;

                    this.vtop = this.top;
                break;
            }
            this.update_ratio();
        }
    }

    edgemouseupleave(){
        this.drag = false;
        this.top = this.vtop;
        this.left = this.vleft;
        this.width = this.vwidth;
        this.height = this.vheight;
    }

    mouseupleave(e){
        if(super.mouseupleave(e)){
            this.vtop = this.top;
            this.vleft = this.left;         
        }
    }
}


var fp = new FlexPanel(
    document.body, // parent div container
    20, // top margin
    20, // left margin
    200, // width 
    150, // height
    'lightgrey', // background
    20, // handle height when horizontal; handle width when vertical
    0.2, // edge up and left resize bar width : top resize bar width = 1 : 5
    35, // green move button width and height
    2, // button margin
);

/*
this method creates an element for you
which you don't need to pass in a selected element

to manipuate dom element
fp.container -> entire panel
fp.panel_el -> inside panel
*/
_x000D_
_x000D_
_x000D_

Achieving functionalities fully requires a lot of hard coding. Please refer to the documentation, it will show you how to use each class as element.

Dynamically adding properties to an ExpandoObject

dynamic x = new ExpandoObject();
x.NewProp = string.Empty;

Alternatively:

var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);

How to change ProgressBar's progress indicator color in Android

ProgressBar color can be changed as follows:

/res/values/colors.xml

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

/res/values/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorAccent">@color/colorAccent</item>
</style> 

onCreate:

progressBar = (ProgressBar) findViewById(R.id.progressBar);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    Drawable drawable = progressBar.getIndeterminateDrawable().mutate();
    drawable.setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.SRC_IN);
    progressBar.setIndeterminateDrawable(drawable);
}

Docker is in volume in use, but there aren't any Docker containers

I am pretty sure that those volumes are actually mounted on your system. Look in /proc/mounts and you will see them there. You will likely need to sudo umount <path> or sudo umount -f -n <path>. You should be able to get the mounted path either in /proc/mounts or through docker volume inspect

Oracle listener not running and won't start

In my case somehow windows listener service had stopped working so I was not able to connect to Qracle using SQL Developer. However I was able to connect through sqlplus.

Below solution worked for me:

First, ensure that your listener service is running.

C:\Documents and Settings\ME>lsnrctl status 

If the listener service is not running, re-start the listener service using the Windows task manager or use the DOS command line utility to re-start the Windows service with the net start command:

C:\Documents and Settings\ME>net start OracleOraDb10g_home1TNSListener 

Try to start the listener service using lsnrctl from DOS prompt.

lsnrctl start

Is it better in C++ to pass by value or pass by constant reference?

As it has been pointed out, it depends on the type. For built-in data types, it is best to pass by value. Even some very small structures, such as a pair of ints can perform better by passing by value.

Here is an example, assume you have an integer value and you want pass it to another routine. If that value has been optimized to be stored in a register, then if you want to pass it be reference, it first must be stored in memory and then a pointer to that memory placed on the stack to perform the call. If it was being passed by value, all that is required is the register pushed onto the stack. (The details are a bit more complicated than that given different calling systems and CPUs).

If you are doing template programming, you are usually forced to always pass by const ref since you don't know the types being passed in. Passing penalties for passing something bad by value are much worse than the penalties of passing a built-in type by const ref.

How to completely remove Python from a Windows machine?

Almost all of the python files should live in their respective folders (C:\Python26 and C:\Python27). Some installers (ActiveState) will also associate .py* files and add the python path to %PATH% with an install if you tick the "use this as the default installation" box.

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

Add a label= to each of your plot() calls, and then call legend(loc='upper left').

Consider this sample (tested with Python 3.8.0):

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)
plt.show()

enter image description here Slightly modified from this tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html

Multiple WHERE clause in Linq

@Jon: Jon, are you saying using multiple where clauses e.g.

var query = from r in tempData.AsEnumerable()
            where r.Field<string>("UserName") != "XXXX" 
            where r.Field<string>("UserName") != "YYYY"
            select r;

is more restictive than using

var query = from r in tempData.AsEnumerable()
            where r.Field<string>("UserName") != "XXXX" && r.Field<string>("UserName") != "YYYY"
            select r;

I think they are equivalent as far as the result goes.

However, I haven't tested, if using multiple where in the first example cause in 2 subqueries, i.e. .Where(r=>r.UserName!="XXXX").Where(r=>r.UserName!="YYYY) or the LINQ translator is smart enought to execute .Where(r=>r.UserName!="XXXX" && r.UsernName!="YYYY")

Best way to detect when a user leaves a web page?

Mozilla Developer Network has a nice description and example of onbeforeunload.

If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data):

window.addEventListener('beforeunload', function(e) {
  var myPageIsDirty = ...; //you implement this logic...
  if(myPageIsDirty) {
    //following two lines will cause the browser to ask the user if they
    //want to leave. The text of this dialog is controlled by the browser.
    e.preventDefault(); //per the standard
    e.returnValue = ''; //required for Chrome
  }
  //else: user is allowed to leave without a warning dialog
});

List names of all tables in a SQL Server 2012 schema

SELECT *
FROM sys.tables t
INNER JOIN sys.objects o on o.object_id = t.object_id
WHERE o.is_ms_shipped = 0;

What does %~dp0 mean, and how does it work?

An example would be nice - here's a trivial one

for %I in (*.*) do @echo %~xI

it lists only the EXTENSIONS of each file in current folder

for more useful variable combinations (also listed in previous response) from the CMD prompt execute: HELP FOR which contains this snippet

The modifiers can be combined to get compound results:

%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
               environment variable for %I and expands to the
               drive letter and path of the first one found.
%~ftzaI     - expands %I to a DIR like output line

How to make a phone call using intent in Android?

For call from dialer (No permission needed):

   fun callFromDailer(mContext: Context, number: String) {
        try {
            val callIntent = Intent(Intent.ACTION_DIAL)
            callIntent.data = Uri.parse("tel:$number")
            mContext.startActivity(callIntent)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(mContext, "No SIM Found", Toast.LENGTH_LONG).show()
        }
    }

For direct call from app(Permission needed):

  fun callDirect(mContext: Context, number: String) {
        try {
            val callIntent = Intent(Intent.ACTION_CALL)
            callIntent.data = Uri.parse("tel:$number")
            mContext.startActivity(callIntent)
        } catch (e: SecurityException) {
            Toast.makeText(mContext, "Need call permission", Toast.LENGTH_LONG).show()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(mContext, "No SIM Found", Toast.LENGTH_LONG).show()
        }
    }

Permission:

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

Bootstrap 3 grid with no gap

The grid system in Bootstrap 3 requires a bit of a lateral shift in your thinking from Bootstrap 2. A column in BS2 (col-*) is NOT synonymous with a column in BS3 (col-sm-*, etc), but there is a way to achieve the same result.

Check out this update to your fiddle: http://jsfiddle.net/pjBzY/22/ (code copied below).

First of all, you don't need to specify a col for each screen size if you want 50/50 columns at all sizes. col-sm-6 applies not only to small screens, but also medium and large, meaning class="col-sm-6 col-md-6" is redundant (the benefit comes in if you want to change the column widths at different size screens, such as col-sm-6 col-md-8).

As for the margins issue, the negative margins provide a way to align blocks of text in a more flexible way than was possible in BS2. You'll notice in the jsfiddle, the text in the first column aligns visually with the text in the paragraph outside the row -- except at "xs" window sizes, where the columns aren't applied.

If you need behavior closer to what you had in BS2, where there is padding between each column and there are no visual negative margins, you will need to add an inner-div to each column. See the inner-content in my jsfiddle. Put something like this in each column, and they will behave the way old col-* elements did in BS2.


jsfiddle HTML

<div class="container">
    <p class="other-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquam sed sem nec viverra. Phasellus fringilla metus vitae libero posuere mattis. Integer sit amet tincidunt felis. Maecenas et pharetra leo. Etiam venenatis purus et nibh laoreet blandit.</p>
    <div class="row">
        <div class="col-sm-6 my-column">
            Col 1
            <p class="inner-content">Inner content - THIS element is more synonymous with a Bootstrap 2 col-*.</p>
        </div>
        <div class="col-sm-6 my-column">
            Col 2
        </div>
    </div>
</div>

and the CSS

.row {
    border: blue 1px solid;
}
.my-column {
    background-color: green;
    padding-top: 10px;
    padding-bottom: 10px;
}
.my-column:first-child {
    background-color: red;
}

.inner-content {
    background: #eee;
    border: #999;
    border-radius: 5px;
    padding: 15px;
}

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

You need to change the password directly in the database because at mysql the users and their profiles are saved in the database.

So there are several ways. At phpMyAdmin you simple go to user admin, choose root and change the password.

How does HTTP file upload work?

Send file as binary content (upload without form or FormData)

In the given answers/examples the file is (most likely) uploaded with a HTML form or using the FormData API. The file is only a part of the data sent in the request, hence the multipart/form-data Content-Type header.

If you want to send the file as the only content then you can directly add it as the request body and you set the Content-Type header to the MIME type of the file you are sending. The file name can be added in the Content-Disposition header. You can upload like this:

var xmlHttpRequest = new XMLHttpRequest();

var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...

xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);

If you don't (want to) use forms and you are only interested in uploading one single file this is the easiest way to include your file in the request.

Can I run multiple programs in a Docker container?

If a dedicated script seems like too much overhead, you can spawn separate processes explicitly with sh -c. For example:

CMD sh -c 'mini_httpd -C /my/config -D &' \
 && ./content_computing_loop

How can I get relative path of the folders in my android project?

File relativeFile = new File(getClass().getResource("/icons/forIcon.png").toURI());
myJFrame.setIconImage(tk.getImage(relativeFile.getAbsolutePath()));

Determine the type of an object?

On instances of object you also have the:

__class__

attribute. Here is a sample taken from Python 3.3 console

>>> str = "str"
>>> str.__class__
<class 'str'>
>>> i = 2
>>> i.__class__
<class 'int'>
>>> class Test():
...     pass
...
>>> a = Test()
>>> a.__class__
<class '__main__.Test'>

Beware that in python 3.x and in New-Style classes (aviable optionally from Python 2.6) class and type have been merged and this can sometime lead to unexpected results. Mainly for this reason my favorite way of testing types/classes is to the isinstance built in function.

VirtualBox Cannot register the hard disk already exists

The solution that worked for me is as follows:

  1. Make sure VirtualBox Manager is not running.
  2. Back up the files ~\.VirtualBox\VirtualBox.xml and ~\.VirtualBox\VirtualBox.xml-prev.
  3. Edit these files to modify the <HardDisks>...</HardDisks> section to remove the duplicate entry of <HardDisk />.
  4. Now run VirtualBox Manager.

Example:

  <HardDisks>
    <HardDisk uuid="{38f266bd-0959-4caf-a0de-27ac9d52e3663}" location="~/VirtualBox VMs/VM1/box-disk001.vmdk" format="VMDK" type="Normal"/>
    <HardDisk uuid="{a6708d79-7393-4d96-89da-2539f75c5465e}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
    <HardDisk uuid="{bdce5d4e-9a1c-4f57-acfd-e2acfc8920552}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
  </HardDisks>

Note in the above fragment that the last two entries refer to the same VM but have different uuid's. One of them is invalid and should be removed. Which one is invalid can be found out by hit and trial -- first remove the second entry and try; if it doesn't work, remove the third entry.

Select From all tables - MySQL

You get all tables containing the column product using this statment:

SELECT DISTINCT TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME IN ('Product')
        AND TABLE_SCHEMA='YourDatabase';

Then you have to run a cursor on these tables so you select eachtime:

Select * from OneTable where product like '%XYZ%'

The results should be entered into a 3rd table or view, take a look here.

Notice: This can work only if the structure of all table is similar, otherwise aou will have to see which columns are united for all these tables and create your result table / View to contain only these columns.

What properties does @Column columnDefinition make redundant?

columnDefinition will override the sql DDL generated by hibernate for this particular column, it is non portable and depends on what database you are using. You can use it to specify nullable, length, precision, scale... ect.

How can I create a progress bar in Excel VBA?

In the past, with VBA projects, I've used a label control with the background colored and adjust the size based on the progress. Some examples with similar approaches can be found in the following links:

  1. http://oreilly.com/pub/h/2607
  2. http://www.ehow.com/how_7764247_create-progress-bar-vba.html
  3. http://spreadsheetpage.com/index.php/tip/displaying_a_progress_indicator/

Here is one that uses Excel's Autoshapes:

http://www.andypope.info/vba/pmeter.htm

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Passing just a type as a parameter in C#

You can use an argument of type Type - iow, pass typeof(int). You can also use generics for a (probably more efficient) approach.

Remove all the children DOM elements in div

From the dojo API documentation:

dojo.html._emptyNode(node);

How to uncheck checked radio button

try this

_x000D_
_x000D_
var radio_button=false;_x000D_
$('.radio-button').on("click", function(event){_x000D_
  var this_input=$(this);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.attr('checked1','11')_x000D_
  } else {_x000D_
    this_input.attr('checked1','22')_x000D_
  }_x000D_
  $('.radio-button').prop('checked', false);_x000D_
  if(this_input.attr('checked1')=='11') {_x000D_
    this_input.prop('checked', false);_x000D_
    this_input.attr('checked1','22')_x000D_
  } else {_x000D_
    this_input.prop('checked', true);_x000D_
    this_input.attr('checked1','11')_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
_x000D_
_x000D_

Clear an input field with Reactjs?

Also after React v 16.8+ you have an ability to use hooks

import React, {useState} from 'react';

const ControlledInputs = () => {
  const [firstName, setFirstName] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (firstName) {
      console.log('firstName :>> ', firstName);
    }
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
          <label htmlFor="firstName">Name: </label>
          <input
            type="text"
            id="firstName"
            name="firstName"
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
          />
        <button type="submit">add person</button>
      </form>
    </>
  );
};

How to reset db in Django? I get a command 'reset' not found error

python manage.py flush

deleted old db contents,

Don't forget to create new superuser:

python manage.py createsuperuser

What's "tools:context" in Android layout files?

This attribute helps to get the best knowledge of the activity associated with your layout. This is also useful when you have to add onClick handlers on a view using QuickFix.

tools:context=".MainActivity"

How to capture the android device screen content?

[Based on Android source code:]

At the C++ side, the SurfaceFlinger implements the captureScreen API. This is exposed over the binder IPC interface, returning each time a new ashmem area that contains the raw pixels from the screen. The actual screenshot is taken through OpenGL.

For the system C++ clients, the interface is exposed through the ScreenshotClient class, defined in <surfaceflinger_client/SurfaceComposerClient.h> for Android < 4.1; for Android > 4.1 use <gui/SurfaceComposerClient.h>

Before JB, to take a screenshot in a C++ program, this was enough:

ScreenshotClient ssc;
ssc.update();

With JB and multiple displays, it becomes slightly more complicated:

ssc.update(
    android::SurfaceComposerClient::getBuiltInDisplay(
        android::ISurfaceComposer::eDisplayIdMain));

Then you can access it:

do_something_with_raw_bits(ssc.getPixels(), ssc.getSize(), ...);

Using the Android source code, you can compile your own shared library to access that API, and then expose it through JNI to Java. To create a screen shot form your app, the app has to have the READ_FRAME_BUFFER permission. But even then, apparently you can create screen shots only from system applications, i.e. ones that are signed with the same key as the system. (This part I still don't quite understand, since I'm not familiar enough with the Android Permissions system.)

Here is a piece of code, for JB 4.1 / 4.2:

#include <utils/RefBase.h>
#include <binder/IBinder.h>
#include <binder/MemoryHeapBase.h>
#include <gui/ISurfaceComposer.h>
#include <gui/SurfaceComposerClient.h>

static void do_save(const char *filename, const void *buf, size_t size) {
    int out = open(filename, O_RDWR|O_CREAT, 0666);
    int len = write(out, buf, size);
    printf("Wrote %d bytes to out.\n", len);
    close(out);
}

int main(int ac, char **av) {
    android::ScreenshotClient ssc;
    const void *pixels;
    size_t size;
    int buffer_index;

    if(ssc.update(
        android::SurfaceComposerClient::getBuiltInDisplay(
            android::ISurfaceComposer::eDisplayIdMain)) != NO_ERROR ){
        printf("Captured: w=%d, h=%d, format=%d\n");
        ssc.getWidth(), ssc.getHeight(), ssc.getFormat());
        size = ssc.getSize();
        do_save(av[1], pixels, size);
    }
    else
        printf(" screen shot client Captured Failed");
    return 0;
}

Applying a single font to an entire website with CSS

As a different font is likely to be already defined by the browser for form elements, here are 2 ways to use this font everywhere:

body, input, textarea {
    font-family: Algerian;
}

body {
    font-family: Algerian !important;
}

There'll still have a monospace font on elements like pre/code, kbd, etc but, in case you use these elements, you'd better use a monospace font there.

Important note: if very few people has this font installed on their OS, then the second font in the list will be used. Here you defined no second font so the default serif font will be used, and it'll be Times, Times New Roman except maybe on Linux.
Two options there: use @font-face if your font is free of use as a downloadable font or add fallback(s): a second, a third, etc and finally a default family (sans-serif, cursive (*), monospace or serif). The first of the list that exists on the OS of the user will be used.

(*) default cursive on Windows is Comic Sans. Except if you want to troll Windows users, don't do that :) This font is terrible except for your children birthdays where it's welcome.

How to store values from foreach loop into an array?

Try

$items = array_values ( $group_membership );

accepting HTTPS connections with self-signed certificates

This is problem resulting from lack of SNI(Server Name Identification) support inA,ndroid 2.x. I was struggling with this problem for a week until I came across the following question, which not only gives a good background of the problem but also provides a working and effective solution devoid of any security holes.

'No peer certificate' error in Android 2.3 but NOT in 4

How to enable SOAP on CentOS

The yum install php-soap command will install the Soap module for php 5.x

For installing the correct version for your environment I recommend to create a file info.php and put this code: <?php echo phpinfo(); ?>

In the header you'll see the version you're using:

enter image description here

Now that you know the correct version you can run this command: yum search php-soap

This command will return the avaliable versions:

php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php54-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php55-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php56-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php73-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php74-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol

Now you just need to choose the correct module to your php version.

For this example, you should run this command php72-php-soap.x86_64

How to use LINQ to select object with minimum or maximum property value

So you are asking for ArgMin or ArgMax. C# doesn't have a built-in API for those.

I've been looking for a clean and efficient (O(n) in time) way to do this. And I think I found one:

The general form of this pattern is:

var min = data.Select(x => (key(x), x)).Min().Item2;
                            ^           ^       ^
              the sorting key           |       take the associated original item
                                Min by key(.)

Specially, using the example in original question:

For C# 7.0 and above that supports value tuple:

var youngest = people.Select(p => (p.DateOfBirth, p)).Min().Item2;

For C# version before 7.0, anonymous type can be used instead:

var youngest = people.Select(p => new {age = p.DateOfBirth, ppl = p}).Min().ppl;

They work because both value tuple and anonymous type have sensible default comparers: for (x1, y1) and (x2, y2), it first compares x1 vs x2, then y1 vs y2. That's why the built-in .Min can be used on those types.

And since both anonymous type and value tuple are value types, they should be both very efficient.

NOTE

In my above ArgMin implementations I assumed DateOfBirth to take type DateTime for simplicity and clarity. The original question asks to exclude those entries with null DateOfBirth field:

Null DateOfBirth values are set to DateTime.MaxValue in order to rule them out of the Min consideration (assuming at least one has a specified DOB).

It can be achieved with a pre-filtering

people.Where(p => p.DateOfBirth.HasValue)

So it's immaterial to the question of implementing ArgMin or ArgMax.

NOTE 2

The above approach has a caveat that when there are two instances that have the same min value, then the Min() implementation will try to compare the instances as a tie-breaker. However, if the class of the instances does not implement IComparable, then a runtime error will be thrown:

At least one object must implement IComparable

Luckily, this can still be fixed rather cleanly. The idea is to associate a distanct "ID" with each entry that serves as the unambiguous tie-breaker. We can use an incremental ID for each entry. Still using the people age as example:

var youngest = Enumerable.Range(0, int.MaxValue)
               .Zip(people, (idx, ppl) => (ppl.DateOfBirth, idx, ppl)).Min().Item3;

Renaming branches remotely in Git

If you really just want to rename branches remotely, without renaming any local branches at the same time, you can do this with a single command:

git push <remote> <remote>/<old_name>:refs/heads/<new_name> :<old_name>

I wrote this script (git-rename-remote-branch) which provides a handy shortcut to do the above easily.

As a bash function:

git-rename-remote-branch(){
  if [ $# -ne 3 ]; then
    echo "Rationale : Rename a branch on the server without checking it out."
    echo "Usage     : ${FUNCNAME[0]} <remote> <old name> <new name>"
    echo "Example   : ${FUNCNAME[0]} origin master release"
    return 1 
  fi

  git push $1 $1/$2\:refs/heads/$3 :$2
}

To integrate @ksrb's comment: What this basically does is two pushes in a single command, first git push <remote> <remote>/<old_name>:refs/heads/<new_name> to push a new remote branch based on the old remote tracking branch and then git push <remote> :<old_name> to delete the old remote branch.

jQuery events .load(), .ready(), .unload()

If both "document.ready" variants are used they will both fire, in the order of appearance

$(function(){
    alert('shorthand document.ready');
});

//try changing places
$(document).ready(function(){
    alert('document.ready');
});

Python CSV error: line contains NULL byte

I got the same error. Saved the file in UTF-8 and it worked.

Vuejs and Vue.set(), update array

VueJS can't pickup your changes to the state if you manipulate arrays like this.

As explained in Common Beginner Gotchas, you should use array methods like push, splice or whatever and never modify the indexes like this a[2] = 2 nor the .length property of an array.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    f: 'DD-MM-YYYY',_x000D_
    items: [_x000D_
      "10-03-2017",_x000D_
      "12-03-2017"_x000D_
    ]_x000D_
  },_x000D_
  methods: {_x000D_
_x000D_
    cha: function(index, item, what, count) {_x000D_
      console.log(item + " index > " + index);_x000D_
      val = moment(this.items[index], this.f).add(count, what).format(this.f);_x000D_
_x000D_
      this.items.$set(index, val)_x000D_
      console.log("arr length:  " + this.items.length);_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<div id="app">_x000D_
  <ul>_x000D_
    <li v-for="(index, item) in items">_x000D_
      <br><br>_x000D_
      <button v-on:click="cha(index, item, 'day', -1)">_x000D_
      - day</button> {{ item }}_x000D_
      <button v-on:click="cha(index, item, 'day', 1)">_x000D_
      + day</button>_x000D_
      <br><br>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

git stash changes apply to new branch?

Is the standard procedure not working?

  • make changes
  • git stash save
  • git branch xxx HEAD
  • git checkout xxx
  • git stash pop

Shorter:

  • make changes
  • git stash
  • git checkout -b xxx
  • git stash pop

How to specify Memory & CPU limit in docker compose version 3

Docker Compose does not support the deploy key. It's only respected when you use your version 3 YAML file in a Docker Stack.

This message is printed when you add the deploy key to you docker-compose.yml file and then run docker-compose up -d

WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use docker stack deploy to deploy to a swarm.

The documentation (https://docs.docker.com/compose/compose-file/#deploy) says:

Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.

Hide Command Window of .BAT file that Executes Another .EXE File

Using Windows API we can start new process, a console application, and hide its "black" window. This can be done at process creation and avoid showing "black" window at all.

In CreateProcess function the dwCreationFlags parameter can have CREATE_NO_WINDOW flag:

The process is a console application that is being run
without a console window. Therefore, the console handle
for the application is not set. This flag is ignored if
the application is not a console application

Here is a link to hide-win32-console-window executable using this method and source code.

hide-win32-console-window is similar to Jamesdlin's silentbatch program.

There is open question: what to do with program's output when its window does not exist? What if exceptions happen? Not a good solution to throw away the output. hide-win32-console-window uses anonymous pipes to redirect program's output to file created in current directory.

Usage

batchscript_starter.exe full/path/to/application [arguments to pass on]

Example running python script

batchscript_starter.exe c:\Python27\python.exe -c "import time; print('prog start'); time.sleep(3.0); print('prog end');"

The output file is created in working directory named python.2019-05-13-13-32-39.log with output from the python command:

prog start
prog end

Example running command

batchscript_starter.exe C:\WINDOWS\system32\cmd.exe /C dir .

The output file is created in working directory named cmd.2019-05-13-13-37-28.log with output from CMD:

 Volume in drive Z is Storage
 Volume Serial Number is XXXX-YYYY

 Directory of hide_console_project\hide-win32-console-window

2019-05-13  13:37    <DIR>          .
2019-05-13  13:37    <DIR>          ..
2019-05-13  04:41            17,274 batchscript_starter.cpp
2018-04-10  01:08            46,227 batchscript_starter.ico
2019-05-12  11:27             7,042 batchscript_starter.rc
2019-05-12  11:27             1,451 batchscript_starter.sln
2019-05-12  21:51             8,943 batchscript_starter.vcxproj
2019-05-12  21:51             1,664 batchscript_starter.vcxproj.filters
2019-05-13  03:38             1,736 batchscript_starter.vcxproj.user
2019-05-13  13:37                 0 cmd.2019-05-13-13-37-28.log
2019-05-13  04:34             1,518 LICENSE
2019-05-13  13:32                22 python.2019-05-13-13-32-39.log
2019-05-13  04:55                82 README.md
2019-05-13  04:44             1,562 Resource.h
2018-04-10  01:08            46,227 small.ico
2019-05-13  04:44               630 targetver.h
2019-05-13  04:57    <DIR>          x64
              14 File(s)        134,378 bytes
               3 Dir(s)  ???,???,692,992 bytes free

Example shortcut for running .bat script

Shortcut for starting windowless .bat file

Target field:

C:\batchscript_starter.exe C:\WINDOWS\system32\cmd.exe /C C:\start_wiki.bat

Directory specified in Start in field will hold output files.

How to add button inside input

This can be achieved using inline-block JS fiddle here

<html>
<body class="body">
    <div class="form">
        <form class="email-form">
            <input type="text" class="input">
            <a href="#" class="button">Button</a>
        </form>
    </div>
</body>
</html>


<style>
* {
    box-sizing: border-box;
}

.body {
    font-family: Arial, sans-serif;
    font-size: 14px;
    line-height: 20px;
    color: #333;
}

.form {
    display: block;
    margin: 0 0 15px;
}

.email-form {
    display: block;
    margin-top: 20px;
    margin-left: 20px;
}

.button {
    height: 40px;
    display: inline-block;
    padding: 9px 15px;
    background-color: grey;
    color: white;
    border: 0;
    line-height: inherit;
    text-decoration: none;
    cursor: pointer;
}

.input {
    display: inline-block;
    width: 200px;
    height: 40px;
    margin-bottom: 0px;
    padding: 9px 12px;
    color: #333333;
    vertical-align: middle;
    background-color: #ffffff;
    border: 1px solid #cccccc;
    margin: 0;
    line-height: 1.42857143;
}
</style>

Throw away local commits in Git

If you are using Atlassian SourceTree app, you could use the reset option in the context menu.

enter image description here

Can I disable a CSS :hover effect via JavaScript?

I would use CSS to prevent the :hover event from changing the appearance of the link.

a{
  font:normal 12px/15px arial,verdana,sans-serif;
  color:#000;
  text-decoration:none;
}

This simple CSS means that the links will always be black and not underlined. I cannot tell from the question whether the change in the appearance is the only thing you want to control.

jQuery Validate Required Select

An easier solution has been outlined here: Validate select box

Make the value be empty and add the required attribute

<select id="select" class="required">
<option value="">Choose an option</option> 
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>

How to use awk sort by column 3

To exclude the first line (header) from sorting, I split it out into two buffers.

df | awk 'BEGIN{header=""; $body=""} { if(NR==1){header=$0}else{body=body"\n"$0}} END{print header; print body|"sort -nk3"}'

Last segment of URL in jquery

Javascript has the function split associated to string object that can help you:

var url = "http://mywebsite/folder/file";
var array = url.split('/');

var lastsegment = array[array.length-1];

Finding the Eclipse Version Number

Here is a working code snippet that will print out the full version of currently running Eclipse (or any RCP-based application).

String product = System.getProperty("eclipse.product");
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint point = registry.getExtensionPoint("org.eclipse.core.runtime.products");
Logger log = LoggerFactory.getLogger(getClass());
if (point != null) {
  IExtension[] extensions = point.getExtensions();
  for (IExtension ext : extensions) {
    if (product.equals(ext.getUniqueIdentifier())) {
      IContributor contributor = ext.getContributor();
      if (contributor != null) {
        Bundle bundle = Platform.getBundle(contributor.getName());
        if (bundle != null) {
          System.out.println("bundle version: " + bundle.getVersion());
        }
      }
    }
  }
}

It looks up the currently running "product" extension and takes the version of contributing plugin.

On Eclipse Luna 4.4.0, it gives the result of 4.4.0.20140612-0500 which is correct.

In Angular, how to pass JSON object/array into directive?

If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.


First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.

I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.

app.factory('locations', function($http) {
  var promise = null;

  return function() {
    if (promise) {
      // If we've already asked for this data once,
      // return the promise that already exists.
      return promise;
    } else {
      promise = $http.get('locations/locations.json');
      return promise;
    }
  };
});

As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations service into the directive, but this couples the directive to that service.

A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.

- The 80/20 Guide to Writing AngularJS Directives

In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.

app.controller('SomeController', function($scope, locations) {
  locations().success(function(data) {
    $scope.locations = data;
  });
});
<ul class="list">
   <li ng-repeat="location in locations">
      <a href="#">{{location.id}}. {{location.name}}</a>
   </li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div></div>',
    scope: {
      // creates a scope variable in your directive
      // called `locations` bound to whatever was passed
      // in via the `locations` attribute in the DOM
      locations: '=locations'
    },
    link: function(scope, element, attrs) {
      scope.$watch('locations', function(locations) {
        angular.forEach(locations, function(location, key) {
          // do something
        });
      });
    }
  };
});

In this way, the map directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.

Redirect to Action by parameter mvc

This error is very non-descriptive but the key here is that 'ID' is in uppercase. This indicates that the route has not been correctly set up. To let the application handle URLs with an id, you need to make sure that there's at least one route configured for it. You do this in the RouteConfig.cs located in the App_Start folder. The most common is to add the id as an optional parameter to the default route.

public static void RegisterRoutes(RouteCollection routes)
{
    //adding the {id} and setting is as optional so that you do not need to use it for every action
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Now you should be able to redirect to your controller the way you have set it up.

[HttpPost]
public ActionResult RedirectToImages(int id)
{
    return RedirectToAction("Index","ProductImageManager", new { id });

    //if the action is in the same controller, you can omit the controller:
    //RedirectToAction("Index", new { id });
}

In one or two occassions way back I ran into some issues by normal redirect and had to resort to doing it by passing a RouteValueDictionary. More information on RedirectToAction with parameter

return RedirectToAction("Index", new RouteValueDictionary( 
    new { controller = "ProductImageManager", action = "Index", id = id } ) 
);

If you get a very similar error but in lowercase 'id', this is usually because the route expects an id parameter that has not been provided (calling a route without the id /ProductImageManager/Index). See this so question for more information.

Detecting iOS orientation change instantly

Try making your changes in:

- (void) viewWillLayoutSubviews {}

The code will run at every orientation change as the subviews get laid out again.

Serialize Class containing Dictionary member

You should explore Json.Net, quite easy to use and allows Json objects to be deserialized in Dictionary directly.

james_newtonking

example:

string json = @"{""key1"":""value1"",""key2"":""value2""}";
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); 
Console.WriteLine(values.Count);
// 2
Console.WriteLine(values["key1"]);
// value1

html table cell width for different rows

You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.

You can however have cells span multiple columns, such as:

<table>
    <tr>
        <td>25</td>
        <td>50</td>
        <td>25</td>
    </tr>
    <tr>
        <td colspan="2">75</td>
        <td>20</td>
    </tr>
</table>

As an aside, you should avoid using style attributes like border and bgcolor and prefer CSS for those.

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

You must just put the values into parentheses:

'%s in %s' % (unicode(self.author),  unicode(self.publication))

Here, for the first %s the unicode(self.author) will be placed. And for the second %s, the unicode(self.publication) will be used.

Note: You should favor string formatting over the % Notation. More info here

Using Google maps API v3 how do I get LatLng with a given address?

I don't think location.LatLng is working, however this works:

results[0].geometry.location.lat(), results[0].geometry.location.lng()

Found it while exploring Get Lat Lon source code.

Angular redirect to login page

Here's an updated example using Angular 4 (also compatible with Angular 5 - 8)

Routes with home route protected by AuthGuard

import { Routes, RouterModule } from '@angular/router';

import { LoginComponent } from './login/index';
import { HomeComponent } from './home/index';
import { AuthGuard } from './_guards/index';

const appRoutes: Routes = [
    { path: 'login', component: LoginComponent },

    // home route protected by auth guard
    { path: '', component: HomeComponent, canActivate: [AuthGuard] },

    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

export const routing = RouterModule.forRoot(appRoutes);

AuthGuard redirects to login page if user isn't logged in

Updated to pass original url in query params to login page

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

For the full example and working demo you can check out this post

wamp server mysql user id and password

Simply goto MySql Console.

If using Wamp:

  1. Click on Wamp icon just beside o'clock.
  2. In MySql section click on MySql Console.
  3. Press enter (means no password) twice.
  4. mysql commands preview like this : mysql>
  5. SET PASSWORD FOR 'root'@'localhost' = PASSWORD('secret');

That's it. This set your root password to secret

In order to set user privilege to default one:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('');

Works like a charm!

Git merge with force overwrite

I had a similar issue, where I needed to effectively replace any file that had changes / conflicts with a different branch.

The solution I found was to use git merge -s ours branch.

Note that the option is -s and not -X. -s denotes the use of ours as a top level merge strategy, -X would be applying the ours option to the recursive merge strategy, which is not what I (or we) want in this case.

Steps, where oldbranch is the branch you want to overwrite with newbranch.

  • git checkout newbranch checks out the branch you want to keep
  • git merge -s ours oldbranch merges in the old branch, but keeps all of our files.
  • git checkout oldbranch checks out the branch that you want to overwrite
  • get merge newbranch merges in the new branch, overwriting the old branch

Calculate the display width of a string in Java

Use the getWidth method in the following class:

import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;

class StringMetrics {

  Font font;
  FontRenderContext context;

  public StringMetrics(Graphics2D g2) {

    font = g2.getFont();
    context = g2.getFontRenderContext();
  }

  Rectangle2D getBounds(String message) {

    return font.getStringBounds(message, context);
  }

  double getWidth(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getWidth();
  }

  double getHeight(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getHeight();
  }

}

Java Array, Finding Duplicates

You can also work with Set, which doesn't allow duplicates in Java..

    for (String name : names)
    {         
      if (set.add(name) == false) 
         { // your duplicate element }
    }

using add() method and check return value. If add() returns false it means that element is not allowed in the Set and that is your duplicate.

allowing only alphabets in text box using java script

<html>
<head>
    <title>allwon only alphabets in textbox using JavaScript</title>
    <script language="Javascript" type="text/javascript">

        function onlyAlphabets(e, t) {
            try {
                if (window.event) {
                    var charCode = window.event.keyCode;
                }
                else if (e) {
                    var charCode = e.which;
                }
                else { return true; }
                if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
                    return true;
                else
                    return false;
            }
            catch (err) {
                alert(err.Description);
            }
        }

    </script>
</head>
<body>
    <table align="center">
        <tr>
            <td>
                <input type="text" onkeypress="return onlyAlphabets(event,this);" />
            </td>
        </tr>
    </table>
</body>
</html>

setting system property

For JBoss, in standalone.xml, put after .

<extensions>
</extensions>

<system-properties>
    <property name="my.project.dir" value="/home/francesco" />
</system-properties>

For eclipse:

http://www.avajava.com/tutorials/lessons/how-do-i-set-system-properties.html?page=2

How to sort a dataFrame in python pandas by two or more columns?

As of pandas 0.17.0, DataFrame.sort() is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values

As such, the answer to your question would now be

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

C++ correct way to return pointer to array from function

Your code is OK. Note though that if you return a pointer to an array, and that array goes out of scope, you should not use that pointer anymore. Example:

int* test (void)
{
    int out[5];
    return out;
}

The above will never work, because out does not exist anymore when test() returns. The returned pointer must not be used anymore. If you do use it, you will be reading/writing to memory you shouldn't.

In your original code, the arr array goes out of scope when main() returns. Obviously that's no problem, since returning from main() also means that your program is terminating.

If you want something that will stick around and cannot go out of scope, you should allocate it with new:

int* test (void)
{
    int* out = new int[5];
    return out;
}

The returned pointer will always be valid. Remember do delete it again when you're done with it though, using delete[]:

int* array = test();
// ...
// Done with the array.
delete[] array;

Deleting it is the only way to reclaim the memory it uses.

How to get coordinates of an svg element?

The way to determine the coordinates depends on what element you're working with. For circles for example, the cx and cy attributes determine the center position. In addition, you may have a translation applied through the transform attribute which changes the reference point of any coordinates.

Most of the ways used in general to get screen coordinates won't work for SVGs. In addition, you may not want absolute coordinates if the line you want to draw is in the same container as the elements it connects.

Edit:

In your particular code, it's quite difficult to get the position of the node because its determined by a translation of the parent element. So you need to get the transform attribute of the parent node and extract the translation from that.

d3.transform(d3.select(this.parentNode).attr("transform")).translate

Working jsfiddle here.

replacing NA's with 0's in R dataframe

dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5);
data <- as.data.frame(dataset)
[,1] [,2] [,3] [,4] [,5] 
[1,]    2    3    5    5    4
[2,]    2    4    3    2    4
[3,]    2   NA   NA   NA    2
[4,]    2    3   NA    5    5
[5,]    2    3    2    2    3
data[is.na(data)] <- 0

Java List.contains(Object with field value equal to x)

contains method uses equals internally. So you need to override the equals method for your class as per your need.

Btw this does not look syntatically correct:

new Object().setName("John")

How to submit form on change of dropdown list?

other than using this.form.submit() you also submiting by id or name. example i have form like this : <form action="" name="PostName" id="IdName">

  1. By Name : <select onchange="PostName.submit()">

  2. By Id : <select onchange="IdName.submit()">

Trigger to fire only if a condition is met in SQL Server

Your where clause should have worked. I am at a loss as to why it didn't. Let me show you how I would have figured out the problem with the where clause as it might help you for the future.

When I create triggers, I start at the query window by creating a temp table called #inserted (and or #deleted) with all the columns of the table. Then I popultae it with typical values (Always multiple records and I try to hit the test cases in the values)

Then I write my triggers logic and I can test without it actually being in a trigger. In a case like your where clause not doing what was expected, I could easily test by commenting out the insert to see what the select was returning. I would then probably be easily able to see what the problem was. I assure you that where clasues do work in triggers if they are written correctly.

Once I know that the code works properly for all the cases, I global replace #inserted with inserted and add the create trigger code around it and voila, a tested trigger.

AS I said in a comment, I have a concern that the solution you picked will not work properly in a multiple record insert or update. Triggers should always be written to account for that as you cannot predict if and when they will happen (and they do happen eventually to pretty much every table.)

Setting different color for each series in scatter plot on matplotlib

You can always use the plot() function like so:

import matplotlib.pyplot as plt

import numpy as np

x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
plt.figure()
for y in ys:
    plt.plot(x, y, 'o')
plt.show()

plot as scatter but changes colors

"Keep Me Logged In" - the best approach

Introduction

Your title “Keep Me Logged In” - the best approach make it difficult for me to know where to start because if you are looking at best approach then you would have to consideration the following :

  • Identification
  • Security

Cookies

Cookies are vulnerable, Between common browser cookie-theft vulnerabilities and cross-site scripting attacks we must accept that cookies are not safe. To help improve security you must note that php setcookies has additional functionality such as

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

  • secure (Using HTTPS connection)
  • httponly (Reduce identity theft through XSS attack)

Definitions

  • Token ( Unpredictable random string of n length eg. /dev/urandom)
  • Reference ( Unpredictable random string of n length eg. /dev/urandom)
  • Signature (Generate a keyed hash value using the HMAC method)

Simple Approach

A simple solution would be :

  • User is logged on with Remember Me
  • Login Cookie issued with token & Signature
  • When is returning, Signature is checked
  • If Signature is ok .. then username & token is looked up in the database
  • if not valid .. return to login page
  • If valid automatically login

The above case study summarizes all example given on this page but they disadvantages is that

  • There is no way to know if the cookies was stolen
  • Attacker may be access sensitive operations such as change of password or data such as personal and baking information etc.
  • The compromised cookie would still be valid for the cookie life span

Better Solution

A better solution would be

  • User is logged in and remember me is selected
  • Generate Token & signature and store in cookie
  • The tokens are random and are only valid for single autentication
  • The token are replace on each visit to the site
  • When a non-logged user visit the site the signature, token and username are verified
  • Remember me login should have limited access and not allow modification of password, personal information etc.

Example Code

// Set privateKey
// This should be saved securely 
$key = 'fc4d57ed55a78de1a7b31e711866ef5a2848442349f52cd470008f6d30d47282';
$key = pack("H*", $key); // They key is used in binary form

// Am Using Memecahe as Sample Database
$db = new Memcache();
$db->addserver("127.0.0.1");

try {
    // Start Remember Me
    $rememberMe = new RememberMe($key);
    $rememberMe->setDB($db); // set example database

    // Check if remember me is present
    if ($data = $rememberMe->auth()) {
        printf("Returning User %s\n", $data['user']);

        // Limit Acces Level
        // Disable Change of password and private information etc

    } else {
        // Sample user
        $user = "baba";

        // Do normal login
        $rememberMe->remember($user);
        printf("New Account %s\n", $user);
    }
} catch (Exception $e) {
    printf("#Error  %s\n", $e->getMessage());
}

Class Used

class RememberMe {
    private $key = null;
    private $db;

    function __construct($privatekey) {
        $this->key = $privatekey;
    }

    public function setDB($db) {
        $this->db = $db;
    }

    public function auth() {

        // Check if remeber me cookie is present
        if (! isset($_COOKIE["auto"]) || empty($_COOKIE["auto"])) {
            return false;
        }

        // Decode cookie value
        if (! $cookie = @json_decode($_COOKIE["auto"], true)) {
            return false;
        }

        // Check all parameters
        if (! (isset($cookie['user']) || isset($cookie['token']) || isset($cookie['signature']))) {
            return false;
        }

        $var = $cookie['user'] . $cookie['token'];

        // Check Signature
        if (! $this->verify($var, $cookie['signature'])) {
            throw new Exception("Cokies has been tampared with");
        }

        // Check Database
        $info = $this->db->get($cookie['user']);
        if (! $info) {
            return false; // User must have deleted accout
        }

        // Check User Data
        if (! $info = json_decode($info, true)) {
            throw new Exception("User Data corrupted");
        }

        // Verify Token
        if ($info['token'] !== $cookie['token']) {
            throw new Exception("System Hijacked or User use another browser");
        }

        /**
         * Important
         * To make sure the cookie is always change
         * reset the Token information
         */

        $this->remember($info['user']);
        return $info;
    }

    public function remember($user) {
        $cookie = [
                "user" => $user,
                "token" => $this->getRand(64),
                "signature" => null
        ];
        $cookie['signature'] = $this->hash($cookie['user'] . $cookie['token']);
        $encoded = json_encode($cookie);

        // Add User to database
        $this->db->set($user, $encoded);

        /**
         * Set Cookies
         * In production enviroment Use
         * setcookie("auto", $encoded, time() + $expiration, "/~root/",
         * "example.com", 1, 1);
         */
        setcookie("auto", $encoded); // Sample
    }

    public function verify($data, $hash) {
        $rand = substr($hash, 0, 4);
        return $this->hash($data, $rand) === $hash;
    }

    private function hash($value, $rand = null) {
        $rand = $rand === null ? $this->getRand(4) : $rand;
        return $rand . bin2hex(hash_hmac('sha256', $value . $rand, $this->key, true));
    }

    private function getRand($length) {
        switch (true) {
            case function_exists("mcrypt_create_iv") :
                $r = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
                break;
            case function_exists("openssl_random_pseudo_bytes") :
                $r = openssl_random_pseudo_bytes($length);
                break;
            case is_readable('/dev/urandom') : // deceze
                $r = file_get_contents('/dev/urandom', false, null, 0, $length);
                break;
            default :
                $i = 0;
                $r = "";
                while($i ++ < $length) {
                    $r .= chr(mt_rand(0, 255));
                }
                break;
        }
        return substr(bin2hex($r), 0, $length);
    }
}

Testing in Firefox & Chrome

enter image description here

Advantage

  • Better Security
  • Limited access for attacker
  • When cookie is stolen its only valid for single access
  • When next the original user access the site you can automatically detect and notify the user of theft

Disadvantage

  • Does not support persistent connection via multiple browser (Mobile & Web)
  • The cookie can still be stolen because the user only gets the notification after the next login.

Quick Fix

  • Introduction of approval system for each system that must have persistent connection
  • Use multiple cookies for the authentication

Multiple Cookie Approach

When an attacker is about to steal cookies the only focus it on a particular website or domain eg. example.com

But really you can authenticate a user from 2 different domains (example.com & fakeaddsite.com) and make it look like "Advert Cookie"

  • User Logged on to example.com with remember me
  • Store username, token, reference in cookie
  • Store username, token, reference in Database eg. Memcache
  • Send refrence id via get and iframe to fakeaddsite.com
  • fakeaddsite.com uses the reference to fetch user & token from Database
  • fakeaddsite.com stores the signature
  • When a user is returning fetch signature information with iframe from fakeaddsite.com
  • Combine it data and do the validation
  • ..... you know the remaining

Some people might wonder how can you use 2 different cookies ? Well its possible, imagine example.com = localhost and fakeaddsite.com = 192.168.1.120. If you inspect the cookies it would look like this

enter image description here

From the image above

  • The current site visited is localhost
  • It also contains cookies set from 192.168.1.120

192.168.1.120

  • Only accepts defined HTTP_REFERER
  • Only accepts connection from specified REMOTE_ADDR
  • No JavaScript, No content but consist nothing rather than sign information and add or retrieve it from cookie

Advantage

  • 99% percent of the time you have tricked the attacker
  • You can easily lock the account in the attacker first attempt
  • Attack can be prevented even before the next login like the other methods

Disadvantage

  • Multiple Request to server just for a single login

Improvement

  • Done use iframe use ajax

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

I've found the answer regarding how to do this myself. Inside the model code, just put:

For Rails <= 2:

include ActionController::UrlWriter

For Rails 3:

include Rails.application.routes.url_helpers

This magically makes thing_path(self) return the URL for the current thing, or other_model_path(self.association_to_other_model) return some other URL.

Clear data in MySQL table with PHP?

TRUNCATE will blank your table and reset primary key DELETE will also make your table blank but it will not reset primary key.

we can use for truncate

TRUNCATE TABLE tablename

we can use for delete

DELETE FROM tablename

we can also give conditions as below

DELETE FROM tablename WHERE id='xyz'

Convert PEM traditional private key to PKCS8 private key

To convert the private key from PKCS#1 to PKCS#8 with openssl:

# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key

That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.

SQL Server: Invalid Column Name

I had a similar problem.

Issue was there was a trigger on the table that would write changes to an audit log table. Columns were missing in audit log table.

Getting the filenames of all files in a folder

You could do it like that:

File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  if (listOfFiles[i].isFile()) {
    System.out.println("File " + listOfFiles[i].getName());
  } else if (listOfFiles[i].isDirectory()) {
    System.out.println("Directory " + listOfFiles[i].getName());
  }
}

Do you want to only get JPEG files or all files?

HTML: can I display button text in multiple lines?

This CSS might work for <input type="button" ..:

white-space: normal

Close application and launch home screen on Android

When you launch the second activity, finish() the first one immediately:

startActivity(new Intent(...));
finish();

How to convert string to integer in UNIX

The standard solution:

 expr $d1 - $d2

You can also do:

echo $(( d1 - d2 ))

but beware that this will treat 07 as an octal number! (so 07 is the same as 7, but 010 is different than 10).

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

How to check if an Object is a Collection Type in Java?

Test if the object implements either java.util.Collection or java.util.Map. (Map has to be tested separately because it isn't a sub-interface of Collection.)

Convert NSDate to String in iOS Swift

DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:

extension Date {  
  func asString(style: DateFormatter.Style) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = style
    return dateFormatter.string(from: self)
  }
}

This gives you the following styles:

short, medium, long, full

Example usage:

let myDate = Date()
myDate.asString(style: .full)   // Wednesday, January 10, 2018
myDate.asString(style: .long)   // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short)  // 1/10/18

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

I ran into this issue when I was manually beginning and committing transactions inside of method annotated as @Transactional. I fixed the problem by detecting if an active transaction already existed.

//Detect underlying transaction
if (session.getTransaction() != null && session.getTransaction().isActive()) {
    myTransaction = session.getTransaction();
    preExistingTransaction = true;
} else {
    myTransaction = session.beginTransaction();
}

Then I allowed Spring to handle committing the transaction.

private void finishTransaction() {
    if (!preExistingTransaction) {
        try {
            tx.commit();
        } catch (HibernateException he) {
            if (tx != null) {
                tx.rollback();
            }
            log.error(he);
        } finally {
            if (newSessionOpened) {
                SessionFactoryUtils.closeSession(session);
                newSessionOpened = false;
                maxResults = 0;
            }
        }
    }
}

How do you reverse a string in place in JavaScript?

var reverseString = function(str){ 
  let length = str.length - 1;
  str = str.split('');

  for(let i=0;i<= length;i++){
    str[length + i + 1] = str[length - i];
  }

  return str.splice(length + 1).join('');
}

PHP namespaces and "use"

If you need to order your code into namespaces, just use the keyword namespace:

file1.php

namespace foo\bar;

In file2.php

$obj = new \foo\bar\myObj();

You can also use use. If in file2 you put

use foo\bar as mypath;

you need to use mypath instead of bar anywhere in the file:

$obj  = new mypath\myObj();

Using use foo\bar; is equal to use foo\bar as bar;.

If a DOM Element is removed, are its listeners also removed from memory?

Don't hesitate to watch heap to see memory leaks in event handlers keeping a reference to the element with a closure and the element keeping a reference to the event handler.

Garbage collector do not like circular references.

Usual memory leak case: admit an object has a ref to an element. That element has a ref to the handler. And the handler has a ref to the object. The object has refs to a lot of other objects. This object was part of a collection you think you have thrown away by unreferencing it from your collection. => the whole object and all it refers will remain in memory till page exit. => you have to think about a complete killing method for your object class or trust a mvc framework for example.

Moreover, don't hesitate to use the Retaining tree part of Chrome dev tools.

How to change the color of a button?

For the text color add:

android:textColor="<hex color>"


For the background color add:

android:background="<hex color>"


From API 21 you can use:

android:backgroundTint="<hex color>"
android:backgroundTintMode="<mode>"

Note: If you're going to work with android/java you really should learn how to google ;)
How to customize different buttons in Android

How to get featured image of a product in woocommerce

I did this and it works great

<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail(); ?></a>
<?php } ?>

How do you create a Distinct query in HQL

It's worth noting that the distinct keyword in HQL does not map directly to the distinct keyword in SQL.

If you use the distinct keyword in HQL, then sometimes Hibernate will use the distinct SQL keyword, but in some situations it will use a result transformer to produce distinct results. For example when you are using an outer join like this:

select distinct o from Order o left join fetch o.lineItems

It is not possible to filter out duplicates at the SQL level in this case, so Hibernate uses a ResultTransformer to filter duplicates after the SQL query has been performed.

pyplot scatter plot marker size

If the size of the circles corresponds to the square of the parameter in s=parameter, then assign a square root to each element you append to your size array, like this: s=[1, 1.414, 1.73, 2.0, 2.24] such that when it takes these values and returns them, their relative size increase will be the square root of the squared progression, which returns a linear progression.

If I were to square each one as it gets output to the plot: output=[1, 2, 3, 4, 5]. Try list interpretation: s=[numpy.sqrt(i) for i in s]

How to make a div have a fixed size?

<div class="ai">a b c d e f</div> // something like ~100px
<div class="ai">a b c d e</div> // ~80
<div class="ai">a b c d</div> // ~60 

<script>

function _reWidthAll_div(classname) {

var _maxwidth = 0;

    $(classname).each(function(){

    var _width = $(this).width();

    _maxwidth = (_width >= _maxwidth) ? _width : _maxwidth; // define max width
    });    

$(classname).width(_maxwidth); // return all div same width

}

_reWidthAll_div('.ai');

</script>

How to add label in chart.js for pie chart

Use ChartNew.js instead of Chart.js

...

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

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

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

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

So sweet.

What do $? $0 $1 $2 mean in shell script?

These are positional arguments of the script.

Executing

./script.sh Hello World

Will make

$0 = ./script.sh
$1 = Hello
$2 = World

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.

Only allow specific characters in textbox

For your validation event IMO the easiest method would be to use a character array to validate textbox characters against. True - iterating and validating isn't particularly efficient, but it is straightforward.

Alternately, use a regular expression of your whitelist characters against the input string. Your events are availalbe at MSDN here: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

Thank to Brian for the code. I was trying to connect to the sql server with {call spname(?,?)} and I got errors, but when I change my code to exec sp... it works very well.

I post my code in hope this helps others with problems like mine:

ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();

try {
    cs=conn.prepareStatement("exec sp_name ?,?,?,?,?,?,?");
    cs.setEscapeProcessing(true);
    cs.setQueryTimeout(90);

    cs.setString(1, "valueA");

    cs.setString(2, "valueB");

    cs.setString(3, "0418");

    //commented, because no need to register parameters out!, I got results from the resultset. 
    //cs.registerOutParameter(1, Types.VARCHAR);
    //cs.registerOutParameter(2, Types.VARCHAR);

    rs = cs.executeQuery();
    ArrayList<ObjectX> listaObjectX = new ArrayList<ObjectX>();
    while (rs.next()) {

        ObjectX to = new ObjectX();
        to.setFecha(rs.getString(1));
        to.setRefId(rs.getString(2));
        to.setRefNombre(rs.getString(3));
        to.setUrl(rs.getString(4));

        listaObjectX.add(to);

    }
    return listaObjectX;
     } catch (SQLException se) {
        System.out.println("Error al ejecutar SQL"+ se.getMessage());
        se.printStackTrace();
        throw new IllegalArgumentException("Error al ejecutar SQL: " + se.getMessage());

    } finally {

        try {

            rs.close();
            cs.close();
          con.close();

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

When should I use mmap for file access?

An advantage that isn't listed yet is the ability of mmap() to keep a read-only mapping as clean pages. If one allocates a buffer in the process's address space, then uses read() to fill the buffer from a file, the memory pages corresponding to that buffer are now dirty since they have been written to.

Dirty pages can not be dropped from RAM by the kernel. If there is swap space, then they can be paged out to swap. But this is costly and on some systems, such as small embedded devices with only flash memory, there is no swap at all. In that case, the buffer will be stuck in RAM until the process exits, or perhaps gives it back withmadvise().

Non written to mmap() pages are clean. If the kernel needs RAM, it can simply drop them and use the RAM the pages were in. If the process that had the mapping accesses it again, it cause a page fault the kernel re-loads the pages from the file they came from originally. The same way they were populated in the first place.

This doesn't require more than one process using the mapped file to be an advantage.

How to run a specific Android app using Terminal?

I used all the above answers and it was giving me errors so I tried

adb shell monkey -p com.yourpackage.name -c android.intent.category.LAUNCHER 1

and it worked. One advantage is you dont have to specify your launcher activity if you use this command.

Add carriage return to a string

Environment.NewLine should be used as Dan Rigby said but there is one problem with the String.Empty. It will remain always empty no matter if it is read before or after it reads. I had a problem in my project yesterday with that. I removed it and it worked the way it was supposed to. It's better to declare the variable and then call it when it's needed. String.Empty will always keep it empty unless the variable needs to be initialized which only then should you use String.Empty. Thought I would throw this tid-bit out for everyone as I've experienced it.

Extract a substring using PowerShell

other solution

$template="-----start-------{Value:This is a test 123}------end-------"
$text="-----start-------Hello World------end-------"

$text | ConvertFrom-String -TemplateContent $template

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

I encountered the same problem in the code and What I did is I found out all the changes I have made from the last correct compilation. And I have observed one function declaration was without ";" and also it was passing a value and I have declared it to pass nothing "void". this method will surely solve the problem for many.

Viscon

SQL statement to select all rows from previous day

Its a really old thread, but here is my take on it. Rather than 2 different clauses, one greater than and less than. I use this below syntax for selecting records from A date. If you want a date range then previous answers are the way to go.

SELECT * FROM TABLE_NAME WHERE 
DATEDIFF(DAY, DATEADD(DAY, X , CURRENT_TIMESTAMP), <column_name>) = 0

In the above case X will be -1 for yesterday's records

What is the difference between Scala's case class and class?

Technically, there is no difference between a class and a case class -- even if the compiler does optimize some stuff when using case classes. However, a case class is used to do away with boiler plate for a specific pattern, which is implementing algebraic data types.

A very simple example of such types are trees. A binary tree, for instance, can be implemented like this:

sealed abstract class Tree
case class Node(left: Tree, right: Tree) extends Tree
case class Leaf[A](value: A) extends Tree
case object EmptyLeaf extends Tree

That enable us to do the following:

// DSL-like assignment:
val treeA = Node(EmptyLeaf, Leaf(5))
val treeB = Node(Node(Leaf(2), Leaf(3)), Leaf(5))

// On Scala 2.8, modification through cloning:
val treeC = treeA.copy(left = treeB.left)

// Pretty printing:
println("Tree A: "+treeA)
println("Tree B: "+treeB)
println("Tree C: "+treeC)

// Comparison:
println("Tree A == Tree B: %s" format (treeA == treeB).toString)
println("Tree B == Tree C: %s" format (treeB == treeC).toString)

// Pattern matching:
treeA match {
  case Node(EmptyLeaf, right) => println("Can be reduced to "+right)
  case Node(left, EmptyLeaf) => println("Can be reduced to "+left)
  case _ => println(treeA+" cannot be reduced")
}

// Pattern matches can be safely done, because the compiler warns about
// non-exaustive matches:
def checkTree(t: Tree) = t match {
  case Node(EmptyLeaf, Node(left, right)) =>
  // case Node(EmptyLeaf, Leaf(el)) =>
  case Node(Node(left, right), EmptyLeaf) =>
  case Node(Leaf(el), EmptyLeaf) =>
  case Node(Node(l1, r1), Node(l2, r2)) =>
  case Node(Leaf(e1), Leaf(e2)) =>
  case Node(Node(left, right), Leaf(el)) =>
  case Node(Leaf(el), Node(left, right)) =>
  // case Node(EmptyLeaf, EmptyLeaf) =>
  case Leaf(el) =>
  case EmptyLeaf =>
}

Note that trees construct and deconstruct (through pattern match) with the same syntax, which is also exactly how they are printed (minus spaces).

And they can also be used with hash maps or sets, since they have a valid, stable hashCode.

offsetTop vs. jQuery.offset().top

You can use parseInt(jQuery.offset().top) to always use the Integer (primitive - int) value across all browsers.

SELECT CASE WHEN THEN (SELECT)

For a start the first select has 6 columns and the second has 4 columns. Perhaps make both have the same number of columns (adding nulls?).

Simulate a button click in Jest

Additionally to the solutions that were suggested in sibling comments, you may change your testing approach a little bit and test not the whole page all at once (with a deep children components tree), but do an isolated component testing. This will simplify testing of onClick() and similar events (see example below).

The idea is to test only one component at a time and not all of them together. In this case all children components will be mocked using the jest.mock() function.

Here is an example of how the onClick() event may be tested in an isolated SearchForm component using Jest and react-test-renderer.

import React from 'react';
import renderer from 'react-test-renderer';
import { SearchForm } from '../SearchForm';

describe('SearchForm', () => {
  it('should fire onSubmit form callback', () => {
    // Mock search form parameters.
    const searchQuery = 'kittens';
    const onSubmit = jest.fn();

    // Create test component instance.
    const testComponentInstance = renderer.create((
      <SearchForm query={searchQuery} onSearchSubmit={onSubmit} />
    )).root;

    // Try to find submit button inside the form.
    const submitButtonInstance = testComponentInstance.findByProps({
      type: 'submit',
    });
    expect(submitButtonInstance).toBeDefined();

    // Since we're not going to test the button component itself
    // we may just simulate its onClick event manually.
    const eventMock = { preventDefault: jest.fn() };
    submitButtonInstance.props.onClick(eventMock);

    expect(onSubmit).toHaveBeenCalledTimes(1);
    expect(onSubmit).toHaveBeenCalledWith(searchQuery);
  });
});

What does "Object reference not set to an instance of an object" mean?

If I have the class:

public class MyClass
{
   public void MyMethod()
   {

   }
}

and I then do:

MyClass myClass = null;
myClass.MyMethod();

The second line throws this exception becuase I'm calling a method on a reference type object that is null (I.e. has not been instantiated by calling myClass = new MyClass())

MySQL root password change

So many coments, but i was helped this method:

sudo mysqladmin -u root password 'my password'

In my case after instalation i had get mysql service without a password for root user, and i was need set the password for my security.

Simple way to read single record from MySQL

at first : CREATE connection

$conn =  new mysqli('localhost', 'User DB', 'Pass DB', 'Table name');

and then get the record target :

$query = "SELECT id FROM games LIMIT 1"; // for example query
$result = $conn->query($query); // run query
if($result->num_rows){ //if exist something
    $ret = $result->fetch_array(MYSQLI_ASSOC); //fetch data
}else{
    $ret = false;
}
var_dump($ret);

How to create an email form that can send email using html

you can use Simple Contact Form in HTML with PHP mailer. It's easy to implement in you website. You can try the demo from following link: Simple Contact/Feedback Form in HTML-PHP mailer

Otherwise you can watch the demo video in following link: Youtube: Simple Contact/Feedback Form in HTML-PHP mailer

When you are running in localhost, you may get following error:

Warning: mail(): Failed to connect to mailserver at "smtp.gmail.com" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in S:\wamp\www\sample\mailTo.php on line 10

You can check in this link for more detailed information: Simple Contact/Feedback Form in HTML with php (HTML-PHP mailer) And this is the screenshot of HTML form: Simple Form

And this is the main PHP coding:

<?php
if($_POST["submit"]) {
    $recipient="[email protected]"; //Enter your mail address
    $subject="Contact from Website"; //Subject 
    $sender=$_POST["name"];
    $senderEmail=$_POST["email"];
    $message=$_POST["comments"];
    $mailBody="Name: $sender\nEmail Address: $senderEmail\n\nMessage: $message";
    mail($recipient, $subject, $mailBody);
    sleep(1);
    header("Location:http://blog.antonyraphel.in/sample/"); // Set here redirect page or destination page
}
?>

Math constant PI value in C

The closest thing C does to "computing p" in a way that's directly visible to applications is acos(-1) or similar. This is almost always done with polynomial/rational approximations for the function being computed (either in C, or by the FPU microcode).

However, an interesting issue is that computing the trigonometric functions (sin, cos, and tan) requires reduction of their argument modulo 2p. Since 2p is not a diadic rational (and not even rational), it cannot be represented in any floating point type, and thus using any approximation of the value will result in catastrophic error accumulation for large arguments (e.g. if x is 1e12, and 2*M_PI differs from 2p by e, then fmod(x,2*M_PI) differs from the correct value of 2p by up to 1e12*e/p times the correct value of x mod 2p. That is to say, it's completely meaningless.

A correct implementation of C's standard math library simply has a gigantic very-high-precision representation of p hard coded in its source to deal with the issue of correct argument reduction (and uses some fancy tricks to make it not-quite-so-gigantic). This is how most/all C versions of the sin/cos/tan functions work. However, certain implementations (like glibc) are known to use assembly implementations on some cpus (like x86) and don't perform correct argument reduction, leading to completely nonsensical outputs. (Incidentally, the incorrect asm usually runs about the same speed as the correct C code for small arguments.)

Change grid interval and specify tick labels in Matplotlib

A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))

# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

Wordpress plugin install: Could not create directory

I was on XAMPP for linux localhost and this worked for me:

sudo chown -R my-linux-username wp-content

How to remove all characters after a specific character in python?

Split on your separator at most once, and take the first piece:

sep = '...'
stripped = text.split(sep, 1)[0]

You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.

Open window in JavaScript with HTML inserted

You can open a new popup window by following code:

var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');

Afterwards, you can add HTML using both myWindow.document.write(); or myWindow.document.body.innerHTML = "HTML";

What I will recommend is that first you create a new html file with any name. In this example I am using

newFile.html

And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id. in this example I have given id="mainBody" to my newFile.html <body> tag

<body id="mainBody">

Then open this file using

<script>    
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>

And add whatever you want to add in your body tag. using following code

<script>    
 var myWindow = window.open("newFile.html","newWindow","width=500,height=700");  

   myWindow.onload = function(){
     let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
   myWindow.document.getElementById('mainBody').innerHTML = content;
    } 

myWindow.window.close();
 </script>

it is as simple as that.

Get $_POST from multiple checkboxes

you have to name your checkboxes accordingly:

<input type="checkbox" name="check_list[]" value="…" />

you can then access all checked checkboxes with

// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
   // do something
}

ps. make sure to properly escape your output (htmlspecialchars())

Getting the Username from the HKEY_USERS values

By searching for my userid in the registry, I found

HKEY_CURRENT_USER\Volatile Environment\Username

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

String.format() to format double in java

String.format("%4.3f" , x) ;

It means that we need total 4 digits in ans , of which 3 should be after decimal . And f is the format specifier of double . x means the variable for which we want to find it . Worked for me . . .

How to Refresh a Component in Angular

kdo

// reload page hack methode

push(uri: string) {
    this.location.replaceState(uri) // force replace and no show change
    await this.router.navigate([uri, { "refresh": (new Date).getTime() }]);
    this.location.replaceState(uri) // replace
  }

Plotting dates on the x-axis with Python's matplotlib

You can do this more simply using plot() instead of plot_date().

First, convert your strings to instances of Python datetime.date:

import datetime as dt

dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here

Then plot:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()

Result:

enter image description here

How can I use an ES6 import in Node.js?

Back to Jonathan002's original question about

"... what version supports the new ES6 import statements?"

based on the article by Dr. Axel Rauschmayer, there is a plan to have it supported by default (without the experimental command line flag) in Node.js 10.x LTS. According to node.js's release plan as it is on 3/29, 2018, it's likely to become available after Apr 2018, while LTS of it will begin on October 2018.

How do I log a Python error with debug information?

A clean way to do it is using format_exc() and then parse the output to get the relevant part:

from traceback import format_exc

try:
    1/0
except Exception:
    print 'the relevant part is: '+format_exc().split('\n')[-2]

Regards

python JSON only get keys in first level

for key in data.keys():
    print key

How can I make a button have a rounded border in Swift?

To do this job in storyboard (Interface Builder Inspector)

With help of IBDesignable, we can add more options to Interface Builder Inspector for UIButton and tweak them on storyboard. First, add the following code to your project.

@IBDesignable extension UIButton {

    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
        }
        get {
            return layer.cornerRadius
        }
    }

    @IBInspectable var borderColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            layer.borderColor = uiColor.cgColor
        }
        get {
            guard let color = layer.borderColor else { return nil }
            return UIColor(cgColor: color)
        }
    }
}

Then simply set the attributes for buttons on storyboard.

enter image description here

Build the full path filename in Python

Um, why not just:

>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'

Using curl to upload POST data with files

Catching the user id as path variable (recommended):

curl -i -X POST -H "Content-Type: multipart/form-data" 
-F "[email protected]" http://mysuperserver/media/1234/upload/

Catching the user id as part of the form:

curl -i -X POST -H "Content-Type: multipart/form-data" 
-F "[email protected];userid=1234" http://mysuperserver/media/upload/

or:

curl -i -X POST -H "Content-Type: multipart/form-data" 
-F "[email protected]" -F "userid=1234" http://mysuperserver/media/upload/

If "0" then leave the cell blank

Use =IF(H15+G16-F16=0,"",H15+G16-F16)

HTML Agility pack - parsing tables

The most simple what I've found to get the XPath for a particular Element is to install FireBug extension for Firefox go to the site/webpage press F12 to bring up firebug; right select and right click the element on the page that you want to query and select "Inspect Element" Firebug will select the element in its IDE then right click the Element in Firebug and choose "Copy XPath" this function will give you the exact XPath Query you need to get the element you want using HTML Agility Library.

How to SELECT a dropdown list item by value programmatically

ddlPageSize.Items.FindByValue("25").Selected = true;

Convert string into integer in bash script - "Leading Zero" number error

How about sed?

hour=`echo $hour|sed -e "s/^0*//g"`

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

For me, the below helped

Find org.apache.http.legacy.jar which is in Android/Sdk/platforms/android-23/optional, add it to your dependency.

Source

How to get the squared symbol (²) to display in a string

Not sure what kind of text box you are refering to. However, I'm not sure if you can do this in a text box on a user form.

A text box on a sheet you can though.

Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Text = "R2=" & variable
Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Characters(2, 1).Font.Superscript = msoTrue

And same thing for an excel cell

Sheets("Sheet1").Range("A1").Characters(2, 1).Font.Superscript = True

If this isn't what you're after you will need to provide more information in your question.

EDIT: posted this after the comment sorry

How do I load a PHP file into a variable?

ob_start();
include "yourfile.php";
$myvar = ob_get_clean();

ob_get_clean()

Looping each row in datagridview

You could loop through DataGridView using Rows property, like:

foreach (DataGridViewRow row in datagridviews.Rows)
{
   currQty += row.Cells["qty"].Value;
   //More code here
}

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

I know it's a very old question, but is the first in my google search and after some time I got how to solve this.

find node on your windows with
$ npm install -g which
$ which node
after cd into the directory, inside the directory cd into node_modules\npm folder and finally:
$ npm install node-gyp@latest
here worked, the answer is from this site

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

This works for me:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

Static variables in C++

Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.

When static variable is declared in a header file is its scope limited to .h file or across all units.

There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.

As such, a static variable declared in a header file is like a static variable in each individual source file.

Since declaring a variable static this way means internal linkage, every translation unit #includeing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.

I would like to know what is the difference between static variables in a header file vs declared in a class.

In a class declaration, static means that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to the static (or "class") variable, it's the same value for all objects. You could think of it as a "class global".

Also generally static variable is initialized in .cpp file when declared in a class right ?

Yes, one (and only one) translation unit must initialize the class variable.

So that does mean static variable scope is limited to 2 compilation units ?

As I said:

  • A header is not a compilation unit,
  • static means completely different things depending on context.

Global static limits scope to the translation unit. Class static means global to all instances.

I hope this helps.

PS: Check the last paragraph of Chubsdad's answer, about how you shouldn't use static in C++ for indicating internal linkage, but anonymous namespaces. (Because he's right. ;-) )

Print a list in reverse order with range()?

range(9,-1,-1)
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Is the correct form. If you use

reversed(range(10))

you wont get a 0 case. For instance, say your 10 isn't a magic number and a variable you're using to lookup start from reverse. If your n case is 0, reversed(range(0)) will not execute which is wrong if you by chance have a single object in the zero index.

How to get images in Bootstrap's card to be the same height/width?

Each of the images need to be the exact dimensions before you put them up otherwise bootstrap 4 will try to place them in a funky shape. Bootstrap also has something like Masonry on their documents that you can use if need be, you can see that here, http://v4-alpha.getbootstrap.com/components/card/#columns.

How to change an image on click using CSS alone?

Try this (but once clicked, it is not reversible):

HTML:

<a id="test"><img src="normal-image.png"/></a>

CSS:

a#test {
    border: 0;
}
a#test:visited img, a#test:active img {
    background-image: url(clicked-image.png);
}

How to make child process die after parent exits?

I think a quick and dirty way is to create a pipe between child and parent. When parent exits, children will receive a SIGPIPE.

SSH configuration: override the default username

Create a file called config inside ~/.ssh. Inside the file you can add:

Host *
    User buck

Or add

Host example
    HostName example.net
    User buck

The second example will set a username and is hostname specific, while the first example sets a username only. And when you use the second one you don't need to use ssh example.net; ssh example will be enough.

Time part of a DateTime Field in SQL

Try this in SQL Server 2008:

select *
from some_table t
where convert(time,t.some_datetime_column) = '5pm'

If you want take a random datetime value and adjust it so the time component is 5pm, then in SQL Server 2008 there are a number of ways. First you need start-of-day (e.g., 2011-09-30 00:00:00.000).

  • One technique that works for all versions of Microsoft SQL Server as well as all versions of Sybase is to use convert/3 to convert the datetime value to a varchar that lacks a time component and then back into a datetime value:

    select convert(datetime,convert(varchar,current_timestamp,112),112)
    

The above gives you start-of-day for the current day.

  • In SQL Server 2008, though, you can say something like this:

    select start_of_day =               t.some_datetime_column
                        - convert(time, t.some_datetime_column ) ,
    from some_table t
    

    which is likely faster.

Once you have start-of-day, getting to 5pm is easy. Just add 17 hours to your start-of-day value:

select five_pm = dateadd(hour,17, t.some_datetime_column
                   - convert(time,t.some_datetime_column)
                   )
from some_table t

How to call external url in jquery?

JQuery and PHP

In PHP file "contenido.php":

<?php
$mURL = $_GET['url'];

echo file_get_contents($mURL);
?>

In html:

<script type="text/javascript" src="js/jquery/jquery.min.js"></script>
<script type="text/javascript">
    function getContent(pUrl, pDivDestino){
        var mDivDestino = $('#'+pDivDestino);

        $.ajax({
            type : 'GET',
            url : 'contenido.php',
            dataType : 'html',
            data: {
                url : pUrl
            },
            success : function(data){                                               
                mDivDestino.html(data);
            }   
        });
    }
</script>

<a href="#" onclick="javascript:getContent('http://www.google.com/', 'contenido')">Get Google</a>
<div id="contenido"></div>

How can I turn a List of Lists into a List in Java 8?

You can use the flatCollect() pattern from Eclipse Collections.

MutableList<List<Object>> list = Lists.mutable.empty();
MutableList<Object> flat = list.flatCollect(each -> each);

If you can't change list from List:

List<List<Object>> list = new ArrayList<>();
List<Object> flat = ListAdapter.adapt(list).flatCollect(each -> each);

Note: I am a contributor to Eclipse Collections.

How can I do width = 100% - 100px in CSS?

You can't.

You can, however, use margins to effect the same result.

Flexbox and Internet Explorer 11 (display:flex in <html>?)

Here is an example of using flex that also works in Internet Explorer 11 and Chrome.

HTML

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >_x000D_
<title>Flex Test</title>_x000D_
<style>_x000D_
html, body {_x000D_
    margin: 0px;_x000D_
    padding: 0px;_x000D_
    height: 100vh;_x000D_
}_x000D_
.main {_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    -ms-flex-direction: row;_x000D_
    flex-direction: row;_x000D_
    align-items: stretch;_x000D_
    min-height: 100vh;_x000D_
}_x000D_
_x000D_
.main::after {_x000D_
  content: '';_x000D_
  height: 100vh;_x000D_
  width: 0;_x000D_
  overflow: hidden;_x000D_
  visibility: hidden;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
.left {_x000D_
    width: 200px;_x000D_
    background: #F0F0F0;_x000D_
    flex-shrink: 0;_x000D_
}_x000D_
_x000D_
.right {_x000D_
    flex-grow: 1;_x000D_
    background: yellow;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="main">_x000D_
    <div class="left">_x000D_
        <div style="height: 300px;">_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="right">_x000D_
        <div style="height: 1000px;">_x000D_
            test test test_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

ASP.net Repeater get current index, pointer, or counter

To display the item number on the repeater you can use the Container.ItemIndex property.

<asp:repeater id="rptRepeater" runat="server">
    <itemtemplate>
        Item <%# Container.ItemIndex + 1 %>| <%# Eval("Column1") %>
    </itemtemplate>
    <separatortemplate>
        <br />
    </separatortemplate>
</asp:repeater>

What is w3wp.exe?

w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.

You can get more information on w3wp.exe here

http://www.processlibrary.com/en/directory/files/w3wp/25761/

How to replicate vector in c?

https://github.com/jakubgorny47/baku-code/tree/master/c_vector

Here's my implementation. It's basicaly a struct containing pointer to the data, size (in elements), overall allocated space and a size of the type that's being stored in vector to allow use of void pointer.

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

Handling click events on a drawable within an EditText

@Override
    public boolean onTouch(View v, MotionEvent event) {

        Drawable drawableObj = getResources().getDrawable(R.drawable.search_btn);
        int drawableWidth = drawableObj.getIntrinsicWidth();

        int x = (int) event.getX();
        int y = (int) event.getY();

        if (event != null && event.getAction() == MotionEvent.ACTION_UP) {
            if (x >= (searchPanel_search.getWidth() - drawableWidth - searchPanel_search.getPaddingRight())
                    && x <= (searchPanel_search.getWidth() - searchPanel_search.getPaddingRight())

                    && y >= searchPanel_search.getPaddingTop() && y <= (searchPanel_search.getHeight() - searchPanel_search.getPaddingBottom())) {

                getSearchData();
            }

            else {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(searchPanel_search, InputMethodManager.SHOW_FORCED);
            }
        }
        return super.onTouchEvent(event);

    }

Make a nav bar stick

To make header sticky, first you have to give position: fixed; for header in css. Then you can adjust width and height etc. I would highly recommand to follow this article. How to create a sticky website header

Here is code as well to work around on header to make it sticky.

header { 
   position: fixed; 
   right: 0; 
   left: 0; 
   z-index: 999;
}

This code above will go inside your styles.css file.

How do I use NSTimer?

there are a couple of ways of using a timer:

1) scheduled timer & using selector

NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
                      target: self
                      selector:@selector(onTick:)
                      userInfo: nil repeats:NO];
  • if you set repeats to NO, the timer will wait 2 seconds before running the selector and after that it will stop;
  • if repeat: YES, the timer will start immediatelly and will repeat calling the selector every 2 seconds;
  • to stop the timer you call the timer's -invalidate method: [t invalidate];

As a side note, instead of using a timer that doesn't repeat and calls the selector after a specified interval, you could use a simple statement like this:

[self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];

this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;

2) self-scheduled timer

NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
                              interval: 1
                              target: self
                              selector:@selector(onTick:)
                              userInfo:nil repeats:YES];

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
  • this will create a timer that will start itself on a custom date specified by you (in this case, after a minute), and repeats itself every one second

3) unscheduled timer & using invocation

NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];

NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
                      invocation:inv 
                      repeats:YES];

and after that, you start the timer manually whenever you need like this:

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];



And as a note, onTick: method looks like this:

-(void)onTick:(NSTimer *)timer {
   //do smth
}

How to insert a character in a string at a certain position?

// Create given String and make with size 30
String str = "Hello How Are You";

// Creating StringBuffer Object for right padding
StringBuffer stringBufferRightPad = new StringBuffer(str);
while (stringBufferRightPad.length() < 30) {
    stringBufferRightPad.insert(stringBufferRightPad.length(), "*");
}

System.out.println("after Left padding : " + stringBufferRightPad);
System.out.println("after Left padding : " + stringBufferRightPad.toString());

// Creating StringBuffer Object for right padding
StringBuffer stringBufferLeftPad = new StringBuffer(str);
while (stringBufferLeftPad.length() < 30) {
    stringBufferLeftPad.insert(0, "*");
}
System.out.println("after Left padding : " + stringBufferLeftPad);
System.out.println("after Left padding : " + stringBufferLeftPad.toString());

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

Is there a way to compile node.js source files?

You can use the Closure compiler to compile your javascript.

You can also use CoffeeScript to compile your coffeescript to javascript.

What do you want to achieve with compiling?

The task of compiling arbitrary non-blocking JavaScript down to say, C sounds very daunting.

There really isn't that much speed to be gained by compiling to C or ASM. If you want speed gain offload computation to a C program through a sub process.

ExtJs Gridpanel store refresh

I had a similiar problem. All I needed to do was type store.load(); in the delete handler. There was no need to subsequently type grid.getView().refresh();.

Instead of all this you can also type store.remove(record) in the delete handler; - this ensures that the deleted record no longer shows on the grid.

Extract string between two strings in java

Your regex looks correct, but you're splitting with it instead of matching with it. You want something like this:

// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Get visible items in RecyclerView

First / last visible child depends on the LayoutManager. If you are using LinearLayoutManager or GridLayoutManager, you can use

int findFirstVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastVisibleItemPosition();
int findLastCompletelyVisibleItemPosition();

For example:

GridLayoutManager layoutManager = ((GridLayoutManager)mRecyclerView.getLayoutManager());
int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();

For LinearLayoutManager, first/last depends on the adapter ordering. Don't query children from RecyclerView; LayoutManager may prefer to layout more items than visible for caching.

Enable remote connections for SQL Server Express 2012

I had to add a firewall inbound port rule to open UDP port 1434. This is the one Sql Server Browser listens on.

Calculate a Running Total in SQL Server

BEGIN TRAN
CREATE TABLE #Table (_Id INT IDENTITY(1,1) ,id INT ,    somedate VARCHAR(100) , somevalue INT)


INSERT INTO #Table ( id  ,    somedate  , somevalue  )
SELECT 45 , '01/Jan/09', 3 UNION ALL
SELECT 23 , '08/Jan/09', 5 UNION ALL
SELECT 12 , '02/Feb/09', 0 UNION ALL
SELECT 77 , '14/Feb/09', 7 UNION ALL
SELECT 39 , '20/Feb/09', 34 UNION ALL
SELECT 33 , '02/Mar/09', 6 

;WITH CTE ( _Id, id  ,  _somedate  , _somevalue ,_totvalue ) AS
(

 SELECT _Id , id  ,    somedate  , somevalue ,somevalue
 FROM #Table WHERE _id = 1
 UNION ALL
 SELECT #Table._Id , #Table.id  , somedate  , somevalue , somevalue + _totvalue
 FROM #Table,CTE 
 WHERE #Table._id > 1 AND CTE._Id = ( #Table._id-1 )
)

SELECT * FROM CTE

ROLLBACK TRAN

Peak signal detection in realtime timeseries data

Instead of comparing a maxima to the mean, one can also compare the maxima to adjacent minima where the minima are only defined above a noise threshold. If the local maximum is > 3 times (or other confidence factor) either adjacent minima, then that maxima is a peak. The peak determination is more accurate with wider moving windows. The above uses a calculation centered on the middle of the window, by the way, rather than a calculation at the end of the window (== lag).

Note that a maxima has to be seen as an increase in signal before and a decrease after.

100% width background image with an 'auto' height

Just use a two color background image:

<div style="width:100%; background:url('images/bkgmid.png');
       background-size: cover;">
content
</div>

CSS Disabled scrolling

overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.

overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.

overflow: hidden;
would remove both scrollbars

Create a custom View by inflating a layout?

In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:

In my_table_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:id="@+id/myTableRow">
    <ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
</TableRow>

Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.

for (int i=0; i<numRows; i++) {
    /*
     * 1. Make the row and attach it to myTable. For some reason this doesn't seem
     * to return the TableRow as you might expect from the xml, so you need to
     * receive the View it returns and then find the TableRow and other items, as
     * per step 2.
     */
    LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v =  inflater.inflate(R.layout.my_table_row, myTable, true);

    // 2. Get all the things that we need to refer to to alter in any way.
    TableRow    tr        = (TableRow)    v.findViewById(R.id.profileTableRow);
    ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
    TextView    rowText   = (TextView)    v.findViewById(R.id.rowText);

    // 3. Configure them out as you need to
    rowText.setText("Text for this row");
    rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
    rowButton.setOnClickListener(this); // See note below ...           

    /*
     * To ensure that when finding views by id on the next time round this
     * loop (or later) gie lots of spurious, unique, ids.
     */
    rowText.setId(1000+i);
    tr.setId(3000+i);
}

For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

How do I divide in the Linux console?

You should try to use:

echo "scale=4;$variablename/3"|bc

Open a URL in a new tab (and not a new window)

this work for me, just prevent the event, add the url to an <a> tag then trigger the click event on that tag.

Js
$('.myBtn').on('click', function(event) {
        event.preventDefault();
        $(this).attr('href',"http://someurl.com");
        $(this).trigger('click');
});
HTML
<a href="#" class="myBtn" target="_blank">Go</a>

Create a new file in git bash

This is a very simple to create file in git bash at first write touch then file name with extension

for example

touch filename.extension

Can I write native iPhone apps using Python?

Yes, nowadays you can develop apps for iOS in Python.

There are two frameworks that you may want to checkout: Kivy and PyMob.

Please consider the answers to this question too, as they are more up-to-date than this one.