Programs & Examples On #Synclock

SyncLock is the VB.NET keyword for its locking statement.

Minimum and maximum value of z-index?

Z-Index only works for elements that have position: relative; or position: absolute; applied to them. If that's not the problem we'll need to see an example page to be more helpful.

EDIT: The good doctor has already put the fullest explanation but the quick version is that the minimum is 0 because it can't be a negative number and the maximum - well, you'll never really need to go above 10 for most designs.

What are database normal forms and can you give examples?

1NF is the most basic of normal forms - each cell in a table must contain only one piece of information, and there can be no duplicate rows.

2NF and 3NF are all about being dependent on the primary key. Recall that a primary key can be made up of multiple columns. As Chris said in his response:

The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF] (so help me Codd).

2NF

Say you have a table containing courses that are taken in a certain semester, and you have the following data:

|-----Primary Key----|               uh oh |
                                           V
CourseID | SemesterID | #Places  | Course Name  |
------------------------------------------------|
IT101    |   2009-1   | 100      | Programming  |
IT101    |   2009-2   | 100      | Programming  |
IT102    |   2009-1   | 200      | Databases    |
IT102    |   2010-1   | 150      | Databases    |
IT103    |   2009-2   | 120      | Web Design   |

This is not in 2NF, because the fourth column does not rely upon the entire key - but only a part of it. The course name is dependent on the Course's ID, but has nothing to do with which semester it's taken in. Thus, as you can see, we have duplicate information - several rows telling us that IT101 is programming, and IT102 is Databases. So we fix that by moving the course name into another table, where CourseID is the ENTIRE key.

Primary Key |

CourseID    |  Course Name |
---------------------------|
IT101       | Programming  |
IT102       | Databases    |
IT103       | Web Design   |

No redundancy!

3NF

Okay, so let's say we also add the name of the teacher of the course, and some details about them, into the RDBMS:

|-----Primary Key----|                           uh oh |
                                                       V
Course  |  Semester  |  #Places   |  TeacherID  | TeacherName  |
---------------------------------------------------------------|
IT101   |   2009-1   |  100       |  332        |  Mr Jones    |
IT101   |   2009-2   |  100       |  332        |  Mr Jones    |
IT102   |   2009-1   |  200       |  495        |  Mr Bentley  |
IT102   |   2010-1   |  150       |  332        |  Mr Jones    |
IT103   |   2009-2   |  120       |  242        |  Mrs Smith   |

Now hopefully it should be obvious that TeacherName is dependent on TeacherID - so this is not in 3NF. To fix this, we do much the same as we did in 2NF - take the TeacherName field out of this table, and put it in its own, which has TeacherID as the key.

 Primary Key |

 TeacherID   | TeacherName  |
 ---------------------------|
 332         |  Mr Jones    |
 495         |  Mr Bentley  |
 242         |  Mrs Smith   |

No redundancy!!

One important thing to remember is that if something is not in 1NF, it is not in 2NF or 3NF either. So each additional Normal Form requires everything that the lower normal forms had, plus some extra conditions, which must all be fulfilled.

Redis command to get all available keys?

In order to get all the keys available in redis server, you should open redis-cli and type: KEYS * In order to get more help please visit this page: This Link

An error when I add a variable to a string

You're missing your database name:

$sql = "SELECT ID, ListStID, ListEmail, Title FROM ".$entry_database." WHERE ID = ". $ReqBookID .";

And make sure that $entry_database isn't null or empty:

var_dump($entry_database);

Also notice that you don't need to have $ReqBookID in '' as if it's an Int.

How do I negate a condition in PowerShell?

If you are like me and dislike the double parenthesis, you can use a function

function not ($cm, $pm) {
  if (& $cm $pm) {0} else {1}
}

if (not Test-Path C:\Code) {'it does not exist!'}

Example

Solving Quadratic Equation

# syntaxis:2.7
# solution for quadratic equation
# a*x**2 + b*x + c = 0

d = b**2-4*a*c # discriminant

if d < 0:
    print 'No solutions'
elif d == 0:
    x1 = -b / (2*a)
    print 'The sole solution is',x1
else: # if d > 0
    x1 = (-b + math.sqrt(d)) / (2*a)
    x2 = (-b - math.sqrt(d)) / (2*a)
    print 'Solutions are',x1,'and',x2

Python script header

Yes, there is - python may not be in /usr/bin, but for example in /usr/local/bin (BSD).

When using virtualenv, it may even be something like ~/projects/env/bin/python

What is the simplest C# function to parse a JSON string into an object?

DataContractJsonSerializer serializer = 
    new DataContractJsonSerializer(typeof(YourObjectType));

YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream);

You could also use the JavaScriptSerializer, but DataContractJsonSerializer is supposedly better able to handle complex types.

Oddly enough JavaScriptSerializer was once deprecated (in 3.5) and then resurrected because of ASP.NET MVC (in 3.5 SP1). That would definitely be enough to shake my confidence and lead me to use DataContractJsonSerializer since it is hard baked for WCF.

How to fill a datatable with List<T>

Just in case you have a nullable property in your class object:

private static DataTable ConvertToDatatable<T>(List<T> data)
{
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for (int i = 0; i < props.Count; i++)
    {
        PropertyDescriptor prop = props[i];
        if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]); 
        else
            table.Columns.Add(prop.Name, prop.PropertyType);
    }

    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;
 }

How to read an external local JSON file in JavaScript?

You can use d3.js to import JSON files. Just call d3 on your html body:

<script src="https://d3js.org/d3.v5.min.js"></script>

Then put this on your js scripts:

  d3.json("test.json").then(function(data_json) {
         //do your stuff
  })

Completely Remove MySQL Ubuntu 14.04 LTS

This is what saved me. Apparently the depackager tries to put things in the wrong tmp folder.

https://askubuntu.com/a/248860

Adding values to a C# array

This seems like a lot less trouble to me:

var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.ToArray();

Effects of the extern keyword on C functions

The extern keyword informs the compiler that the function or variable has external linkage - in other words, that it is visible from files other than the one in which it is defined. In this sense it has the opposite meaning to the static keyword. It is a bit weird to put extern at the time of the definition, since no other files would have visibility of the definition (or it would result in multiple definitions). Normally you put extern in a declaration at some point with external visibility (such as a header file) and put the definition elsewhere.

Can I convert a boolean to Yes/No in a ASP.NET GridView

You could use a Mixin.

/// <summary>
/// Adds "mixins" to the Boolean class.
/// </summary>
public static class BooleanMixins
{
    /// <summary>
    /// Converts the value of this instance to its equivalent string representation (either "Yes" or "No").
    /// </summary>
    /// <param name="boolean"></param>
    /// <returns>string</returns>
    public static string ToYesNoString(this Boolean boolean)
    {
        return boolean ? "Yes" : "No";
    }
}

How to delete columns in numpy.array

This creates another array without those columns:

  b = a.compress(logical_not(z), axis=1)

Writing String to Stream and reading it back does not work

You're using message.Length which returns the number of characters in the string, but you should be using the nubmer of bytes to read. You should use something like:

byte[] messageBytes = uniEncoding.GetBytes(message);
stringAsStream.Write(messageBytes, 0, messageBytes.Length);

You're then reading a single byte and expecting to get a character from it just by casting to char. UnicodeEncoding will use two bytes per character.

As Justin says you're also not seeking back to the beginning of the stream.

Basically I'm afraid pretty much everything is wrong here. Please give us the bigger picture and we can help you work out what you should really be doing. Using a StreamWriter to write and then a StreamReader to read is quite possibly what you want, but we can't really tell from just the brief bit of code you've shown.

Concatenating multiple text files into a single file in Bash

Be careful, because none of these methods work with a large number of files. Personally, I used this line:

for i in $(ls | grep ".txt");do cat $i >> output.txt;done

EDIT: As someone said in the comments, you can replace $(ls | grep ".txt") with $(ls *.txt)

EDIT: thanks to @gnourf_gnourf expertise, the use of glob is the correct way to iterate over files in a directory. Consequently, blasphemous expressions like $(ls | grep ".txt") must be replaced by *.txt (see the article here).

Good Solution

for i in *.txt;do cat $i >> output.txt;done

installing python packages without internet and using source code as .tar.gz and .whl

pipdeptree is a command line utility for displaying the python packages installed in an virtualenv in form of a dependency tree. Just use it: https://github.com/naiquevin/pipdeptree

How to convert a Java 8 Stream to an Array?

Using the toArray(IntFunction<A[]> generator) method is indeed a very elegant and safe way to convert (or more correctly, collect) a Stream into an array of the same type of the Stream.

However, if the returned array's type is not important, simply using the toArray() method is both easier and shorter. For example:

    Stream<Object> args = Stream.of(BigDecimal.ONE, "Two", 3);
    System.out.printf("%s, %s, %s!", args.toArray());

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

Your compile SDK version must match the support library. so do one of the following:

1.In your Build.gradle change

compile 'com.android.support:appcompat-v7:23.0.1'

2.Or change:

compileSdkVersion 23
buildToolsVersion "23.0.2"

to

compileSdkVersion 25
buildToolsVersion "25.0.2"

As you are using : compile 'com.android.support:appcompat-v7:25.3.1'

i would recommend to use the 2nd method as it is using the latest sdk - so you can able to utilize the new functionality of the latest sdk.

Latest Example of build.gradle with build tools 27.0.2 -- Source

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.2"
    defaultConfig {
        applicationId "your_applicationID"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.0.2'
    compile 'com.android.support:design:27.0.2'
    testCompile 'junit:junit:4.12'
}

If you face problem during updating the version like:

enter image description here

Go through this Answer for easy upgradation using Google Maven Repository

EDIT

if you are using Facebook Account Kit

don't use: compile 'com.facebook.android:account-kit-sdk:4.+'

instead use a specific version like:

compile 'com.facebook.android:account-kit-sdk:4.12.0'

there is a problem with the latest version in account kit with sdk 23

EDIT

For Facebook Android Sdk

in your build.gradle instead of:

compile 'com.facebook.android:facebook-android-sdk: 4.+'

use a specific version:

compile 'com.facebook.android:facebook-android-sdk:4.18.0'

there is a problem with the latest version in Facebook sdk with Android sdk version 23.

How to create a popup window (PopupWindow) in Android

Button endDataSendButton = (Button)findViewById(R.id.end_data_send_button);

Similarly you can get the text view by adding a id to it.

What's the difference between JavaScript and JScript?

Just different names for what is really ECMAScript. John Resig has a good explanation.

Here's the full version breakdown:

  • IE 6-7 support JScript 5 (which is equivalent to ECMAScript 3, JavaScript 1.5)
  • IE 8 supports JScript 6 (which is equivalent to ECMAScript 3, JavaScript 1.5 - more bug fixes over JScript 5)
  • Firefox 1.0 supports JavaScript 1.5 (ECMAScript 3 equivalent)
  • Firefox 1.5 supports JavaScript 1.6 (1.5 + Array Extras + E4X + misc.)
  • Firefox 2.0 supports JavaScript 1.7 (1.6 + Generator + Iterators + let + misc.)
  • Firefox 3.0 supports JavaScript 1.8 (1.7 + Generator Expressions + Expression Closures + misc.)
  • The next version of Firefox will support JavaScript 1.9 (1.8 + To be determined)
  • Opera supports a language that is equivalent to ECMAScript 3 + Getters and Setters + misc.
  • Safari supports a language that is equivalent to ECMAScript 3 + Getters and Setters + misc.

Can a table have two foreign keys?

Yes, a table have one or many foreign keys and each foreign keys hava a different parent table.

Convert Date/Time for given Timezone - java

We can get the UTC/GMT time stamp from the given date.

/**
 * Get the time stamp in GMT/UTC by passing the valid time (dd-MM-yyyy HH:mm:ss)
 */
public static long getGMTTimeStampFromDate(String datetime) {
    long timeStamp = 0;
    Date localTime = new Date();

    String format = "dd-MM-yyyy HH:mm:ss";
    SimpleDateFormat sdfLocalFormat = new SimpleDateFormat(format);
    sdfLocalFormat.setTimeZone(TimeZone.getDefault());

    try {

        localTime = (Date) sdfLocalFormat.parse(datetime); 

        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"),
                Locale.getDefault());
        TimeZone tz = cal.getTimeZone();

        cal.setTime(localTime);

        timeStamp = (localTime.getTime()/1000);
        Log.d("GMT TimeStamp: ", " Date TimegmtTime: " + datetime
                + ", GMT TimeStamp : " + localTime.getTime());

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return timeStamp;

}

It will return the UTC time based on passed date.

  • We can do reverse like UTC time stamp to current date and time(vice versa)

        public static String getLocalTimeFromGMT(long gmtTimeStamp) {
                 try{
                        Calendar calendar = Calendar.getInstance();
                        TimeZone tz = TimeZone.getDefault();
                        calendar.setTimeInMillis(gmtTimeStamp * 1000);
        //              calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis())); 
                        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                        Date currenTimeZone = (Date) calendar.getTime();
                        return sdf.format(currenTimeZone);
                    }catch (Exception e) {
                    }
                    return "";  
                }
    

I hope this will help others. Thanks!!

How to SSH to a VirtualBox guest externally through a host?

On secure networks setting your network to bridge might not work. Administrators could only allow one mac address per port or even worse block the port should the switches detect multiple macs on one port.

The best solution in my opinion is to set up additional network interfaces to handle additional services you would like to run on your machines. So I have a bridge interface to allow for bridging when I take my laptop home and can SSH into it from other devices on my network as well as a host only adapter when I would like to SSH into my VM from my laptop when I am connected to the eduroam wifi network on campus.

How to convert a set to a list in python?

Hmmm I bet that in some previous lines you have something like:

list = set(something)

Am I wrong ?

Delete forked repo from GitHub

Sweet and simple:

  1. Open the repository
  2. Navigate to settings
  3. Scroll to the bottom of the page
  4. Click on delete
  5. Confirm names of the Repository to delete
  6. Click on delete

Print an integer in binary format in Java

There are already good answers posted here for this question. But, this is the way I've tried myself (and might be the easiest logic based ? modulo/divide/add):

        int decimalOrBinary = 345;
        StringBuilder builder = new StringBuilder();

        do {
            builder.append(decimalOrBinary % 2);
            decimalOrBinary = decimalOrBinary / 2;
        } while (decimalOrBinary > 0);

        System.out.println(builder.reverse().toString()); //prints 101011001

How to check if string input is a number?

This solution will accept only integers and nothing but integers.

def is_number(s):
    while s.isdigit() == False:
        s = raw_input("Enter only numbers: ")
    return int(s)


# Your program starts here    
user_input = is_number(raw_input("Enter a number: "))

How to generate a random number in C++?

for random every RUN file

size_t randomGenerator(size_t min, size_t max) {
    std::mt19937 rng;
    rng.seed(std::random_device()());
    //rng.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
    std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);

    return dist(rng);
}

Sequel Pro Alternative for Windows

I use SQLYog at home and work. It turns out they DO have a free open-source version, though sadly they've been trying to hide that fact for the last few years.

You can download the open-source version from https://github.com/webyog/sqlyog-community - just click the "Download SQLyog Community Version" link.

initializing strings as null vs. empty string

I would prefere

if (!myStr.empty())
{
    //do something
}

Also you don't have to write std::string a = "";. You can just write std::string a; - it will be empty by default

How can I determine the URL that a local Git repository was originally cloned from?

#!/bin/bash

git-remote-url() {
 local rmt=$1; shift || { printf "Usage: git-remote-url [REMOTE]\n" >&2; return 1; }
 local url

 if ! git config --get remote.${rmt}.url &>/dev/null; then
  printf "%s\n" "Error: not a valid remote name" && return 1
  # Verify remote using 'git remote -v' command
 fi

 url=`git config --get remote.${rmt}.url`

 # Parse remote if local clone used SSH checkout
 [[ "$url" == git@* ]] \
 && { url="https://github.com/${url##*:}" >&2; }; \
 { url="${url%%.git}" >&2; };

 printf "%s\n" "$url"
}

Usage:

# Either launch a new terminal and copy `git-remote-url` into the current shell process, 
# or create a shell script and add it to the PATH to enable command invocation with bash.

# Create a local clone of your repo with SSH, or HTTPS
git clone [email protected]:your-username/your-repository.git
cd your-repository

git-remote-url origin

Output:

https://github.com/your-username/your-repository

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

How can I fill out a Python string with spaces?

You can try this:

print "'%-100s'" % 'hi'

How do I convert from a money datatype in SQL server?

Would casting it to int help you? Money is meant to have the decimal places...

DECLARE @test AS money
SET @test = 3
SELECT CAST(@test AS int), @test

error: unknown type name ‘bool’

C90 does not support the boolean data type.

C99 does include it with this include:

#include <stdbool.h>

What does 'foo' really mean?

foo is used as a place-holder name, usually in example code to signify that the object being named, or the choice of name, is not part of the crux of the example. foo is often followed by bar, baz, and even bundy, if more than one such name is needed. Wikipedia calls these names Metasyntactic Variables. Python programmers supposedly use spam, eggs, ham, instead of foo, etc.

There are good uses of foo in SA.

I have also seen foo used when the programmer can't think of a meaningful name (as a substitute for tmp, say), but I consider that to be a misuse of foo.

AddRange to a Collection

Remember that each Add will check the capacity of the collection and resize it whenever necessary (slower). With AddRange, the collection will be set the capacity and then added the items (faster). This extension method will be extremely slow, but will work.

how to create a logfile in php?

Please check with this documentation.

http://php.net/manual/en/function.error-log.php

Example:

<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
    error_log("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
    error_log("Big trouble, we're all out of FOOs!", 1,
               "[email protected]");
}

// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

According to the state machine diagram on the JSON website, only escaped double-quote characters are allowed, not single-quotes. Single quote characters do not need to be escaped:

http://www.json.org/string.gif


Update - More information for those that are interested:


Douglas Crockford does not specifically say why the JSON specification does not allow escaped single quotes within strings. However, during his discussion of JSON in Appendix E of JavaScript: The Good Parts, he writes:

JSON's design goals were to be minimal, portable, textual, and a subset of JavaScript. The less we need to agree on in order to interoperate, the more easily we can interoperate.

So perhaps he decided to only allow strings to be defined using double-quotes since this is one less rule that all JSON implementations must agree on. As a result, it is impossible for a single quote character within a string to accidentally terminate the string, because by definition a string can only be terminated by a double-quote character. Hence there is no need to allow escaping of a single quote character in the formal specification.


Digging a little bit deeper, Crockford's org.json implementation of JSON for Java is more permissible and does allow single quote characters:

The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more forgiving in the texts they will accept:

...

  • Strings may be quoted with ' (single quote).

This is confirmed by the JSONTokener source code. The nextString method accepts escaped single quote characters and treats them just like double-quote characters:

public String nextString(char quote) throws JSONException {
    char c;
    StringBuffer sb = new StringBuffer();
    for (;;) {
        c = next();
        switch (c) {

        ...

        case '\\':
            c = this.next();
            switch (c) {

            ...

            case '"':
            case '\'':
            case '\\':
            case '/':
                sb.append(c);
                break;
        ...

At the top of the method is an informative comment:

The formal JSON format does not allow strings in single quotes, but an implementation is allowed to accept them.

So some implementations will accept single quotes - but you should not rely on this. Many popular implementations are quite restrictive in this regard and will reject JSON that contains single quoted strings and/or escaped single quotes.


Finally to tie this back to the original question, jQuery.parseJSON first attempts to use the browser's native JSON parser or a loaded library such as json2.js where applicable (which on a side note is the library the jQuery logic is based on if JSON is not defined). Thus jQuery can only be as permissive as that underlying implementation:

parseJSON: function( data ) {
    ...

    // Attempt to parse using the native JSON parser first
    if ( window.JSON && window.JSON.parse ) {
        return window.JSON.parse( data );
    }

    ...

    jQuery.error( "Invalid JSON: " + data );
},

As far as I know these implementations only adhere to the official JSON specification and do not accept single quotes, hence neither does jQuery.

Git Push ERROR: Repository not found

That's what worked for me:

1. The Remotes

$ git remote rm origin
$ git remote add origin [email protected]:<USER>/<REPO>.git

If your SSH key is already in use on another github rep, you can generate a new one.

2. Generating a new SSH key

$ ssh-keygen -t rsa -b 4096 -C "[email protected]"

3. Addition of the key at the SSH agent level

$ eval "$(ssh-agent -s)"
$ ssh-add ~/.ssh/id_rsa_github

4. Add the new key to the Github repo.

How can I solve equations in Python?

There are two ways to approach this problem: numerically and symbolically.

To solve it numerically, you have to first encode it as a "runnable" function - stick a value in, get a value out. For example,

def my_function(x):
    return 2*x + 6

It is quite possible to parse a string to automatically create such a function; say you parse 2x + 6 into a list, [6, 2] (where the list index corresponds to the power of x - so 6*x^0 + 2*x^1). Then:

def makePoly(arr):
    def fn(x):
        return sum(c*x**p for p,c in enumerate(arr))
    return fn

my_func = makePoly([6, 2])
my_func(3)    # returns 12

You then need another function which repeatedly plugs an x-value into your function, looks at the difference between the result and what it wants to find, and tweaks its x-value to (hopefully) minimize the difference.

def dx(fn, x, delta=0.001):
    return (fn(x+delta) - fn(x))/delta

def solve(fn, value, x=0.5, maxtries=1000, maxerr=0.00001):
    for tries in xrange(maxtries):
        err = fn(x) - value
        if abs(err) < maxerr:
            return x
        slope = dx(fn, x)
        x -= err/slope
    raise ValueError('no solution found')

There are lots of potential problems here - finding a good starting x-value, assuming that the function actually has a solution (ie there are no real-valued answers to x^2 + 2 = 0), hitting the limits of computational accuracy, etc. But in this case, the error minimization function is suitable and we get a good result:

solve(my_func, 16)    # returns (x =) 5.000000000000496

Note that this solution is not absolutely, exactly correct. If you need it to be perfect, or if you want to try solving families of equations analytically, you have to turn to a more complicated beast: a symbolic solver.

A symbolic solver, like Mathematica or Maple, is an expert system with a lot of built-in rules ("knowledge") about algebra, calculus, etc; it "knows" that the derivative of sin is cos, that the derivative of kx^p is kpx^(p-1), and so on. When you give it an equation, it tries to find a path, a set of rule-applications, from where it is (the equation) to where you want to be (the simplest possible form of the equation, which is hopefully the solution).

Your example equation is quite simple; a symbolic solution might look like:

=> LHS([6, 2]) RHS([16])

# rule: pull all coefficients into LHS
LHS, RHS = [lh-rh for lh,rh in izip_longest(LHS, RHS, 0)], [0]

=> LHS([-10,2]) RHS([0])

# rule: solve first-degree poly
if RHS==[0] and len(LHS)==2:
    LHS, RHS = [0,1], [-LHS[0]/LHS[1]]

=> LHS([0,1]) RHS([5])

and there is your solution: x = 5.

I hope this gives the flavor of the idea; the details of implementation (finding a good, complete set of rules and deciding when each rule should be applied) can easily consume many man-years of effort.

How to set tbody height with overflow scroll

HTML:

<table id="uniquetable">
    <thead>
      <tr>
        <th> {{ field[0].key }} </th>
        <th> {{ field[1].key }} </th>
        <th> {{ field[2].key }} </th>
        <th> {{ field[3].key }} </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="obj in objects" v-bind:key="obj.id">
        <td> {{ obj.id }} </td>
        <td> {{ obj.name }} </td>
        <td> {{ obj.age }} </td>
        <td> {{ obj.gender }} </td>
      </tr>
    </tbody>
</table>

CSS:

#uniquetable thead{
    display:block;
    width: 100%;
}
#uniquetable tbody{
    display:block;
    width: 100%;
    height: 100px;
    overflow-y:overlay;
    overflow-x:hidden;
}
#uniquetable tbody tr,#uniquetable thead tr{
    width: 100%;
    display:table;
}
#uniquetable tbody tr td, #uniquetable thead tr th{
   display:table-cell;
   width:20% !important;
   overflow:hidden;
}

this will work as well:

#uniquetable tbody {
    width:inherit !important;
    display:block;
    max-height: 400px;
    overflow-y:overlay;
  }
  #uniquetable thead {
    width:inherit !important;
    display:block;
  }
  #uniquetable tbody tr, #uniquetable thead tr {
    display:inline-flex;
    width:100%;
  }
  #uniquetable tbody tr td,  #uniquetable thead tr th {
    display:block;
    width:20%;
    border-top:none;
    text-overflow: ellipsis;
    overflow: hidden;
    max-height:400px;
  }

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I would change the query in the following ways:

  1. Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the group by.
  2. Combine the second and third subqueries. They are aggregating on the same column. This requires using a left outer join to ensure that all data is available.
  3. By using count(<fieldname>) you can eliminate the comparisons to is null. This is important for the second and third calculated values.
  4. To combine the second and third queries, it needs to count an id from the mde table. These use mde.mdeid.

The following version follows your example by using union all:

SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
       SUM(TOTALMAILED) as TotalMailed,
       SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
       SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
              NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract
       where SentDate is not null
       group by SentDate
      ) union all
      (select MDE.ReturnMailDate AS ReceiptDate, 0,
              COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
              SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract MDE left outer join
            DTSharedData.dbo.ScanData SD
            ON SD.ScanDataID = MDE.ReturnScanDataID
       group by MDE.ReturnMailDate;
      )
     ) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;

The following does something similar using full outer join:

SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
       sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
       mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
      from MailDataExtract
      where SentDate is not null
      group by cast(SentDate as date)
     ) sd full outer join
    (select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
            COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
            SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
     from MailDataExtract MDE left outer join
          DTSharedData.dbo.ScanData SD
          ON SD.ScanDataID = MDE.ReturnScanDataID
     group by cast(MDE.ReturnMailDate as date)
    ) mde
    on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;

How to redirect DNS to different ports

Use SRV record. If you are using freenom go to cloudflare.com and connect your freenom server to cloudflare (freenom doesn't support srv records) use _minecraft as service tcp as protocol and your ip as target (you need "a" record to use your ip. I recommend not using your "Arboristal.com" domain as "a" record. If you use "Arboristal.com" as your "a" record hackers can go in your router settings and hack your network) priority - 0, weight - 0 and port - the port you want to use.(i know this because i was in the same situation) Do the same for any domain provider. (sorry if i made spell mistakes)

Property getters and setters

Setters/getters in Swift are quite different than ObjC. The property becomes a computed property which means it does not have a backing variable such as _x as it would in ObjC.

In the solution code below you can see the xTimesTwo does not store anything, but simply computes the result from x.

See Official docs on computed properties.

The functionality you want might also be Property Observers.

What you need is:

var x: Int

var xTimesTwo: Int {
    set {
       x = newValue / 2
    }
    get {
        return x * 2
    }
}

You can modify other properties within the setter/getters, which is what they are meant for.

How can I render Partial views in asp.net mvc 3?

Create your partial view something like:

@model YourModelType
<div>
  <!-- HTML to render your object -->
</div>

Then in your view use:

@Html.Partial("YourPartialViewName", Model)

If you do not want a strongly typed partial view remove the @model YourModelType from the top of the partial view and it will default to a dynamic type.

Update

The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/ in the path below.

@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)

Cannot execute RUN mkdir in a Dockerfile

You can also simply use

WORKDIR /var/www/app

It will automatically create the folders if they don't exist.

Then switch back to the directory you need to be in.

Set the location in iPhone Simulator

in iOS Simulator menu, go to Debug -> Location -> Custom Location. There you can set the latitude and longitude and test the app accordingly. This works with mapkit and also with CLLocationManager.

Compare two Timestamp in java

From : http://download.oracle.com/javase/6/docs/api/java/sql/Timestamp.html#compareTo(java.sql.Timestamp)

public int compareTo(Timestamp ts)

Compares this Timestamp object to the given Timestamp object. Parameters: ts - the Timestamp object to be compared to this Timestamp object Returns: the value 0 if the two Timestamp objects are equal; a value less than 0 if this Timestamp object is before the given argument; and a value greater than 0 if this Timestamp object is after the given argument. Since: 1.4

Get a list of all threads currently running in Java

In the java console, hit Ctrl-Break. It will list all threads plus some information about the heap. This won't give you access to the objects of course. But it can be very helpful for debugging anyway.

How do you run a script on login in *nix?

From wikipedia Bash

When Bash starts, it executes the commands in a variety of different scripts.

When Bash is invoked as an interactive login shell, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable.

When a login shell exits, Bash reads and executes commands from the file ~/.bash_logout, if it exists.

When an interactive shell that is not a login shell is started, Bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force Bash to read and execute commands from file instead of ~/.bashrc.

jQuery: If this HREF contains

It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.

You can, however, use jQuery:

  if ($(this).is('[href$=?]'))

You can also just look at the "href" value:

  if (/\?$/.test(this.href))

In Perl, how can I read an entire file into a string?

I would do it in the simplest way, so anyone can understand what happens, even if there are smarter ways:

my $text = "";
while (my $line = <FILE>) {
    $text .= $line;
}

Combine two (or more) PDF's

Here is a example using iTextSharp

public static void MergePdf(Stream outputPdfStream, IEnumerable<string> pdfFilePaths)
{
    using (var document = new Document())
    using (var pdfCopy = new PdfCopy(document, outputPdfStream))
    {
        pdfCopy.CloseStream = false;
        try
        {
            document.Open();
            foreach (var pdfFilePath in pdfFilePaths)
            {
                using (var pdfReader = new PdfReader(pdfFilePath))
                {
                    pdfCopy.AddDocument(pdfReader);
                    pdfReader.Close();
                }
            }
        }
        finally
        {
            document?.Close();
        }
    }
}

The PdfReader constructor has many overloads. It's possible to replace the parameter type IEnumerable<string> with IEnumerable<Stream> and it should work as well. Please notice that the method does not close the OutputStream, it delegates that task to the Stream creator.

Common xlabel/ylabel for matplotlib subplots

Update:

This feature is now part of the proplot matplotlib package that I recently released on pypi. By default, when you make figures, the labels are "shared" between axes.


Original answer:

I discovered a more robust method:

If you know the bottom and top kwargs that went into a GridSpec initialization, or you otherwise know the edges positions of your axes in Figure coordinates, you can also specify the ylabel position in Figure coordinates with some fancy "transform" magic. For example:

import matplotlib.transforms as mtransforms
bottom, top = .1, .9
f, a = plt.subplots(nrows=2, ncols=1, bottom=bottom, top=top)
avepos = (bottom+top)/2
a[0].yaxis.label.set_transform(mtransforms.blended_transform_factory(
       mtransforms.IdentityTransform(), f.transFigure # specify x, y transform
       )) # changed from default blend (IdentityTransform(), a[0].transAxes)
a[0].yaxis.label.set_position((0, avepos))
a[0].set_ylabel('Hello, world!')

...and you should see that the label still appropriately adjusts left-right to keep from overlapping with ticklabels, just like normal -- but now it will adjust to be always exactly between the desired subplots.

Furthermore, if you don't even use set_position, the ylabel will show up by default exactly halfway up the figure. I'm guessing this is because when the label is finally drawn, matplotlib uses 0.5 for the y-coordinate without checking whether the underlying coordinate transform has changed.

How do you add swap to an EC2 instance?

Try swapspace http://pqxx.org/development/swapspace/

Most distros have it packaged.

On EC2 you might want to change "swappath" to /mnt or high-iops disk.

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

I was not getting the error on 32-bit machines but was on 64-bit so I changed the target platform from x86 to Any CPU and it resolved the issue.

How do I automatically scroll to the bottom of a multiline text box?

It seems the interface has changed in .NET 4.0. There is the following method that achieves all of the above. As Tommy Engebretsen suggested, putting it in a TextChanged event handler makes it automatic.

textBox1.ScrollToEnd();

Deploying my application at the root in Tomcat

Adding on to @Rob Hruska's sol, this setting in server.xml inside section works:

<Context path="" docBase="gateway" reloadable="true" override="true"> </Context>

Note: override="true" might be required in some cases.

Add and Remove Views in Android Dynamically?

For Adding the Button

LinearLayout dynamicview = (LinearLayout)findViewById(R.id.buttonlayout);
LinearLayout.LayoutParams  lprams = new LinearLayout.LayoutParams(  LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);

Button btn = new Button(this);
btn.setId(count);
final int id_ = btn.getId();
btn.setText("Capture Image" + id_);
btn.setTextColor(Color.WHITE);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
dynamicview.addView(btn, lprams);
btn = ((Button) findViewById(id_));
btn.setOnClickListener(this);

For removing the button

ViewGroup layout = (ViewGroup) findViewById(R.id.buttonlayout);
View command = layout.findViewById(count);
layout.removeView(command);

C# Return Different Types?

Rick's solution is the 'best' way to go in most cases. Sometimes when that's not available you want to use object as base type. And you could use the method like this:

public object GetAnything()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = new Radio();

     return hello; // or computer or radio   
}

To use it, you will want to use the as operator, like this:

public void TestMethod()
{
    object anything = GetAnything();
    var hello = anything as Hello;
    var computer = anything as Computer;
    var radio = anything as Radio;

    if (hello != null)
    {
        // GetAnything() returned a hello
    }
    else if (computer != null)
    {
        // GetAnything() returned a computer
    }
    else if (radio != null)
    {
        // GetAnything() returned a radio
    }
    else
    {
        // GetAnything() returned... well anything :D
    }
}

In your case you want to call a method play. So this'd seem more appropriate:

interface IPlayable
{
    void Play();
}

class Radio : IPlayable
{
    public void Play() { /* Play radio */ }
}

class Hello : IPlayable
{
    public void Play() { /* Say hello */ }
}

class Computer : IPlayable
{
    public void Play() { /* beep beep */ }
}

public IPlayable GetAnything()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = new Radio();

     return hello; // or computer or radio   
}

Adding images to an HTML document with javascript

Get rid of the this statements too

var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = document.getElementById("gamediv");
src.appendChild(this.img)

How to handle the `onKeyPress` event in ReactJS?

var Test = React.createClass({
     add: function(event){
         if(event.key === 'Enter'){
            alert('Adding....');
         }
     },
     render: function(){
        return(
           <div>
            <input type="text" id="one" onKeyPress={(event) => this.add(event)}/>    
          </div>
        );
     }
});

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Let me add an example here:

I'm trying to build Alluxio on windows platform and got the same issue, it's because the pom.xml contains below step:

      <plugin>
        <artifactId>exec-maven-plugin</artifactId>
        <groupId>org.codehaus.mojo</groupId>
        <inherited>false</inherited>
        <executions>
          <execution>
            <id>Check that there are no Windows line endings</id>
            <phase>compile</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
            </configuration>
          </execution>
        </executions>
      </plugin>

The .sh file is not executable on windows so the error throws.

Comment it out if you do want build Alluxio on windows.

How do I align a number like this in C?

Looking this up in my handy Harbison & Steele....

Determine the maximum width of fields.

int max_width, value_to_print;
max_width = 8;
value_to_print = 1000;
printf("%*d\n", max_width, value_to_print);

Bear in mind that max_width must be of type int to work with the asterisk, and you'll have to calculate it based on how much space you're going to want to have. In your case, you'll have to calculate the maximum width of the largest number, and add 4.

How to deselect all selected rows in a DataGridView control?

i found out why my first row was default selected and found out how to not select it by default.

By default my datagridview was the object with the first tab-stop on my windows form. Making the tab stop first on another object (maybe disabling tabstop for the datagrid at all will work to) disabled selecting the first row

tap gesture recognizer - which object was tapped?

you can use

 - (void)highlightLetter:(UITapGestureRecognizer*)sender {
     UIView *view = sender.view; 
     NSLog(@"%d", view.tag); 
}

view will be the Object in which the tap gesture was recognised

Graphviz: How to go from .dot to a graph?

type: dot -Tps filename.dot -o outfile.ps

If you want to use the dot renderer. There are alternatives like neato and twopi. If graphiz isn't in your path, figure out where it is installed and run it from there.

You can change the output format by varying the value after -T and choosing an appropriate filename extension after -o.

If you're using windows, check out the installed tool called GVEdit, it makes the whole process slightly easier.

Go look at the graphviz site in the section called "User's Guides" for more detail on how to use the tools:

http://www.graphviz.org/documentation/

(See page 27 for output formatting for the dot command, for instance)

http://www.graphviz.org/pdf/dotguide.pdf

String split on new line, tab and some number of spaces

You can use this

string.strip().split(":")

In python, what is the difference between random.uniform() and random.random()?

The difference is in the arguments. It's very common to generate a random number from a uniform distribution in the range [0.0, 1.0), so random.random() just does this. Use random.uniform(a, b) to specify a different range.

Xml serialization - Hide null values

You can define some default values and it prevents the fields from being serialized.

    [XmlElement, DefaultValue("")]
    string data;

    [XmlArray, DefaultValue(null)]
    List<string> data;

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

Edit: isMounted is deprecated and will probably be removed in later versions of React. See this and this, isMounted is an Antipattern.


As the warning states, you are calling this.setState on an a component that was mounted but since then has been unmounted.

To make sure your code is safe, you can wrap it in

if (this.isMounted()) {
    this.setState({'time': remainTimeInfo});
}

to ensure that the component is still mounted.

How to generate a random string in Ruby

In ruby 1.9 one can use Array's choice method which returns random element from array

Difference between the System.Array.CopyTo() and System.Array.Clone()

As stated in many other answers both methods perform shallow copies of the array. However there are differences and recommendations that have not been addressed yet and that are highlighted in the following lists.

Characteristics of System.Array.Clone:

  • Tests, using .NET 4.0, show that it is slower than CopyTo probably because it uses Object.MemberwiseClone;
  • Requires casting the result to the appropriate type;
  • The resulting array has the same length as the source.

Characteristics of System.Array.CopyTo:

  • Is faster than Clone when copying to array of same type;
  • It calls into Array.Copy inheriting is capabilities, being the most useful ones:
    • Can box value type elements into reference type elements, for example, copying an int[] array into an object[];
    • Can unbox reference type elements into value type elements, for example, copying a object[] array of boxed int into an int[];
    • Can perform widening conversions on value types, for example, copying a int[] into a long[].
    • Can downcast elements, for example, copying a Stream[] array into a MemoryStream[] (if any element in source array is not convertible to MemoryStream an exception is thrown).
  • Allows to copy the source to a target array that has a length greater than the source.

Also note, these methods are made available to support ICloneable and ICollection, so if you are dealing with variables of array types you should not use Clone or CopyTo and instead use Array.Copy or Array.ConstrainedCopy. The constrained copy assures that if the copy operation cannot complete successful then the target array state is not corrupted.

Check if string has space in between (or anywhere)

If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:

string s = "Hello There";
bool fHasSpace = s.Contains(" ");

If you're looking for ways to detect whitespace, there's several great options below.

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

Put search icon near textbox using bootstrap

Here are three different ways to do it:

screenshot

Here's a working Demo in Fiddle Of All Three

Validation:

You can use native bootstrap validation states (No Custom CSS!):

<div class="form-group has-feedback">
    <label class="control-label" for="inputSuccess2">Name</label>
    <input type="text" class="form-control" id="inputSuccess2"/>
    <span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>

For a full discussion, see my answer to Add a Bootstrap Glyphicon to Input Box

Input Group:

You can use the .input-group class like this:

<div class="input-group">
    <input type="text" class="form-control"/>
    <span class="input-group-addon">
        <i class="fa fa-search"></i>
    </span>
</div>

For a full discussion, see my answer to adding Twitter Bootstrap icon to Input box

Unstyled Input Group:

You can still use .input-group for positioning but just override the default styling to make the two elements appear separate.

Use a normal input group but add the class input-group-unstyled:

<div class="input-group input-group-unstyled">
    <input type="text" class="form-control" />
    <span class="input-group-addon">
        <i class="fa fa-search"></i>
    </span>
</div>

Then change the styling with the following css:

.input-group.input-group-unstyled input.form-control {
    -webkit-border-radius: 4px;
       -moz-border-radius: 4px;
            border-radius: 4px;
}
.input-group-unstyled .input-group-addon {
    border-radius: 4px;
    border: 0px;
    background-color: transparent;
}

Also, these solutions work for any input size

Image style height and width not taken in outlook mails

Put the width and height in separate attributes, with no unit:

<img style="margin: 0; border: 0; padding: 0; display: block;"
src="images/img.jpg" width="120" height="150">

Another Option:

<!--[if gte mso 9]>
<style type="text/css">
img.header { width: 600px; } /* or something like that */
</style>
<![endif]-->

How Best to Compare Two Collections in Java and Act on Them?

I'd move to lists and solve it this way:

  1. Sort both lists by id ascending using custom Comparator if objects in lists aren't Comparable
  2. Iterate over elements in both lists like in merge phase in merge sort algorithm, but instead of merging lists, you check your logic.

The code would be more or less like this:

/* Main method */
private void execute(Collection<Foo> oldSet, Collection<Foo> newSet) {
  List<Foo> oldList = asSortedList(oldSet);
  List<Foo> newList = asSortedList(newSet);

  int oldIndex = 0;
  int newIndex = 0;
  // Iterate over both collections but not always in the same pace
  while( oldIndex < oldList.size() 
      && newIndex < newIndex.size())  {
    Foo oldObject = oldList.get(oldIndex);
    Foo newObject = newList.get(newIndex);

    // Your logic here
    if(oldObject.getId() < newObject.getId()) {
      doRemove(oldObject);
      oldIndex++;
    } else if( oldObject.getId() > newObject.getId() ) {
      doAdd(newObject);
      newIndex++;
    } else if( oldObject.getId() == newObject.getId() 
            && isModified(oldObject, newObject) ) {
      doUpdate(oldObject, newObject);
      oldIndex++;
      newIndex++;
    } else {
      ... 
    }
  }// while

  // Check if there are any objects left in *oldList* or *newList*

  for(; oldIndex < oldList.size(); oldIndex++ ) {
    doRemove( oldList.get(oldIndex) );  
  }// for( oldIndex )

  for(; newIndex < newList.size(); newIndex++ ) {
    doAdd( newList.get(newIndex) );
  }// for( newIndex ) 
}// execute( oldSet, newSet )

/** Create sorted list from collection 
    If you actually perform any actions on input collections than you should 
    always return new instance of list to keep algorithm simple.
*/
private List<Foo> asSortedList(Collection<Foo> data) {
  List<Foo> resultList;
  if(data instanceof List) {
     resultList = (List<Foo>)data;
  } else {
     resultList = new ArrayList<Foo>(data);
  }
  Collections.sort(resultList)
  return resultList;
}

adb command for getting ip address assigned by operator

For IP address- adb shell ifconfig under wlan0 Link encap:UNSPEC you will have your ip address written

How to convert Nonetype to int or string?

This can happen if you forget to return a value from a function: it then returns None. Look at all places where you are assigning to that variable, and see if one of them is a function call where the function lacks a return statement.

Can someone explain how to implement the jQuery File Upload plugin?

You can use uploadify this is the best multiupload jquery plugin i have used.

The implementation is easy, the browser support is perfect.

How to find GCD, LCM on a set of numbers

int lcmcal(int i,int y)
{
    int n,x,s=1,t=1;
    for(n=1;;n++)
    {
        s=i*n;
        for(x=1;t<s;x++)
        {
            t=y*x;
        }
        if(s==t)
            break;
    }
    return(s);
}

"git rm --cached x" vs "git reset head --? x"?

git rm --cached file will remove the file from the stage. That is, when you commit the file will be removed. git reset HEAD -- file will simply reset file in the staging area to the state where it was on the HEAD commit, i.e. will undo any changes you did to it since last commiting. If that change happens to be newly adding the file, then they will be equivalent.

Change default text in input type="file"?

Update 2017:

I have done research on how this could be achieved. And the best explanation/tutorial is here: https://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/

I'll write summary here just in case it becomes unavailable. So you should have HTML:

<input type="file" name="file" id="file" class="inputfile" />
<label for="file">Choose a file</label>

Then hide the input with CSS:

.inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;}

Then style the label:

.inputfile + label {
font-size: 1.25em;
font-weight: 700;
color: white;
background-color: black;
display: inline-block;
}

Then optionally you can add JS to display the name of the file:

var inputs = document.querySelectorAll( '.inputfile' );
Array.prototype.forEach.call( inputs, function( input )
{
var label    = input.nextElementSibling,
    labelVal = label.innerHTML;

input.addEventListener( 'change', function( e )
{
    var fileName = '';
    if( this.files && this.files.length > 1 )
        fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
    else
        fileName = e.target.value.split( '\\' ).pop();

    if( fileName )
        label.querySelector( 'span' ).innerHTML = fileName;
    else
        label.innerHTML = labelVal;
});
});

But really just read the tutorial and download the demo, it's really good.

Send JSON data from Javascript to PHP?

Javascript file using jQuery (cleaner but library overhead):

$.ajax({
    type: 'POST',
    url: 'process.php',
    data: {json: JSON.stringify(json_data)},
    dataType: 'json'
});

PHP file (process.php):

directions = json_decode($_POST['json']);
var_dump(directions);

Note that if you use callback functions in your javascript:

$.ajax({
    type: 'POST',
    url: 'process.php',
    data: {json: JSON.stringify(json_data)},
    dataType: 'json'
})
.done( function( data ) {
    console.log('done');
    console.log(data);
})
.fail( function( data ) {
    console.log('fail');
    console.log(data);
});

You must, in your PHP file, return a JSON object (in javascript formatting), in order to get a 'done/success' outcome in your Javascript code. At a minimum return/print:

print('{}');

See Ajax request return 200 OK but error event is fired instead of success

Although for anything a bit more serious you should be sending back a proper header explicitly with the appropriate response code.

Can't import database through phpmyadmin file size too large

  1. Set the below values in php.ini file (C:\xampp\php\)

    • max_execution_time = 0
    • max_input_time=259200
    • memory_limit = 1000M
    • upload_max_filesize = 750M
    • post_max_size = 750M
  2. Open config.default file(C:\xampp\phpMyAdmin\libraries\config.default) and set the value as below:

    • $cfg['ExecTimeLimit'] = 0;
  3. Then open the config.inc file(C:\xampp\phpMyAdmin\config.inc). and paste below line:

    • $cfg['UploadDir'] = 'upload';
  4. Go to phpMyAdmin(C:\xampp\phpMyAdmin) folder and create folder called upload and paste your database to newly created upload folder (don't need to zip)

  5. Lastly, go to phpMyAdmin and upload your db (Please select your database in drop-down)

upload image

  1. That's all baby ! :)

*It takes lot of time.In my db(266mb) takes 50min to upload. So be patient ! *

How to send emails from my Android application?

To JUST LET EMAIL APPS to resolve your intent you need to specify ACTION_SENDTO as Action and mailto as Data.

private void sendEmail(){

    Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
    emailIntent.setData(Uri.parse("mailto:" + "[email protected]")); 
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "My email's subject");
    emailIntent.putExtra(Intent.EXTRA_TEXT, "My email's body");

    try {
        startActivity(Intent.createChooser(emailIntent, "Send email using..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(Activity.this, "No email clients installed.", Toast.LENGTH_SHORT).show();
    }

}

Jquery function return value

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

function getMachine(color, qty) {
    var returnValue = null;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            returnValue = thisArray[3];
            return false; // this breaks out of the each
        }
    });
    return returnValue;
}

var retval = getMachine(color, qty);

How to center cell contents of a LaTeX table whose columns have fixed widths?

You can use \centering with your parbox to do this.

More info here and here.

(Sorry for the Google cached link; the original one I had doesn't work anymore.)

Finding the average of an array using JS

It can simply be done with a single reduce operation as follows;

_x000D_
_x000D_
var avg = [1,2,3,4].reduce((p,c,_,a) => p + c/a.length,0);_x000D_
console.log(avg)
_x000D_
_x000D_
_x000D_

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

For .Net 4 use:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

I personally use Visual Leak Detector, though it can cause large delays when large blocks are leaked (it displays the contents of the entire leaked block).

Unable to establish SSL connection, how do I fix my SSL cert?

In my case I had not enabled the site 'default-ssl'. Only '000-default' was listed in the /etc/apache2/sites-enabled folder.

Enable SSL site on Ubuntu 14 LTS, Apache 2.4.7:

a2ensite default-ssl
service apache2 reload

How to check for DLL dependency?

Please refer SysInternal toolkit from Microsoft from below link, https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer

Goto the download folder, Open "Procexp64.exe" as admin privilege. Open Find Menu-> "Find Handle or DLL" option or Ctrl+F shortcut way.

enter image description here

Check if value exists in enum in TypeScript

According to sandersn the best way to do this would be:

Object.values(MESSAGE_TYPE).includes(type as MESSAGE_TYPE)

Flatten list of lists

>>> lis=[[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> [x[0] for x in lis]
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]

How to remove default chrome style for select Input?

When looking at an input with a type of number, you'll notice the spinner buttons (up/down) on the right-hand side of the input field. These spinners aren't always desirable, thus the code below removes such styling to render an input that resembles that of an input with a type of text.

enter image description here

input[type=number]::-webkit-inner-spin-button, 
input[type=number]::-webkit-outer-spin-button { 
  -webkit-appearance: none; 
}

Java File - Open A File And Write To It

Please Search Google given to the world by Larry Page and Sergey Brin.

BufferedWriter out = null;

try {
    FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
    out = new BufferedWriter(fstream);
    out.write("\nsue");
}

catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

finally {
    if(out != null) {
        out.close();
    }
}

Why is division in Ruby returning an integer instead of decimal value?

Change the 5 to 5.0. You're getting integer division.

How do you detect the clearing of a "search" HTML5 input?

Here's one way of achieving this. You need to add incremental attribute to your html or it won't work.

_x000D_
_x000D_
window.onload = function() {_x000D_
  var tf = document.getElementById('textField');_x000D_
  var button = document.getElementById('b');_x000D_
  button.disabled = true;_x000D_
  var onKeyChange = function textChange() {_x000D_
    button.disabled = (tf.value === "") ? true : false;_x000D_
  }_x000D_
  tf.addEventListener('keyup', onKeyChange);_x000D_
  tf.addEventListener('search', onKeyChange);_x000D_
_x000D_
}
_x000D_
<input id="textField" type="search" placeholder="search" incremental="incremental">_x000D_
<button id="b">Go!</button>
_x000D_
_x000D_
_x000D_

Pyspark: Exception: Java gateway process exited before sending the driver its port number

If you are trying to run spark without hadoop binaries, you might encounter the above mentioned error. One solution is to :

1) download hadoop separatedly.
2) add hadoop to your PATH
3) add hadoop classpath to your SPARK install

The first two steps are trivial, the last step can be best done by adding the following in the $SPARK_HOME/conf/spark-env.sh in each spark node (master and workers)

### in conf/spark-env.sh ###

export SPARK_DIST_CLASSPATH=$(hadoop classpath)

for more info also check: https://spark.apache.org/docs/latest/hadoop-provided.html

Convert IEnumerable to DataTable

There is nothing built in afaik, but building it yourself should be easy. I would do as you suggest and use reflection to obtain the properties and use them to create the columns of the table. Then I would step through each item in the IEnumerable and create a row for each. The only caveat is if your collection contains items of several types (say Person and Animal) then they may not have the same properties. But if you need to check for it depends on your use.

C++ passing an array pointer as a function argument

int *a[], when used as a function parameter (but not in normal declarations), is a pointer to a pointer, not a pointer to an array (in normal declarations, it is an array of pointers). A pointer to an array looks like this:

int (*aptr)[N]

Where N is a particular positive integer (not a variable).

If you make your function a template, you can do it and you don't even need to pass the size of the array (because it is automatically deduced):

template<size_t SZ>
void generateArray(int (*aptr)[SZ])
{
    for (size_t i=0; i<SZ; ++i)
        (*aptr)[i] = rand() % 9;
}

int main()
{    
    int a[5];    
    generateArray(&a);
}

You could also take a reference:

template<size_t SZ>
void generateArray(int (&arr)[SZ])
{
    for (size_t i=0; i<SZ; ++i)
        arr[i] = rand() % 9;
}

int main()
{    
    int a[5];    
    generateArray(a);
}

Adding n hours to a date in Java?

You can do it with Joda DateTime API

DateTime date= new DateTime(dateObj);
date = date.plusHours(1);
dateObj = date.toDate();

How do I obtain crash-data from my Android application?

For sample applications and debugging purposes, I use a simple solution that allows me to write the stacktrace to the sd card of the device and/or upload it to a server. This solution has been inspired by Project android-remote-stacktrace (specifically, the save-to-device and upload-to-server parts) and I think it solves the problem mentioned by Soonil. It's not optimal, but it works and you can improve it if you want to use it in a production application. If you decide to upload the stacktraces to the server, you can use a php script (index.php) to view them. If you're interested, you can find all the sources below - one java class for your application and two optional php scrips for the server hosting the uploaded stacktraces.

In a Context (e.g. the main Activity), call

if(!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) {
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
            "/sdcard/<desired_local_path>", "http://<desired_url>/upload.php"));
}

CustomExceptionHandler

public class CustomExceptionHandler implements UncaughtExceptionHandler {

    private UncaughtExceptionHandler defaultUEH;

    private String localPath;

    private String url;

    /* 
     * if any of the parameters is null, the respective functionality 
     * will not be used 
     */
    public CustomExceptionHandler(String localPath, String url) {
        this.localPath = localPath;
        this.url = url;
        this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    }

    public void uncaughtException(Thread t, Throwable e) {
        String timestamp = TimestampFormatter.getInstance().getTimestamp();
        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        e.printStackTrace(printWriter);
        String stacktrace = result.toString();
        printWriter.close();
        String filename = timestamp + ".stacktrace";

        if (localPath != null) {
            writeToFile(stacktrace, filename);
        }
        if (url != null) {
            sendToServer(stacktrace, filename);
        }

        defaultUEH.uncaughtException(t, e);
    }

    private void writeToFile(String stacktrace, String filename) {
        try {
            BufferedWriter bos = new BufferedWriter(new FileWriter(
                    localPath + "/" + filename));
            bos.write(stacktrace);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendToServer(String stacktrace, String filename) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("filename", filename));
        nvps.add(new BasicNameValuePair("stacktrace", stacktrace));
        try {
            httpPost.setEntity(
                    new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

upload.php

<?php
    $filename = isset($_POST['filename']) ? $_POST['filename'] : "";
    $message = isset($_POST['stacktrace']) ? $_POST['stacktrace'] : "";
    if (!ereg('^[-a-zA-Z0-9_. ]+$', $filename) || $message == ""){
        die("This script is used to log debug data. Please send the "
                . "logging message and a filename as POST variables.");
    }
    file_put_contents($filename, $message . "\n", FILE_APPEND);
?>

index.php

<?php
    $myDirectory = opendir(".");
    while($entryName = readdir($myDirectory)) {
        $dirArray[] = $entryName;
    }
    closedir($myDirectory);
    $indexCount = count($dirArray);
    sort($dirArray);
    print("<TABLE border=1 cellpadding=5 cellspacing=0 \n");
    print("<TR><TH>Filename</TH><TH>Filetype</th><th>Filesize</TH></TR>\n");
    for($index=0; $index < $indexCount; $index++) {
        if ((substr("$dirArray[$index]", 0, 1) != ".") 
                && (strrpos("$dirArray[$index]", ".stacktrace") != false)){ 
            print("<TR><TD>");
            print("<a href=\"$dirArray[$index]\">$dirArray[$index]</a>");
            print("</TD><TD>");
            print(filetype($dirArray[$index]));
            print("</TD><TD>");
            print(filesize($dirArray[$index]));
            print("</TD></TR>\n");
        }
    }
    print("</TABLE>\n");
?>

PHP reindex array?

$myarray = array_values($myarray);

array_values

'NOT LIKE' in an SQL query

You need to specify the column in both expressions.

SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'

python tuple to dict

Try:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}

How to escape single quotes within single quoted strings

If you're generating the shell string within Python 2 or Python 3, the following may help to quote the arguments:

#!/usr/bin/env python

from __future__ import print_function

try:  # py3
    from shlex import quote as shlex_quote
except ImportError:  # py2
    from pipes import quote as shlex_quote

s = """foo ain't "bad" so there!"""

print(s)
print(" ".join([shlex_quote(t) for t in s.split()]))

This will output:

foo ain't "bad" so there!
foo 'ain'"'"'t' '"bad"' so 'there!'

Tar archiving that takes input from a list of files

Yes:

tar -cvf allfiles.tar -T mylist.txt

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

Woks fine for me on ubuntu 16.04. path: /etc/mysql/mysql.cnf

and paste that

[mysqld]
#
# * Basic Settings
#
sql_mode = "NO_ENGINE_SUBSTITUTION"

How to comment out particular lines in a shell script

You have to rely on '#' but to make the task easier in vi you can perform the following (press escape first):

:10,20 s/^/#

with 10 and 20 being the start and end line numbers of the lines you want to comment out

and to undo when you are complete:

:10,20 s/^#//

Angular - "has no exported member 'Observable'"

Try this:

npm install rxjs-compat --save

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.

Format datetime in asp.net mvc 4

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.

My finally working solution:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

You have to include before:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:

Install-Package Moment.js

Import module from subfolder

There's no need to mess with your PYTHONPATH or sys.path here.

To properly use absolute imports in a package you should include the "root" packagename as well, e.g.:

from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2

Or you can use relative imports:

from .dirfoo1.foo1 import Foo1
from .dirfoo2.foo2 import Foo2

Extension gd is missing from your system - laravel composer Update

Open your php.ini and uncomment this line:

;extension=php_gd2.dll

How to exit from the application and show the home screen?

There is another option, to use the FinishAffinity method to close all the tasks in the stack related to the app.

See: https://stackoverflow.com/a/27765687/1984636

Good ways to manage a changelog using git?

Since creating a tag per version is the best practice, you may want to partition your changelog per version. In that case, this command could help you:

git log YOUR_LAST_VERSION_TAG..HEAD --no-merges --format=%B

Angularjs how to upload multipart form data and a file?

You can check out this method for sending image and form data altogether

<div class="form-group ml-5 mt-4" ng-app="myApp" ng-controller="myCtrl">
                    <label for="image_name">Image Name:</label>
                    <input type="text"   placeholder="Image name" ng-model="fileName" class="form-control" required>
                    <br>

                    <br>
                    <input id="file_src" type="file"   accept="image/jpeg" file-input="files"   >
                    <br>
                        {{file_name}}
            <img class="rounded mt-2 mb-2 " id="prvw_img" width="150" height="100" >
                    <hr>
                      <button class="btn btn-info" ng-click="uploadFile()">Upload</button>
                        <br>

                       <div ng-show = "IsVisible" class="alert alert-info w-100 shadow mt-2" role="alert">
              <strong> {{response_msg}} </strong>
            </div>
                            <div class="alert alert-danger " id="filealert"> <strong> File Size should be less than 4 MB </strong></div>
                    </div>

Angular JS Code

    var app = angular.module("myApp", []);
 app.directive("fileInput", function($parse){
      return{
           link: function($scope, element, attrs){
                element.on("change", function(event){
                     var files = event.target.files;


                     $parse(attrs.fileInput).assign($scope, element[0].files);
                     $scope.$apply();
                });
           }
      }
 });
 app.controller("myCtrl", function($scope, $http){
      $scope.IsVisible = false;
      $scope.uploadFile = function(){
           var form_data = new FormData();
           angular.forEach($scope.files, function(file){
                form_data.append('file', file); //form file
                                form_data.append('file_Name',$scope.fileName); //form text data
           });
           $http.post('upload.php', form_data,
           {
                //'file_Name':$scope.file_name;
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined,'Process-Data': false}
           }).success(function(response){
             $scope.IsVisible = $scope.IsVisible = true;
                      $scope.response_msg=response;
               // alert(response);
               // $scope.select();
           });
      }

 });

Getting Lat/Lng from Google marker

You could just call getPosition() on the Marker - have you tried that?

If you're on the deprecated, v2 of the JavaScript API, you can call getLatLng() on GMarker.

Conditional formatting using AND() function

This is probably because of the column() and row() functions. I am not sure how they are applied in conditional formatting. Try creating a new column with the value from this formula and then use it for your formatting needs.

How to filter empty or NULL names in a QuerySet?

From Django 1.8,

from django.db.models.functions import Length

Name.objects.annotate(alias_length=Length('alias')).filter(alias_length__gt=0)

Fake "click" to activate an onclick method

For IE there is fireEvent() method. Don't know if that works for other browsers.

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Gotcha!

You have to use RegisterStartupScript instead of RegisterClientScriptBlock

Here My Example.

MasterPage:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
    Inherits="prueba.MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">

        function confirmCallBack() {
            var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');

            alert(a.value);

        }

    </script>

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

WebForm1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace prueba
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);

        }
    }
}

dynamically add and remove view to viewpager

After figuring out which ViewPager methods are called by ViewPager and which are for other purposes, I came up with a solution. I present it here since I see a lot of people have struggled with this and I didn't see any other relevant answers.

First, here's my adapter; hopefully comments within the code are sufficient:

public class MainPagerAdapter extends PagerAdapter
{
  // This holds all the currently displayable views, in order from left to right.
  private ArrayList<View> views = new ArrayList<View>();

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  "Object" represents the page; tell the ViewPager where the
  // page should be displayed, from left-to-right.  If the page no longer exists,
  // return POSITION_NONE.
  @Override
  public int getItemPosition (Object object)
  {
    int index = views.indexOf (object);
    if (index == -1)
      return POSITION_NONE;
    else
      return index;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager needs a page to display; it is our job
  // to add the page to the container, which is normally the ViewPager itself.  Since
  // all our pages are persistent, we simply retrieve it from our "views" ArrayList.
  @Override
  public Object instantiateItem (ViewGroup container, int position)
  {
    View v = views.get (position);
    container.addView (v);
    return v;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager no longer needs a page to display; it
  // is our job to remove the page from the container, which is normally the
  // ViewPager itself.  Since all our pages are persistent, we do nothing to the
  // contents of our "views" ArrayList.
  @Override
  public void destroyItem (ViewGroup container, int position, Object object)
  {
    container.removeView (views.get (position));
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager; can be used by app as well.
  // Returns the total number of pages that the ViewPage can display.  This must
  // never be 0.
  @Override
  public int getCount ()
  {
    return views.size();
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.
  @Override
  public boolean isViewFromObject (View view, Object object)
  {
    return view == object;
  }

  //-----------------------------------------------------------------------------
  // Add "view" to right end of "views".
  // Returns the position of the new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v)
  {
    return addView (v, views.size());
  }

  //-----------------------------------------------------------------------------
  // Add "view" at "position" to "views".
  // Returns position of new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v, int position)
  {
    views.add (position, v);
    return position;
  }

  //-----------------------------------------------------------------------------
  // Removes "view" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, View v)
  {
    return removeView (pager, views.indexOf (v));
  }

  //-----------------------------------------------------------------------------
  // Removes the "view" at "position" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, int position)
  {
    // ViewPager doesn't have a delete method; the closest is to set the adapter
    // again.  When doing so, it deletes all its views.  Then we can delete the view
    // from from the adapter and finally set the adapter to the pager again.  Note
    // that we set the adapter to null before removing the view from "views" - that's
    // because while ViewPager deletes all its views, it will call destroyItem which
    // will in turn cause a null pointer ref.
    pager.setAdapter (null);
    views.remove (position);
    pager.setAdapter (this);

    return position;
  }

  //-----------------------------------------------------------------------------
  // Returns the "view" at "position".
  // The app should call this to retrieve a view; not used by ViewPager.
  public View getView (int position)
  {
    return views.get (position);
  }

  // Other relevant methods:

  // finishUpdate - called by the ViewPager - we don't care about what pages the
  // pager is displaying so we don't use this method.
}

And here's some snips of code showing how to use the adapter.

class MainActivity extends Activity
{
  private ViewPager pager = null;
  private MainPagerAdapter pagerAdapter = null;

  //-----------------------------------------------------------------------------
  @Override
  public void onCreate (Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView (R.layout.main_activity);

    ... do other initialization, such as create an ActionBar ...

    pagerAdapter = new MainPagerAdapter();
    pager = (ViewPager) findViewById (R.id.view_pager);
    pager.setAdapter (pagerAdapter);

    // Create an initial view to display; must be a subclass of FrameLayout.
    LayoutInflater inflater = context.getLayoutInflater();
    FrameLayout v0 = (FrameLayout) inflater.inflate (R.layout.one_of_my_page_layouts, null);
    pagerAdapter.addView (v0, 0);
    pagerAdapter.notifyDataSetChanged();
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to add a view to the ViewPager.
  public void addView (View newPage)
  {
    int pageIndex = pagerAdapter.addView (newPage);
    // You might want to make "newPage" the currently displayed page:
    pager.setCurrentItem (pageIndex, true);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to remove a view from the ViewPager.
  public void removeView (View defunctPage)
  {
    int pageIndex = pagerAdapter.removeView (pager, defunctPage);
    // You might want to choose what page to display, if the current page was "defunctPage".
    if (pageIndex == pagerAdapter.getCount())
      pageIndex--;
    pager.setCurrentItem (pageIndex);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to get the currently displayed page.
  public View getCurrentPage ()
  {
    return pagerAdapter.getView (pager.getCurrentItem());
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to set the currently displayed page.  "pageToShow" must
  // currently be in the adapter, or this will crash.
  public void setCurrentPage (View pageToShow)
  {
    pager.setCurrentItem (pagerAdapter.getItemPosition (pageToShow), true);
  }
}

Finally, you can use the following for your activity_main.xml layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</android.support.v4.view.ViewPager>

How to fix Invalid AES key length?

I was facing the same issue then i made my key 16 byte and it's working properly now. Create your key exactly 16 byte. It will surely work.

Get attribute name value of <input>

A better way could be using 'this', it takes whatever the name of the 'id' is and uses that. As long as you add the class name called 'mytarget'.

Whenever any of the fields that have target change then it will show an alert box with the name of that field. Just cut and past whole script for it to work!

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
 $('.mytarget').change(function() {
var name1 = $(this).attr("name");
alert(name1);
 });
});
</script>

Name: <input type="text" name="myname" id="myname" class="mytarget"><br />
Age: <input type="text" name="myage" id="myage" class="mytarget"><br />

moment.js, how to get day of week number

You can get this in 2 way using moment and also using Javascript

_x000D_
_x000D_
const date = moment("2015-07-02"); // Thursday Feb 2015_x000D_
const usingMoment_1 = date.day();_x000D_
const usingMoment_2 = date.isoWeekday();_x000D_
_x000D_
console.log('usingMoment: date.day() ==> ',usingMoment_1);_x000D_
console.log('usingMoment: date.isoWeekday() ==> ',usingMoment_2);_x000D_
_x000D_
_x000D_
const usingJS= new Date("2015-07-02").getDay();_x000D_
console.log('usingJavaSript: new Date("2015-07-02").getDay() ===> ',usingJS);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Insert Data Into Temp Table with Query

use as at end of query

Select * into #temp (select * from table1,table2) as temp_table

How do I get current URL in Selenium Webdriver 2 Python?

Another way to do it would be to inspect the url bar in chrome to find the id of the element, have your WebDriver click that element, and then send the keys you use to copy and paste using the keys common function from selenium, and then printing it out or storing it as a variable, etc.

TSQL How do you output PRINT in a user defined function?

You can try returning the variable you wish to inspect. E.g. I have this function:

--Contencates seperate date and time strings and converts to a datetime. Date should be in format 25.03.2012. Time as 9:18:25.
ALTER FUNCTION [dbo].[ufn_GetDateTime] (@date nvarchar(11), @time nvarchar(11))
RETURNS datetime
AS
BEGIN

        --select dbo.ufn_GetDateTime('25.03.2012.', '9:18:25')

    declare @datetime datetime

    declare @day_part nvarchar(3)
    declare @month_part nvarchar(3)
    declare @year_part nvarchar(5)

    declare @point_ix int

    set @point_ix = charindex('.', @date)
    set @day_part = substring(@date, 0, @point_ix)

    set @date = substring(@date, @point_ix, len(@date) - @point_ix)
    set @point_ix = charindex('.', @date)

    set @month_part = substring(@date, 0, @point_ix)

    set @date = substring(@date, @point_ix, len(@date) - @point_ix)
    set @point_ix = charindex('.', @date)

    set @year_part = substring(@date, 0, @point_ix)

    set @datetime = @month_part + @day_part  + @year_part + ' ' + @time

    return @datetime
END

When I run it.. I get: Msg 241, Level 16, State 1, Line 1 Conversion failed when converting date and/or time from character string.

Arghh!!

So, what do I do?

ALTER FUNCTION [dbo].[ufn_GetDateTime] (@date nvarchar(11), @time nvarchar(11))
RETURNS nvarchar(22)
AS
BEGIN

        --select dbo.ufn_GetDateTime('25.03.2012.', '9:18:25')

    declare @day_part nvarchar(3)
    declare @point_ix int

    set @point_ix = charindex('.', @date)
    set @day_part = substring(@date, 0, @point_ix)

    return @day_part
END

And I get '25'. So, I am off by one and so I change to..

set @day_part = substring(@date, 0, @point_ix + 1)

Voila! Now it works :)

Calling a phone number in swift

Swift 3, iOS 10

func call(phoneNumber:String) {
        let cleanPhoneNumber = phoneNumber.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
        let urlString:String = "tel://\(cleanPhoneNumber)"
        if let phoneCallURL = URL(string: urlString) {
            if (UIApplication.shared.canOpenURL(phoneCallURL)) {
                UIApplication.shared.open(phoneCallURL, options: [:], completionHandler: nil)
            }
        }
  }

How do I commit case-sensitive only filename changes in Git?

You can use git mv:

git mv -f OldFileNameCase newfilenamecase

How to reload apache configuration for a site without restarting apache?

Late answer here, but if you search /etc/init.d/apache2 for 'reload', you'll find something like this:

do_reload() {
        if apache_conftest; then
                if ! pidofproc -p $PIDFILE "$DAEMON" > /dev/null 2>&1 ; then
                        APACHE2_INIT_MESSAGE="Apache2 is not running"
                        return 2
                fi
                $APACHE2CTL graceful > /dev/null 2>&1
                return $?
        else
                APACHE2_INIT_MESSAGE="The apache2$DIR_SUFFIX configtest failed. Not doing anything."
                return 2
        fi
}

Basically, what the answers that suggest using init.d, systemctl, etc are invoking is a thin wrapper that says:

  • check the apache config
  • if it's good, run apachectl graceful (swallowing the output, and forwarding the exit code)

This suggests that @Aruman's answer is also correct, provided you are confident there are no errors in your configuration or have already run apachctl configtest manually.

The apache documentation also supplies the same command for a graceful restart (apachectl -k graceful), and some more color on the behavior thereof.

Get Maven artifact version at runtime

To follow up the answer above, for a .war artifact, I found I had to apply the equivalent configuration to maven-war-plugin, rather than maven-jar-plugin:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.1</version>
    <configuration>
        <archive>                   
            <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
            </manifest>
        </archive>
    </configuration>
</plugin>

This added the version information to MANIFEST.MF in the project's .jar (included in WEB-INF/lib of the .war)

Passing an array of parameters to a stored procedure

You could try this:



DECLARE @List VARCHAR(MAX)

SELECT @List = '1,2,3,4,5,6,7,8'

EXEC(
'DELETE
FROM TABLE
WHERE ID NOT IN (' + @List + ')'
)

How to import image (.svg, .png ) in a React Component

There are few steps if we dont use "create-react-app",([email protected]) first we should install file-loader as devDedepencie,next step is to add rule in webpack.config

_x000D_
_x000D_
{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
}
_x000D_
_x000D_
_x000D_

, then in our src directory we should make file called declarationFiles.d.ts(for example) and register modules inside

_x000D_
_x000D_
declare module '*.jpg';
declare module '*.png';
_x000D_
_x000D_
_x000D_

,then restart dev-server. After these steps we can import and use images like in code bellow

_x000D_
_x000D_
import React from 'react';
import image from './img1.png';
import './helloWorld.scss';

const HelloWorld = () => (
  <>
    <h1 className="main">React TypeScript Starter</h1>
        <img src={image} alt="some example image" />
  </>
);
export default HelloWorld;
_x000D_
_x000D_
_x000D_

Works in typescript and also in javacript,just change extension from .ts to .js

Cheers.

keycloak Invalid parameter: redirect_uri

Check that the value of the redirect_uri parameter is whitelisted for the client that you are using. You can manage the configuration of the client via the admin console.

The redirect uri should match exactly with one of the whitelisted redirect uri's, or you can use a wildcard at the end of the uri you want to whitelist. See: https://www.keycloak.org/docs/latest/server_admin/#_clients

Note that using wildcards to whitelist redirect uri's is allowed by Keycloak, but is actually a violation of the OpenId Connect specification. See the discussion on this at https://lists.jboss.org/pipermail/keycloak-dev/2018-December/011440.html

Git: Merge a Remote branch locally

Maybe you want to track the remote branch with a local branch:

  1. Create a new local branch: git branch new-local-branch
  2. Set this newly created branch to track the remote branch: git branch --set-upstream-to=origin/remote-branch new-local-branch
  3. Enter into this branch: git checkout new-local-branch
  4. Pull all the contents of the remote branch into the local branch: git pull

How to add 10 days to current time in Rails

days, years, etc., are part of Active Support, So this won't work in irb, but it should work in rails console.

How to setup Tomcat server in Netbeans?

In Netbeans 8 you may have to install the Tomcat plugin manually. After you download and extract Tomcat follow these steps:

  1. Tools -> Plugins -> Available plugins, search for 'tomcat' and install the one named "Java EE Base plugin".
  2. Restart Netbeans
  3. On the project view (default left side of the screen), go to services, right click on Servers and then "Add Server"
  4. Select Apache Tomcat, enter username and password and config the rest and finish

How to select rows from a DataFrame based on column values

You can also use .apply:

df.apply(lambda row: row[df['B'].isin(['one','three'])])

It actually works row-wise (i.e., applies the function to each row).

The output is

   A      B  C   D
0  foo    one  0   0
1  bar    one  1   2
3  bar  three  3   6
6  foo    one  6  12
7  foo  three  7  14

The results is the same as using as mentioned by @unutbu

df[[df['B'].isin(['one','three'])]]

SQL injection that gets around mysql_real_escape_string()

Consider the following query:

$iId = mysql_real_escape_string("1 OR 1=1");    
$sSql = "SELECT * FROM table WHERE id = $iId";

mysql_real_escape_string() will not protect you against this. The fact that you use single quotes (' ') around your variables inside your query is what protects you against this. The following is also an option:

$iId = (int)"1 OR 1=1";
$sSql = "SELECT * FROM table WHERE id = $iId";

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

This answer is an update, circa November 2019. None of the popular pip installs will give you a working setup on MacOS 10.13 (and likely other versions as well). Here is a simple way that I got things working:

brew install mysql
pip install mysqlclient

If you need help installing brew, see this site: https://brew.sh/

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

You can get rid of the first line. You don't need import java.lang.*;

Just change your 5th line to:

public static void main(String [] args) throws Exception

AngularJS + JQuery : How to get dynamic content working in angularjs

Addition to @jwize's answer

Because angular.element(document).injector() was giving error injector is not defined So, I have created function that you can run after AJAX call or when DOM is changed using jQuery.

  function compileAngularElement( elSelector) {

        var elSelector = (typeof elSelector == 'string') ? elSelector : null ;  
            // The new element to be added
        if (elSelector != null ) {
            var $div = $( elSelector );

                // The parent of the new element
                var $target = $("[ng-app]");

              angular.element($target).injector().invoke(['$compile', function ($compile) {
                        var $scope = angular.element($target).scope();
                        $compile($div)($scope);
                        // Finally, refresh the watch expressions in the new element
                        $scope.$apply();
                    }]);
            }

        }

use it by passing just new element's selector. like this

compileAngularElement( '.user' ) ; 

Could not find a version that satisfies the requirement tensorflow

1.Go to https://www.tensorflow.org/install/pip website and look if the version you are using support the Tensorflow. some latest version does not support Tesnsorflow. until Tensorflow releases its latest version for that Python version.

  1. you must have 64 bit python installed

  2. have latest version of pip installed
    pip install --upgrade pip

Why do I need to configure the SQL dialect of a data source?

The dialect in the Hibernate context, will take care of database data type, like in orace it is integer however in SQL it is int, so this will by known in hibernate by this property, how to map the fields internally.

How do you use colspan and rowspan in HTML tables?

It is similar to your table

  <table border=1 width=50%>
<tr>
    <td rowspan="2">x</td> 
    <td colspan="4">y</td>
</tr>
<tr>
    <td bgcolor=#FFFF00 >I</td>
    <td>II</td>
    <td bgcolor=#FFFF00>III</td>
    <td>IV</td>
</tr>
<tr>
    <td>empty</td>
    <td bgcolor=#FFFF00>1</td>
    <td>2</td>
    <td bgcolor=#FFFF00>3</td>
    <td>4</td>
</tr>

How do I pass JavaScript variables to PHP?

You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.

You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.

<DOCTYPE html>
<html>
  <head>
    <title>My Test Form</title>
  </head>

  <body>
    <form method="POST">
      <p>Please, choose the salary id to proceed result:</p>
      <p>
        <label for="salarieids">SalarieID:</label>
        <?php
          $query = "SELECT * FROM salarie";
          $result = mysql_query($query);
          if ($result) :
        ?>
        <select id="salarieids" name="salarieid">
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
            }
          ?>
        </select>
        <?php endif ?>
      </p>
      <p>
        <input type="submit" value="Sumbit my choice"/>
      </p>
    </form>

    <?php if isset($_POST['salaried']) : ?>
      <?php
        $query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
        $result = mysql_query($query);
        if ($result) :
      ?>
        <table>
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<tr>';
              echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
              echo '</tr>';
            }
          ?>
        </table>
      <?php endif?>
    <?php endif ?>
  </body>
</html>

Changing the space between each item in Bootstrap navbar

With regard to bootstrap, the correct answer is using spacing utilities as mentioned by loopasam in a previous comment. Following is an example of using padding for both left and right.

<a href="#" class="nav-item nav-link px-3">Blog</a>

C++ callback using class member

Here's a concise version that works with class method callbacks and with regular function callbacks. In this example, to show how parameters are handled, the callback function takes two parameters: bool and int.

class Caller {
  template<class T> void addCallback(T* const object, void(T::* const mf)(bool,int))
  {
    using namespace std::placeholders; 
    callbacks_.emplace_back(std::bind(mf, object, _1, _2));
  }
  void addCallback(void(* const fun)(bool,int)) 
  {
    callbacks_.emplace_back(fun);
  }
  void callCallbacks(bool firstval, int secondval) 
  {
    for (const auto& cb : callbacks_)
      cb(firstval, secondval);
  }
private:
  std::vector<std::function<void(bool,int)>> callbacks_;
}

class Callee {
  void MyFunction(bool,int);
}

//then, somewhere in Callee, to add the callback, given a pointer to Caller `ptr`

ptr->addCallback(this, &Callee::MyFunction);

//or to add a call back to a regular function
ptr->addCallback(&MyRegularFunction);

This restricts the C++11-specific code to the addCallback method and private data in class Caller. To me, at least, this minimizes the chance of making mistakes when implementing it.

Injection of autowired dependencies failed;

The error shows that com.bd.service.ArticleService is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:

<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>

Alternatively, if you want to include all subpackages in com.bd:

<context:component-scan base-package="com.bd">
     <context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>

As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration.

@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {

    @Autowired
    ArticleService articleService;
    ...
}

You might find this Spring in depth section on Autowiring useful.

unix diff side-to-side results?

You can use:

sdiff  file1 file2

or

diff -y file1 file2

or

vimdiff file1 file2

for side by side display.

How do I view the list of functions a Linux shared library is exporting?

What you need is nm and its -D option:

$ nm -D /usr/lib/libopenal.so.1
.
.
.
00012ea0 T alcSetThreadContext
000140f0 T alcSuspendContext
         U atanf
         U calloc
.
.
.

Exported sumbols are indicated by a T. Required symbols that must be loaded from other shared objects have a U. Note that the symbol table does not include just functions, but exported variables as well.

See the nm manual page for more information.

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

How to insert special characters into a database?

$var = mysql_real_escape_string("data & the base");
$result = mysql_query('SELECT * FROM php_bugs WHERE php_bugs_category like  "%' .$var.'%"');

Default background color of SVG root element

Found this works in Safari. SVG only colors in with background-color where an element's bounding box covers. So, give it a border (stroke) with a zero pixel boundary. It fills in the whole thing for you with your background-color.

<svg style='stroke-width: 0px; background-color: blue;'> </svg>

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

you can also try this trick:

ps aux | grep puma

sample output:

myname           77921   0.0  0.0  2433828   1972 s000  R+   11:17AM   0:00.00 grep puma
myname           67661   0.0  2.3  2680504 191204 s002  S+   11:00AM   0:18.38 puma 3.11.2 (tcp://localhost:3000) [my_proj]

then:

kill -9 67661

Run a Python script from another Python script, passing in arguments

import subprocess
subprocess.call(" python script2.py 1", shell=True)

How to handle authentication popup with Selenium WebDriver using Java

Popular solution is to append username and password in URL, like, http://username:[email protected]. However, if your username or password contains special character, then it may fail. So when you create the URL, make sure you encode those special characters.

String username = URLEncoder.encode(user, StandardCharsets.UTF_8.toString());
String password = URLEncoder.encode(pass, StandardCharsets.UTF_8.toString());
String url = “http://“ + username + “:” + password + “@website.com”;
driver.get(url);

Error: EACCES: permission denied

node recommends executing following:

 sudo chown -R $USER:$(id -gn $USER) /home/venkatesh/.config

If you execute

npm config

You will see something like this

¦                   npm update check failed                   ¦
¦             Try running with sudo or get access             ¦
¦            to the local update config store via             ¦
¦ sudo chown -R $USER:$(id -gn $USER) /home/venkatesh/.config ¦

It worked for me.

Serializing enums with Jackson

Finally I found solution myself.

I had to annotate enum with @JsonSerialize(using = OrderTypeSerializer.class) and implement custom serializer:

public class OrderTypeSerializer extends JsonSerializer<OrderType> {

  @Override
  public void serialize(OrderType value, JsonGenerator generator,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {

    generator.writeStartObject();
    generator.writeFieldName("id");
    generator.writeNumber(value.getId());
    generator.writeFieldName("name");
    generator.writeString(value.getName());
    generator.writeEndObject();
  }
}

What is DOM Event delegation?

Event delegation makes use of two often overlooked features of JavaScript events: event bubbling and the target element.When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree.

Imagine an HTML table with 10 columns and 100 rows in which you want something to happen when the user clicks on a table cell. For example, I once had to make each cell of a table of that size editable when clicked. Adding event handlers to each of the 1000 cells would be a major performance problem and, potentially, a source of browser-crashing memory leaks. Instead, using event delegation, you would add only one event handler to the table element, intercept the click event and determine which cell was clicked.

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
.

Do not forget the . at the end, which indicates end of line

How to fill color in a cell in VBA?

  1. Use conditional formatting instead of VBA to highlight errors.

  2. Using a VBA loop like the one you posted will take a long time to process

  3. the statement If cell.Value = "#N/A" Then will never work. If you insist on using VBA to highlight errors, try this instead.

    Sub ColorCells()

    Dim Data As Range
    Dim cell As Range
    Set currentsheet = ActiveWorkbook.Sheets("Comparison")
    Set Data = currentsheet.Range("A2:AW1048576")
    
    For Each cell In Data
    
    If IsError(cell.Value) Then
       cell.Interior.ColorIndex = 3
    End If
    Next
    
    End Sub
    
  4. Be prepared for a long wait, since the procedure loops through 51 million cells

  5. There are more efficient ways to achieve what you want to do. Update your question if you have a change of mind.

Count textarea characters

$("#textarea").keyup(function(){
  $("#count").text($(this).val().length);
});

The above will do what you want. If you want to do a count down then change it to this:

$("#textarea").keyup(function(){
  $("#count").text("Characters left: " + (500 - $(this).val().length));
});

Alternatively, you can accomplish the same thing without jQuery using the following code. (Thanks @Niet)

document.getElementById('textarea').onkeyup = function () {
  document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};

What is TypeScript and why would I use it in place of JavaScript?

I originally wrote this answer when TypeScript was still hot-off-the-presses. Five years later, this is an OK overview, but look at Lodewijk's answer below for more depth

1000ft view...

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

To get an idea of what I mean, watch Microsoft's introductory video on the language.

For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.

It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza). These days, other IDEs offer TypeScript support too.

Are there other technologies like it?

There's CoffeeScript, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for tools through its optional static typing (see this recent blog post for a little more critique). There's also Dart but that's a full on replacement for JavaScript (though it can produce JavaScript code)

Example

As an example, here's some TypeScript (you can play with this in the TypeScript Playground)

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}  

And here's the JavaScript it would produce

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.

It's also capable of inferring types which aren't explicitly declared, for example, it would determine the greet() method returns a string.

Debugging TypeScript

Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio

Want to know more?

I originally wrote this answer when TypeScript was still hot-off-the-presses. Check out Lodewijk's answer to this question for some more current detail.

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I set up a simple 3-column range on Sheet1 with Country, City, and Language in columns A, B, and C. The following code autofilters the range and then pastes only one of the columns of autofiltered data to another sheet. You should be able to modify this for your purposes:

Sub CopyPartOfFilteredRange()
    Dim src As Worksheet
    Dim tgt As Worksheet
    Dim filterRange As Range
    Dim copyRange As Range
    Dim lastRow As Long

    Set src = ThisWorkbook.Sheets("Sheet1")
    Set tgt = ThisWorkbook.Sheets("Sheet2")

    ' turn off any autofilters that are already set
    src.AutoFilterMode = False

    ' find the last row with data in column A
    lastRow = src.Range("A" & src.Rows.Count).End(xlUp).Row

    ' the range that we are auto-filtering (all columns)
    Set filterRange = src.Range("A1:C" & lastRow)

    ' the range we want to copy (only columns we want to copy)
    ' in this case we are copying country from column A
    ' we set the range to start in row 2 to prevent copying the header
    Set copyRange = src.Range("A2:A" & lastRow)

    ' filter range based on column B
    filterRange.AutoFilter field:=2, Criteria1:="Rio de Janeiro"

    ' copy the visible cells to our target range
    ' note that you can easily find the last populated row on this sheet
    ' if you don't want to over-write your previous results
    copyRange.SpecialCells(xlCellTypeVisible).Copy tgt.Range("A1")

End Sub

Note that by using the syntax above to copy and paste, nothing is selected or activated (which you should always avoid in Excel VBA) and the clipboard is not used. As a result, Application.CutCopyMode = False is not necessary.

Including a groovy script in another groovy

Here's a complete example of including one script within another.
Just run the Testmain.groovy file
Explanatory comments included because I'm nice like that ;]

Testutils.groovy

// This is the 'include file'
// Testmain.groovy will load it as an implicit class
// Each method in here will become a method on the implicit class

def myUtilityMethod(String msg) {
    println "myUtilityMethod running with: ${msg}"
}

Testmain.groovy

// Run this file

// evaluate implicitly creates a class based on the filename specified
evaluate(new File("./Testutils.groovy"))
// Safer to use 'def' here as Groovy seems fussy about whether the filename (and therefore implicit class name) has a capital first letter
def tu = new Testutils()
tu.myUtilityMethod("hello world")

How to update one file in a zip archive

I've found the Linux zip file to be cumbersome for replacing a single file in a zip. The jar utility from the Java Development Kit may be easier. Consider the common task of updating WEB/web.xml in a JAR file (which is just a zip file):

jar -uf path/to/myapp.jar -C path/to/dir WEB-INF/web.xml

Here, path/to/dir is the path to a directory containing the WEB-INF directory (which in turn contains web.xml).

How do I find all files containing specific text on Linux?

List of file names containing a given text

First of all, I believe you have used -H instead of -l. Also you can try adding the text inside quotes followed by {} \.

find / -type f -exec grep -l "text-to-find-here" {} \; 

Example

Let's say you are searching for files containing specific text "Apache License" inside your directory. It will display results somewhat similar to below (output will be different based on your directory content).

bash-4.1$ find . -type f -exec grep -l "Apache License" {} \; 
./net/java/jvnet-parent/5/jvnet-parent-5.pom
./commons-cli/commons-cli/1.3.1/commons-cli-1.3.1.pom
./io/swagger/swagger-project/1.5.10/swagger-project-1.5.10.pom
./io/netty/netty-transport/4.1.7.Final/netty-transport-4.1.7.Final.pom
./commons-codec/commons-codec/1.9/commons-codec-1.9.pom
./commons-io/commons-io/2.4/commons-io-2.4.pom
bash-4.1$ 

Remove case sensitiveness

Even if you are not use about the case like "text" vs "TEXT", you can use the -i switch to ignore case. You can read further details here.

Hope this helps you.

Delete the 'first' record from a table in SQL Server, without a WHERE condition

What do you mean by «'first' record from a table» ? There's no such concept as "first record" in a relational db, i think.

Using MS SQL Server 2005, if you intend to delete the "top record" (the first one that is presented when you do a simple "*select * from tablename*"), you may use "delete top(1) from tablename"... but be aware that this does not assure which row is deleted from the recordset, as it just removes the first row that would be presented if you run the command "select top(1) from tablename".

How do I find the last column with data?

Lots of ways to do this. The most reliable is find.

Dim rLastCell As Range

Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)

MsgBox ("The last used column is: " & rLastCell.Column)

If you want to find the last column used in a particular row you can use:

Dim lColumn As Long

lColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column

Using used range (less reliable):

Dim lColumn As Long

lColumn = ws.UsedRange.Columns.Count

Using used range wont work if you have no data in column A. See here for another issue with used range:

See Here regarding resetting used range.

Column calculated from another column?

If it is a selection, you can do it as:

SELECT id, value, (value/2) AS calculated FROM mytable

Else, you can also first alter the table to add the missing column and then do an UPDATE query to compute the values for the new column as:

UPDATE mytable SET calculated = value/2;

If it must be automatic, and your MySQL version allows it, you can try with triggers

Execute method on startup in Spring

Posted another solution that implements WebApplicationInitializer and is called much before any spring bean is instantiated, in case someone has that use case

Initialize default Locale and Timezone with Spring configuration

offsetTop vs. jQuery.offset().top

It is possible that the offset could be a non-integer, using em as the measurement unit, relative font-sizes in %.

I also theorise that the offset might not be a whole number when the zoom isn't 100% but that depends how the browser handles scaling.

Squaring all elements in a list

Use a list comprehension (this is the way to go in pure Python):

>>> l = [1, 2, 3, 4]
>>> [i**2 for i in l]
[1, 4, 9, 16]

Or numpy (a well-established module):

>>> numpy.array([1, 2, 3, 4])**2
array([ 1,  4,  9, 16])

In numpy, math operations on arrays are, by default, executed element-wise. That's why you can **2 an entire array there.

Other possible solutions would be map-based, but in this case I'd really go for the list comprehension. It's Pythonic :) and a map-based solution that requires lambdas is slower than LC.

How do you declare an interface in C++?

The whole reason you have a special Interface type-category in addition to abstract base classes in C#/Java is because C#/Java do not support multiple inheritance.

C++ supports multiple inheritance, and so a special type isn't needed. An abstract base class with no non-abstract (pure virtual) methods is functionally equivalent to a C#/Java interface.

MVC ajax post to controller action method

try this:

/////// Controller post and get simple text value 
[HttpPost]
    public string Contact(string message)
    { 
        return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
    }

//// in the view add reference to the Javascript (jQuery) files

@section Scripts{

<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>  
}

/// then add the Post method as following:

<script type="text/javascript"> 

/// post and get text value
    
$("#send").on("click", function () {    
$.post('', { message: $('#msg').val() })  

//// empty post('') means post to the default controller, 
///we are not pacifying different action or controller
/// however we can define a url as following:
/// var url = "@(Url.Action("GetDataAction", "GetDataController"))"

         .done(function (response) {
             $("#myform").html(response);
        })
        .error(function () { alert('Error') })
        .success(function () { alert('OK') })
        return false;
    }); 

Now let's say you want to do it using $.Ajax and JSON:

// Post JSON data  add using System.Net;
    [HttpPost]
    public JsonResult JsonFullName(string fname, string lastname)
    {
        var data = "{ \"fname\" : \"" + fname  + " \" , \"lastname\" : \"" + lastname + "\" }";
//// you have to add the JsonRequestBehavior.AllowGet 
 //// otherwise it will throw an exception on run-time.
        return Json(data, JsonRequestBehavior.AllowGet);  
    }

Then, inside your view: add the event click on a an input of type button, or even a from submit: Just make sure your JSON data is well formatted.

  $("#jsonGetfullname").on("click", function () { 
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "@(Url.Action("JsonFullName", "Home"))",
            data: "{ \"fname\" : \"Mahmoud\" , \"lastname\" : \"Sayed\" }",
            dataType: "json",
            success: function (data) {
                var res = $.parseJSON(data);
                $("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
            }, 
            error: function (xhr, err) {
                alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
                alert("responseText: " + xhr.responseText);
            } 
        })
    });

Proper way to catch exception from JSON.parse

We can check error & 404 statusCode, and use try {} catch (err) {}.

You can try this :

_x000D_
_x000D_
const req = new XMLHttpRequest();_x000D_
req.onreadystatechange = function() {_x000D_
    if (req.status == 404) {_x000D_
        console.log("404");_x000D_
        return false;_x000D_
    }_x000D_
_x000D_
    if (!(req.readyState == 4 && req.status == 200))_x000D_
        return false;_x000D_
_x000D_
    const json = (function(raw) {_x000D_
        try {_x000D_
            return JSON.parse(raw);_x000D_
        } catch (err) {_x000D_
            return false;_x000D_
        }_x000D_
    })(req.responseText);_x000D_
_x000D_
    if (!json)_x000D_
        return false;_x000D_
_x000D_
    document.body.innerHTML = "Your city : " + json.city + "<br>Your isp : " + json.org;_x000D_
};_x000D_
req.open("GET", "https://ipapi.co/json/", true);_x000D_
req.send();
_x000D_
_x000D_
_x000D_

Read more :

LaTeX: remove blank page after a \part or \chapter

I believe that in the book class all \part and \chapter are set to start on a recto page.

from book.cls:

\newcommand\part{%
  \if@openright
    \cleardoublepage
  \else
    \clearpage
  \fi
  \thispagestyle{plain}%
  \if@twocolumn
    \onecolumn
    \@tempswatrue
  \else
    \@tempswafalse
  \fi
  \null\vfil
  \secdef\@part\@spart}

you should be able to renew that command, and something similar for the \chapter.

Changing the git user inside Visual Studio Code

I had the same problem as Daniel, setting the commit address and unsetting the credentials helper also worked for me.

git config --global user.email '<git-commit-address>'
git config --global --unset credential.helper

How to detect orientation change in layout in Android?

In case this is of use to some newer dev's because its not specified above. Just to be very explicit:

You need two things if using onConfigurationChanged:

  1. An onConfigurationChanged method in your Activity Class

  2. Specify in your manifest which configuration changes will be handled by your onConfigurationChanged method

The manifest snippet in the above answers, while no doubt correct for the particular app that manifest belongs to, is NOT exactly what you need to add in your manifest to trigger the onConfigurationChanged method in your Activity Class. i.e. the below manifest entry may not be correct for your app.

<activity name= ".MainActivity" android:configChanges="orientation|screenSize"/>

In the above manifest entry, there are various Android actions for android:configChanges="" which can trigger the onCreate in your Activity lifecycle.

This is very important - The ones NOT Specified in the manifest are the ones that trigger your onCreate and The ones specified in the manifest are the ones that trigger your onConfigurationChanged method in your Activity Class.

So you need to identify which config changes you need to handle yourself. For the Android Encyclopedically Challenged like me, I used the quick hints pop-out in Android Studio and added in almost every possible configuration option. Listing all of these basically said that I would handle everything and onCreate will never be called due to configurations.

<activity name= ".MainActivity" android:configChanges="screenLayout|touchscreen|mnc|mcc|density|uiMode|fontScale|orientation|keyboard|layoutDirection|locale|navigation|smallestScreenSize|keyboardHidden|colorMode|screenSize"/>

Now obviously I don't want to handle everything, so I began eliminating the above options one at a time. Re-building and testing my app after each removal.

Another important point: If there is just one configuration option being handled automatically that triggers your onCreate (You do not have it listed in your manifest above), then it will appear like onConfigurationChanged is not working. You must put all relevant ones into your manifest.

I ended up with 3 that were triggering onCreate originally, then I tested on an S10+ and I was still getting the onCreate, so I had to do my elimination exercise again and I also needed the |screenSize. So test on a selection of platforms.

<activity name= ".MainActivity" android:configChanges="screenLayout|uiMode|orientation|screenSize"/>

So my suggestion, although I'm sure someone can poke holes in this:

  1. Add your onConfigurationChanged method in your Activity Class with a TOAST or LOG so you can see when its working.

  2. Add all possible configuration options to your manifest.

  3. Confirm your onConfigurationChanged method is working by testing your app.

  4. Remove each config option from your manifest file one at a time, testing your app after each.

  5. Test on as large a variety of devices as possible.

  6. Do not copy/paste my snippet above to your manifest file. Android updates change the list, so use the pop-out Android Studio hints to make sure you get them all.

I hope this saves someone some time.

My onConfigurationChanged method just for info below. onConfigurationChanged is called in the lifecycle after the new orientation is available, but before the UI has been recreated. Hence my first if to check the orientation works correctly, and then the 2nd nested if to look at the visibility of my UI ImageView also works correctly.

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            pokerCardLarge = findViewById(R.id.pokerCardLgImageView);

            if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
                Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
                pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
                pokerCardLarge.setImageBitmap(image);
            }

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            pokerCardLarge = findViewById(R.id.pokerCardLgImageView);

            if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
                Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
                pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
                pokerCardLarge.setImageBitmap(image);
            }

        }
    }

How to make a round button?

Create an xml file named roundedbutton.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="rectangle">
    <solid android:color="#eeffffff" />
    <corners android:bottomRightRadius="8dp"
        android:bottomLeftRadius="8dp"  
        android:topRightRadius="8dp"
        android:topLeftRadius="8dp"/>
</shape>

Finally set that as background to your Button as android:background = "@drawable/roundedbutton"

If you want to make it completely rounded, alter the radius and settle for something that is ok for you.

Compile error: "g++: error trying to exec 'cc1plus': execvp: No such file or directory"

Something went wrong with your GCC installation. Try reinstalling the it like this:

sudo apt-get install --reinstall g++-5

In Ubuntu the g++ is a dependency package that installs the default version of g++ for your OS version. So simply removing and installing the package again won't work, cause it will install the default version. That's why you need to reinstall.

Note: You can replace the g++-5 with your desired g++ version. To find your current g++ version run this:

g++ --version

Return outside function error in Python

It basically occours when you return from a loop you can only return from function

How do you get the current page number of a ViewPager for Android?

The setOnPageChangeListener() method is deprecated. Use addOnPageChangeListener(OnPageChangeListener) instead.

You can use OnPageChangeListener and getting the position inside onPageSelected() method, this is an example:

   viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            Log.d(TAG, "my position is : " + position); 
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

Or just use getCurrentItem() to get the real position:

viewPager.getCurrentItem();

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

The reason on using the return:false; is well explained on this other question.

For the other issue, you can check for the referrer to see if it is empty:

    function backAway(){
        if (document.referrer == "") { //alternatively, window.history.length == 0
            window.location = "http://www.example.com";
        } else {
            history.back();
        }
    }

<a href="#" onClick="backAway()">Back Button Here.</a>

Check if a variable is a string in JavaScript

I find this simple technique useful to type-check for String -

String(x) === x // true, if x is a string
                // false in every other case

_x000D_
_x000D_
const test = x =>_x000D_
  console.assert_x000D_
    ( String(x) === x_x000D_
    , `not a string: ${x}`_x000D_
    )_x000D_
_x000D_
test("some string")_x000D_
test(123)           // assertion failed_x000D_
test(0)             // assertion failed_x000D_
test(/some regex/)  // assertion failed_x000D_
test([ 5, 6 ])      // assertion failed_x000D_
test({ a: 1 })      // assertion failed_x000D_
test(x => x + 1)    // assertion failed
_x000D_
_x000D_
_x000D_

The same technique works for Number too -

Number(x) === x // true, if x is a number
                // false in every other case

_x000D_
_x000D_
const test = x =>_x000D_
  console.assert_x000D_
    ( Number(x) === x_x000D_
    , `not a number: ${x}`_x000D_
    )_x000D_
_x000D_
test("some string") // assertion failed_x000D_
test(123)           _x000D_
test(0)             _x000D_
test(/some regex/)  // assertion failed_x000D_
test([ 5, 6 ])      // assertion failed_x000D_
test({ a: 1 })      // assertion failed_x000D_
test(x => x + 1)    // assertion failed
_x000D_
_x000D_
_x000D_

And for RegExp -

RegExp(x) === x // true, if x is a regexp
                // false in every other case

_x000D_
_x000D_
const test = x =>_x000D_
  console.assert_x000D_
    ( RegExp(x) === x_x000D_
    , `not a regexp: ${x}`_x000D_
    )_x000D_
_x000D_
test("some string") // assertion failed_x000D_
test(123)           // assertion failed_x000D_
test(0)             // assertion failed_x000D_
test(/some regex/)  _x000D_
test([ 5, 6 ])      // assertion failed_x000D_
test({ a: 1 })      // assertion failed_x000D_
test(x => x + 1)    // assertion failed
_x000D_
_x000D_
_x000D_

Same for Object -

Object(x) === x // true, if x is an object
                // false in every other case

NB, regexps, arrays, and functions are considered objects too.

_x000D_
_x000D_
const test = x =>_x000D_
  console.assert_x000D_
    ( Object(x) === x_x000D_
    , `not an object: ${x}`_x000D_
    )_x000D_
_x000D_
test("some string") // assertion failed_x000D_
test(123)           // assertion failed_x000D_
test(0)             // assertion failed_x000D_
test(/some regex/)  _x000D_
test([ 5, 6 ])      _x000D_
test({ a: 1 })      _x000D_
test(x => x + 1)    
_x000D_
_x000D_
_x000D_

But, checking for Array is a bit different -

Array.isArray(x) === x // true, if x is an array
                       // false in every other case

_x000D_
_x000D_
const test = x =>_x000D_
  console.assert_x000D_
    ( Array.isArray(x)_x000D_
    , `not an array: ${x}`_x000D_
    )_x000D_
_x000D_
test("some string") // assertion failed_x000D_
test(123)           // assertion failed_x000D_
test(0)             // assertion failed_x000D_
test(/some regex/)  // assertion failed_x000D_
test([ 5, 6 ])      _x000D_
test({ a: 1 })      // assertion failed_x000D_
test(x => x + 1)    // assertion failed
_x000D_
_x000D_
_x000D_

This technique does not work for Functions however -

Function(x) === x // always false

window.location.href doesn't redirect

In case anyone was a tired and silly as I was the other night whereupon I came across many threads espousing the different methods to get a javascript redirect, all of which were failing...

You can't use window.location.replace or document.location.href or any of your favourite vanilla javascript methods to redirect a page to itself.

So if you're dynamically adding in the redirect path from the back end, or pulling it from a data tag, make sure you do check at some stage for redirects to the current page. It could be as simple as:

if(window.location.href == linkout)
{
    location.reload();
}
else
{
    window.location.href = linkout;
}

How to index into a dictionary?

Dictionaries are unordered in Python versions up to and including Python 3.6. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can use d.keys()[i] and d.values()[i] or d.items()[i]. (Note that these methods create a list of all keys, values or items in Python 2.x. So if you need them more then once, store the list in a variable to improve performance.)

If you do care about the order of the entries, starting with Python 2.7 you can use collections.OrderedDict. Or use a list of pairs

l = [("blue", "5"), ("red", "6"), ("yellow", "8")]

if you don't need access by key. (Why are your numbers strings by the way?)

In Python 3.7, normal dictionaries are ordered, so you don't need to use OrderedDict anymore (but you still can – it's basically the same type). The CPython implementation of Python 3.6 already included that change, but since it's not part of the language specification, you can't rely on it in Python 3.6.

jQuery selectors on custom data attributes using HTML5

jsFiddle Demo

jQuery provides several selectors (full list) in order to make the queries you are looking for work. To address your question "In other cases is it possible to use other selectors like "contains, less than, greater than, etc..."." you can also use contains, starts with, and ends with to look at these html5 data attributes. See the full list above in order to see all of your options.

The basic querying has been covered above, and using John Hartsock's answer is going to be the best bet to either get every data-company element, or to get every one except Microsoft (or any other version of :not).

In order to expand this to the other points you are looking for, we can use several meta selectors. First, if you are going to do multiple queries, it is nice to cache the parent selection.

var group = $('ul[data-group="Companies"]');

Next, we can look for companies in this set who start with G

var google = $('[data-company^="G"]',group);//google

Or perhaps companies which contain the word soft

var microsoft = $('[data-company*="soft"]',group);//microsoft

It is also possible to get elements whose data attribute's ending matches

var facebook = $('[data-company$="book"]',group);//facebook

_x000D_
_x000D_
//stored selector_x000D_
var group = $('ul[data-group="Companies"]');_x000D_
_x000D_
//data-company starts with G_x000D_
var google = $('[data-company^="G"]',group).css('color','green');_x000D_
_x000D_
//data-company contains soft_x000D_
var microsoft = $('[data-company*="soft"]',group).css('color','blue');_x000D_
_x000D_
//data-company ends with book_x000D_
var facebook = $('[data-company$="book"]',group).css('color','pink');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul data-group="Companies">_x000D_
  <li data-company="Microsoft">Microsoft</li>_x000D_
  <li data-company="Google">Google</li>_x000D_
  <li data-company ="Facebook">Facebook</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

failed to load ad : 3

This error can be because of too much reasons. Try first with testAds ca-app-pub id to avoid admob account issues.

Check that you extends AppCompatActivity in your mainActivity, in my case that was the issue

Also check all this steps again https://developers.google.com/admob/android/quick-start?hl=en-419#import_the_mobile_ads_sdk