Programs & Examples On #Algebraic data types

Algebraic data types are data structures built from sums, products and recursive types, admitting an algebra. Descriptions of types given as ADTs may be manipulated symbolically to derive other related data structures. The logic for building types algebraically is related to combinatorial species in combinatorial mathematics.

How do you uninstall all dependencies listed in package.json (NPM)?

Another SIMPLE option is to delete the node_modules and package-lock.json

rm -rf node_modules
rm -rf package-lock.json

After this you can try reinstalling the npm packages

How to set the background image of a html 5 canvas to .png image

You can draw the image on the canvas and let the user draw on top of that.

The drawImage() function will help you with that, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

Run hive in debug mode

hive -hiveconf hive.root.logger=DEBUG,console

and then execute

show tables

can find the actual problem

What is the command to exit a Console application in C#?

You can use Environment.Exit(0); and Application.Exit

Environment.Exit(0) is cleaner.

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

This can be logically solved using a property. Here I have a property called a key.

  1. Take out any String property in the object and put it in the list.
  2. Check in the list weather that property contains if so then remove it.
  3. Return the object list.

List<Object> objectList = new ArrayList<>();
 List<String> keyList = new ArrayList<>();
  objectList.forEach( obj -> {
   if(keyList.contains(unAvailabilityModel.getKey())) 
         objectList.remove(unAvailabilityModel); 
    else
        keyList.add(unAvailabilityModel.getKey();
});
return objectList;

Array functions in jQuery

The Visual jQuery site has some great examples of jQuery's array functionality. (Click "Utilities" on the left-hand tab, and then "Array and Object operations".)

In Jenkins, how to checkout a project into a specific directory (using GIT)

It's worth investigating the Pipeline plugin. With the plugin you can checkout multiple VCS projects into relative directory paths. Beforehand creating a directory per VCS checkout. Then issue commands to the newly checked out VCS workspace. In my case I am using git. But you should get the idea.

node{
    def exists = fileExists 'foo'
    if (!exists){
        new File('foo').mkdir()
    }
    dir ('foo') {
        git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
        ......
    }
    def exists = fileExists 'bar'
    if (!exists){
        new File('bar').mkdir()
    }
    dir ('bar') {
        git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
        ......
    }
    def exists = fileExists 'baz'
    if (!exists){
        new File('baz').mkdir()
    }
    dir ('baz') {
        git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
        ......
    }
}

Read input stream twice

If you are using RestTemplate to make http calls Simply add an interceptor. Response body is cached by the implementation of ClientHttpResponse. Now inputstream can be retrieved from respose as many times as we need

ClientHttpRequestInterceptor interceptor =  new ClientHttpRequestInterceptor() {

            @Override
            public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                    ClientHttpRequestExecution execution) throws IOException {
                ClientHttpResponse  response = execution.execute(request, body);

                  // additional work before returning response
                  return response 
            }
        };

    // Add the interceptor to RestTemplate Instance 

         restTemplate.getInterceptors().add(interceptor); 

ConcurrentModificationException for ArrayList

You can't remove from list if you're browsing it with "for each" loop. You can use Iterator. Replace:

for (DrugStrength aDrugStrength : aDrugStrengthList) {
    if (!aDrugStrength.isValidDrugDescription()) {
        aDrugStrengthList.remove(aDrugStrength);
    }
}

With:

for (Iterator<DrugStrength> it = aDrugStrengthList.iterator(); it.hasNext(); ) {
    DrugStrength aDrugStrength = it.next();
    if (!aDrugStrength.isValidDrugDescription()) {
        it.remove();
    }
}

What is getattr() exactly and how do I use it?

I sometimes use getattr(..) to lazily initialise attributes of secondary importance just before they are used in the code.

Compare the following:

class Graph(object):
    def __init__(self):
        self.n_calls_to_plot = 0

    #...
    #A lot of code here
    #...

    def plot(self):
        self.n_calls_to_plot += 1

To this:

class Graph(object):
    def plot(self):
        self.n_calls_to_plot = 1 + getattr(self, "n_calls_to_plot", 0)

The advantage of the second way is that n_calls_to_plot only appears around the place in the code where it is used. This is good for readability, because (1) you can immediately see what value it starts with when reading how it's used, (2) it doesn't introduce a distraction into the __init__(..) method, which ideally should be about the conceptual state of the class, rather than some utility counter that is only used by one of the function's methods for technical reasons, such as optimisation, and has nothing to do with the meaning of the object.

Change Tomcat Server's timeout in Eclipse

I have tomcat 8 Update 25 and tomcat 7 but facing the same issue it shows the message Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.

Execute php file from another php

This came across while working on a project on linux platform.

exec('wget http://<url to the php script>)

This runs as if you run the script from browser.

Hope this helps!!

Convert Xml to Table SQL Server

This is the answer, hope it helps someone :)

First there are two variations on how the xml can be written:

1

<row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row>

Answer:

SELECT  
       Tbl.Col.value('IdInvernadero[1]', 'smallint'),  
       Tbl.Col.value('IdProducto[1]', 'smallint'),  
       Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
       Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
       Tbl.Col.value('Cantidad[1]', 'int'),
       Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM   @xml.nodes('//row') Tbl(Col)  

2.

<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />                         
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />

Answer:

SELECT  
       Tbl.Col.value('@IdInvernadero', 'smallint'),  
       Tbl.Col.value('@IdProducto', 'smallint'),  
       Tbl.Col.value('@IdCaracteristica1', 'smallint'),
       Tbl.Col.value('@IdCaracteristica2', 'smallint'),
       Tbl.Col.value('@Cantidad', 'int'),
       Tbl.Col.value('@Folio', 'varchar(7)')

FROM   @xml.nodes('//row') Tbl(Col)

Taken from:

  1. http://kennyshu.blogspot.com/2007/12/convert-xml-file-to-table-in-sql-2005.html

  2. http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx

Why am I getting InputMismatchException?

Since you have the manual user input loop, after the scanner has read your first input it will pass the carriage/return into the next line which will also be read; of course, that is not what you wanted.

You can try this

try {
    // ...
} catch (InputMismatchException e) {
    reader.next(); 
}

or alternatively, you can consume that carriage return before reading your next double input by calling

reader.next()

How do files get into the External Dependencies in Visual Studio C++?

To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified  all '.lib' files & there names for current project.

So, Developer has to specify external dependencies for Project as below..

1. Select Project in Solution explorer.

2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".

3.  Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".

enter image description here enter image description here

Best way to check for nullable bool in a condition expression (if ...)

I think a lot of people concentrate on the fact that this value is nullable, and don't think about what they actually want :)

bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else { ... } // false or null

Or if you want more options...

bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else if (nullableBool == false) { ... } // false
else { ... } // null

(nullableBool == true) will never return true if the bool? is null :P

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

Another reason of this problem may be a missing library.

Go to Properties -> Android and check that you add the libraries correctly

What is the difference between .text, .value, and .value2?

Except first answer form Bathsheba, except MSDN information for:

.Value
.Value2
.Text

you could analyse these tables for better understanding of differences between analysed properties.

enter image description here

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

ieshims.dll is an artefact of Vista/7 where a shim DLL is used to proxy certain calls (such as CreateProcess) to handle protected mode IE, which doesn't exist on XP, so it is unnecessary. wer.dll is related to Windows Error Reporting and again is probably unused on Windows XP which has a slightly different error reporting system than Vista and above.

I would say you shouldn't need either of them to be present on XP and would normally be delay loaded anyway.

How to remove special characters from a string?

Use the String.replaceAll() method in Java. replaceAll should be good enough for your problem.

How do I protect Python code?

The reliable only way to protect code is to run it on a server you control and provide your clients with a client which interfaces with that server.

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

I've tried all answers but only the following combination of advice has worked for me. Why? I had very specific requirements:

  1. JaCoCo generates report when build is run from command line: mvn clean verify (Maven 3.6.0)
  2. Intellij IDEA (2019.01) runs my tests as well
  3. It all works in presence of another javaagent defined in surefire plugin

Solution - prepend argLine value in surefire configuration with "late replacement" maven property @{...} as explained in surefire FAQ (my fixed configuration)

How do I use properties set by other plugins in argLine? Maven does property replacement for

${...} values in pom.xml before any plugin is run. So Surefire would never see the place-holders in its argLine property. Since the Version 2.17 using an alternate syntax for these properties,

@{...} allows late replacement of properties when the plugin is executed, so properties that have been modified by other plugins will be picked up correctly.

Failed first try - define jaCoCoArgLine property in prepare-agent goal configuration of jacoco - the scenario failed my second requirement, IntelliJ IDEA couldn't figure out agent for jmockit I use in the project for static method mocking

Spring Boot application can't resolve the org.springframework.boot package

When you run your application as an jar, your Manifest.MF file should know which class has the main method.

To add this information when SpringBoot compiles your code, add start-class property on your pom file.

E.g.:

<properties>
        <start-class>com.example.DemoApplication</start-class>
</properties>

Oracle: is there a tool to trace queries, like Profiler for sql server?

Oracle, along with other databases, analyzes a given query to create an execution plan. This plan is the most efficient way of retrieving the data.

Oracle provides the 'explain plan' statement which analyzes the query but doesn't run it, instead populating a special table that you can query (the plan table).

The syntax (simple version, there are other options such as to mark the rows in the plan table with a special ID, or use a different plan table) is:

explain plan for <sql query>

The analysis of that data is left for another question, or your further research.

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

Something I found was that all the fields have to match EXACTLY.

For example, sending 'cat dog' is not the same as sending 'catdog'.

What I did to troubleshoot this was to script out the FK code from the table I was inserting data into, take note of the "Foreign Key" that had the constraints (in my case there were 2) and make sure those 2 fields values matched EXACTLY as they were in the table that was throwing the FK Constraint error.

Once I fixed the 2 fields giving my problems, life was good!

If you need a better explanation, let me know.

What's the use of ob_start() in php?

You have it backwards. ob_start does not buffer the headers, it buffers the content. Using ob_start allows you to keep the content in a server-side buffer until you are ready to display it.

This is commonly used to so that pages can send headers 'after' they've 'sent' some content already (ie, deciding to redirect half way through rendering a page).

Ubuntu: Using curl to download an image

For ones who got permission denied for saving operation, here is the command that worked for me:

$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png --output py.png

Java NIO FileChannel versus FileOutputstream performance / usefulness

I tested the performance of FileInputStream vs. FileChannel for decoding base64 encoded files. In my experients I tested rather large file and traditional io was alway a bit faster than nio.

FileChannel might have had an advantage in prior versions of the jvm because of synchonization overhead in several io related classes, but modern jvm are pretty good at removing unneeded locks.

Timer for Python game

In this example the loop is run every second for ten seconds:

import datetime, time
then = datetime.datetime.now() + datetime.timedelta(seconds=10)
while then > datetime.datetime.now():
    print 'sleeping'
    time.sleep(1)

How to specify an element after which to wrap in css flexbox?

You can accomplish this by setting this on the container:

ul {
    display: flex;
    flex-wrap: wrap;
}

And on the child you set this:

li:nth-child(2n) {
    flex-basis: 100%;
}

_x000D_
_x000D_
ul {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
}

li:nth-child(4n) {
  flex-basis: 100%;
}
_x000D_
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>
_x000D_
_x000D_
_x000D_

This causes the child to make up 100% of the container width before any other calculation. Since the container is set to break in case there is not enough space it does so before and after this child. So you could use an empty div element to force the wrap between the element before and after it.

Cannot implicitly convert type 'int?' to 'int'.

Well you're casting OrdersPerHour to an int?

OrdersPerHour = (int?)dbcommand.ExecuteScalar();

Yet your method signature is int:

static int OrdersPerHour(string User)

The two have to match.


Also a quick suggestion -> Use parameters in your query, something like:

string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > ? AND User = ? AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered')";
OleDbCommand dbcommand = new OleDbCommand(query, conn);
dbcommand.Parameters.Add(curTime.AddHours(-1));
dbcommand.Parameters.Add(User);

Node Version Manager (NVM) on Windows

An alternative to nvm-windows, which is mentioned in other answers would be Nodist.

I've had some issues with nvm-windows and admin privileges, which Nodist doesn't seem to have.

Why doesn't java.util.Set have get(int index)?

This kind of leads to the question when you should use a set and when you should use a list. Usually, the advice goes:

  1. If you need ordered data, use a List
  2. If you need unique data, use a Set
  3. If you need both, use either: a SortedSet (for data ordered by comparator) or an OrderedSet/UniqueList (for data ordered by insertion). Unfortunately the Java API does not yet have OrderedSet/UniqueList.

A fourth case that appears often is that you need neither. In this case you see some programmers go with lists and some with sets. Personally I find it very harmful to see set as a list without ordering - because it is really a whole other beast. Unless you need stuff like set uniqueness or set equality, always favor lists.

mysql count group by having

SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t

How to inject a Map using the @Value Spring Annotation?

You can inject values into a Map from the properties file using the @Value annotation like this.

The property in the properties file.

propertyname={key1:'value1',key2:'value2',....}

In your code.

@Value("#{${propertyname}}")  private Map<String,String> propertyname;

Note the hashtag as part of the annotation.

Genymotion Android emulator - adb access?

If you launch the VM with the the launchpad (genymotion binary where you download the VMs) and you set the Android SDK path into the application parameters the connection is automatic and you don't need to run adb connect

You can find the information in the Genymotion Docs.

Visualizing decision tree in scikit-learn

I copy and change a part of your code as the below:

from pandas import read_csv, DataFrame
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from os import system

data = read_csv('D:/training.csv')
Y = data.Y
X = data.ix[:,"X0":"X33"]

dtree = tree.DecisionTreeClassifier(criterion = "entropy")
dtree = dtree.fit(X, Y)

After making sure you have dtree, which means that the above code runs well, you add the below code to visualize decision tree:

Remember to install graphviz first: pip install graphviz

import graphviz 
from graphviz import Source
dot_data = tree.export_graphviz(dtree, out_file=None, feature_names=X.columns)
graph = graphviz.Source(dot_data) 
graph.render("name of file",view = True)

I tried with my data, visualization worked well and I got a pdf file viewed immediately.

Breaking out of nested loops

If you're able to extract the loop code into a function, a return statement can be used to exit the outermost loop at any time.

def foo():
    for x in range(10):
        for y in range(10):
            print(x*y)
            if x*y > 50:
                return
foo()

If it's hard to extract that function you could use an inner function, as @bjd2385 suggests, e.g.

def your_outer_func():
    ...
    def inner_func():
        for x in range(10):
            for y in range(10):
                print(x*y)
                if x*y > 50:
                    return
    inner_func()
    ...

What's the console.log() of java?

console.log() in java is System.out.println(); to put text on the next line

And System.out.print(); puts text on the same line.

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

In my case I had a pem file which contained two certificates and an encrypted private key to be used in mutual SSL authentication. So my pem file looked like this:

-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9
...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

Here is what I did:

Split the file into three separate files, so that each one contains just one entry, starting with "---BEGIN.." and ending with "---END.." lines. Lets assume we now have three files: cert1.pem cert2.pem and pkey.pem

Convert pkey.pem into DER format using openssl and the following syntax:

openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER

Note, that if the private key is encrypted you need to supply a password( obtain it from the supplier of the original pem file ) to convert to DER format, openssl will ask you for the password like this: "enter a pass phraze for pkey.pem: " If conversion is successful, you will get a new file called "pkey.der"

Create a new java key store and import the private key and the certificates:

String keypass = "password";  // this is a new password, you need to come up with to protect your java key store file
String defaultalias = "importkey";
KeyStore ks = KeyStore.getInstance("JKS", "SUN");

// this section does not make much sense to me, 
// but I will leave it intact as this is how it was in the original example I found on internet:   
ks.load( null, keypass.toCharArray());
ks.store( new FileOutputStream ( "mykeystore"  ), keypass.toCharArray());
ks.load( new FileInputStream ( "mykeystore" ),    keypass.toCharArray());
// end of section..


// read the key file from disk and create a PrivateKey

FileInputStream fis = new FileInputStream("pkey.der");
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

byte[] key = new byte[bais.available()];
KeyFactory kf = KeyFactory.getInstance("RSA");
bais.read(key, 0, bais.available());
bais.close();

PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );
PrivateKey ff = kf.generatePrivate (keysp);


// read the certificates from the files and load them into the key store:

Collection  col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem"));
Collection  col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem"));

Certificate crt1 = (Certificate) col_crt1.iterator().next();
Certificate crt2 = (Certificate) col_crt2.iterator().next();
Certificate[] chain = new Certificate[] { crt1, crt2 };

String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName();
String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName();

ks.setCertificateEntry(alias1, crt1);
ks.setCertificateEntry(alias2, crt2);

// store the private key
ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain );

// save the key store to a file         
ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());

(optional) Verify the content of your new key store:

keytool -list -keystore mykeystore -storepass password

Keystore type: JKS Keystore provider: SUN

Your keystore contains 3 entries

cn=...,ou=...,o=.., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 2C:B8: ...

importkey, Sep 2, 2014, PrivateKeyEntry, Certificate fingerprint (SHA1): 9C:B0: ...

cn=...,o=...., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 83:63: ...

(optional) Test your certificates and private key from your new key store against your SSL server: ( You may want to enable debugging as an VM option: -Djavax.net.debug=all )

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        SSLSocketFactory factory = sclx.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 );
        socket.startHandshake();

        //if no exceptions are thrown in the startHandshake method, then everything is fine..

Finally register your certificates with HttpsURLConnection if plan to use it:

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        HostnameVerifier hv = new HostnameVerifier()
        {
            public boolean verify(String urlHostName, SSLSession session)
            {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost()))
                {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };

        HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() );
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

Android – Listen For Incoming SMS Messages

broadcast implementation on Kotlin:

 private class SmsListener : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.d(TAG, "SMS Received!")

        val txt = getTextFromSms(intent?.extras)
        Log.d(TAG, "message=" + txt)
    }

    private fun getTextFromSms(extras: Bundle?): String {
        val pdus = extras?.get("pdus") as Array<*>
        val format = extras.getString("format")
        var txt = ""
        for (pdu in pdus) {
            val smsmsg = getSmsMsg(pdu as ByteArray?, format)
            val submsg = smsmsg?.displayMessageBody
            submsg?.let { txt = "$txt$it" }
        }
        return txt
    }

    private fun getSmsMsg(pdu: ByteArray?, format: String?): SmsMessage? {
        return when {
            SDK_INT >= Build.VERSION_CODES.M -> SmsMessage.createFromPdu(pdu, format)
            else -> SmsMessage.createFromPdu(pdu)
        }
    }

    companion object {
        private val TAG = SmsListener::class.java.simpleName
    }
}

Note: In your manifest file add the BroadcastReceiver-

<receiver android:name=".listener.SmsListener">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

Add this permission:

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

How to get the last characters in a String in Java, regardless of String size

How about:

String numbers = text.substring(text.length() - 7);

That assumes that there are 7 characters at the end, of course. It will throw an exception if you pass it "12345". You could address that this way:

String numbers = text.substring(Math.max(0, text.length() - 7));

or

String numbers = text.length() <= 7 ? text : text.substring(text.length() - 7);

Note that this still isn't doing any validation that the resulting string contains numbers - and it will still throw an exception if text is null.

Why can't C# interfaces contain fields?

The short answer is yes, every implementing type will have to create its own backing variable. This is because an interface is analogous to a contract. All it can do is specify particular publicly accessible pieces of code that an implementing type must make available; it cannot contain any code itself.

Consider this scenario using what you suggest:

public interface InterfaceOne
{
    int myBackingVariable;

    int MyProperty { get { return myBackingVariable; } }
}

public interface InterfaceTwo
{
    int myBackingVariable;

    int MyProperty { get { return myBackingVariable; } }
}

public class MyClass : InterfaceOne, InterfaceTwo { }

We have a couple of problems here:

  • Because all members of an interface are--by definition--public, our backing variable is now exposed to anyone using the interface
  • Which myBackingVariable will MyClass use?

The most common approach taken is to declare the interface and a barebones abstract class that implements it. This allows you the flexibility of either inheriting from the abstract class and getting the implementation for free, or explicitly implementing the interface and being allowed to inherit from another class. It works something like this:

public interface IMyInterface
{
    int MyProperty { get; set; }
}

public abstract class MyInterfaceBase : IMyInterface
{
    int myProperty;

    public int MyProperty
    {
        get { return myProperty; }
        set { myProperty = value; }
    }
}

How to get all selected values of a multiple select box?

suppose the multiSelect is the Multiple-Select-Element, just use its selectedOptions Property:

//show all selected options in the console:

for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
  console.log( multiSelect.selectedOptions[i].value);
}

Saving the PuTTY session logging

To set permanent PuTTY session parameters do:

  1. Create sessions in PuTTY. Name it as "MyskinPROD"

  2. Configure the path for this session to point to "C:\dir\&Y&M&D&T_&H_putty.log".

  3. Create a Windows "Shortcut" to C:...\Putty.exe.

  4. Open "Shortcut" Properties and append "Target" line with parameters as shown below:

    "C:\Program Files (x86)\UTL\putty.exe" -ssh -load MyskinPROD user@ServerIP -pw password
    

Now, your PuTTY shortcut will bring in the "MyskinPROD" configuration every time you open the shortcut.

Check the screenshots and details on how I did it in my environment:

http://www.evernote.com/shard/s184/sh/93ebf08f-fde2-4dad-bccf-961c98fb614b/983d2ff8f2d1e6184318825d68b0b829

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.

How can I convert ArrayList<Object> to ArrayList<String>?

It's not safe to do that!
Imagine if you had:

ArrayList<Object> list = new ArrayList<Object>();
list.add(new Employee("Jonh"));
list.add(new Car("BMW","M3"));
list.add(new Chocolate("Twix"));

It wouldn't make sense to convert the list of those Objects to any type.

Regular Expression - 2 letters and 2 numbers in C#

You're missing an ending anchor.

if(Regex.IsMatch(myString, "^[A-Za-z]{2}[0-9]{2}\z")) {
    // ...
}

Here's a demo.


EDIT: If you can have anything between an initial 2 letters and a final 2 numbers:

if(Regex.IsMatch(myString, @"^[A-Za-z]{2}.*\d{2}\z")) {
    // ...
}

Here's a demo.

Filter df when values matches part of a string in pyspark

Spark 2.2 onwards

df.filter(df.location.contains('google.com'))

Spark 2.2 documentation link


Spark 2.1 and before

You can use plain SQL in filter

df.filter("location like '%google.com%'")

or with DataFrame column methods

df.filter(df.location.like('%google.com%'))

Spark 2.1 documentation link

Make an image follow mouse pointer

Ok, here's a simple box that follows the cursor

Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.

Select the right image (use a sprite) to orientate the rocket.

Yeah, annoying as hell. :-)

_x000D_
_x000D_
function getMouseCoords(e) {
  var e = e || window.event;
  document.getElementById('container').innerHTML = e.clientX + ', ' +
    e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}


var followCursor = (function() {
  var s = document.createElement('div');
  s.style.position = 'absolute';
  s.style.margin = '0';
  s.style.padding = '5px';
  s.style.border = '1px solid red';
  s.textContent = ""

  return {
    init: function() {
      document.body.appendChild(s);
    },

    run: function(e) {
      var e = e || window.event;
      s.style.left = (e.clientX - 5) + 'px';
      s.style.top = (e.clientY - 5) + 'px';
      getMouseCoords(e);
    }
  };
}());

window.onload = function() {
  followCursor.init();
  document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
  width: 1000px;
  height: 1000px;
  border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

How can I convert string to double in C++?

If it is a c-string (null-terminated array of type char), you can do something like:

#include <stdlib.h>
char str[] = "3.14159";
double num = atof(str);

If it is a C++ string, just use the c_str() method:

double num = atof( cppstr.c_str() );

atof() will convert the string to a double, returning 0 on failure. The function is documented here: http://www.cplusplus.com/reference/clibrary/cstdlib/atof.html

Fragment MyFragment not attached to Activity

Their are quite trick solution for this and leak of fragment from activity.

So in case of getResource or anything one which is depending on activity context accessing from Fragment it is always check activity status and fragments status as follows

 Activity activity = getActivity(); 
    if(activity != null && isAdded())

         getResources().getString(R.string.no_internet_error_msg);
//Or any other depends on activity context to be live like dailog


        }
    }

AngularJS $http-post - convert binary to excel file and download

There is no way (to my knowledge) to trigger the download window in your browser from Javascript. The only way to do it is to redirect the browser to a url that streams the file to the browser.

If you can modify your REST service, you might be able to solve it by changing so the POST request doesn't respond with the binary file, but with a url to that file. That'll get you the url in Javascript instead of the binary data, and you can redirect the browser to that url, which should prompt the download without leaving the original page.

How can I create a two dimensional array in JavaScript?

An awesome repository here .

  • api : masfufa.js

  • sample : masfufa.html

Two Examples will be enough to understand this library :

Example 1:

   /*     | 1 , 2 , 3 |
    * MX= | 4 , 5 , 6 |     Dimensions= 3 x 3
    *     | 7 , 8 , 9 |
    */ 


  jsdk.getAPI('my');
  var A=[1, 2, 3, 4, 5, 6, 7, 8, 9];
  var MX=myAPI.getInstance('masfufa',{data:A,dim:'3x3'});

then :

MX.get[0][0]  // -> 1 (first)
MX.get[2][2] //  ->9 (last)

Example 2:

   /*      | 1 , 9 , 3 , 4 |
    * MXB= | 4 , 5 , 6 , 2 |     Dimensions= 2 x 4
    *   
    */ 

  var B=[1 , 9 , 3 , 4 , 4 , 5 , 6 , 2];
  var MXB=myAPI.getInstance('masfufa',{data:B,dim:'2x4'});

then :

MXB.get[0][0]  // -> 1 (first)
MXB.get[1][3] //  -> 2 (last)
MXB.get[1][2] //  -> 6 (before last)

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

JSHint and jQuery: '$' is not defined

To fix this error when using the online JSHint implementation:

  • Click "CONFIGURE" (top of the middle column on the page)
  • Enable "jQuery" (under the "ASSUME" section at the bottom)

How to check if an email address exists without sending an email?

About all you can do is search DNS and ensure the domain that is in the email address has an MX record, other than that there is no reliable way of dealing with this.

Some servers may work with the rcpt-to method where you talk to the SMTP server, but it depends entirely on the configuration of the server. Another issue may be an overloaded server may return a 550 code saying user is unknown, but this is a temporary error, there is a permanent error (451 i think?) that can be returned. This depends entirely on the configuration of the server.

I personally would check for the DNS MX record, then send an email verification if the MX record exists.

Create unique constraint with null columns

You can store favourites with no associated menu in a separate table:

CREATE TABLE FavoriteWithoutMenu
(
  FavoriteWithoutMenuId uuid NOT NULL, --Primary key
  UserId uuid NOT NULL,
  RecipeId uuid NOT NULL,
  UNIQUE KEY (UserId, RecipeId)
)

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

After like three (3) hours of google..ing.This is the solution to the problem: First, I run this command;

$mysqladmin -u root -p[your root password here] version Which outputs:

    Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.

    Server version      5.5.49-0ubuntu0.14.04.1
    Protocol version    10
    Connection      Localhost via UNIX socket
    UNIX socket     /var/run/mysqld/mysqld.sock
    Uptime:         1 hour 54 min 3 sec

Finally, I changed the connect_type parameter from tcp to socket and added the parameter socket in config.inc.php:

    $cfg['Servers'][$i]['host'] = 'localhost';
    $cfg['Servers'][$i]['connect_type'] = 'socket';
    $cfg['Servers'][$i]['socket'] = '/var/run/mysqld/mysqld.sock';

All credit goes to this person: This is the correct solution

pandas: best way to select all columns whose names start with X

Another option for the selection of the desired entries is to use map:

df.loc[(df == 1).any(axis=1), df.columns.map(lambda x: x.startswith('foo'))]

which gives you all the columns for rows that contain a 1:

   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
5     6.8         1             0        5          0

The row selection is done by

(df == 1).any(axis=1)

as in @ajcr's answer which gives you:

0     True
1     True
2     True
3    False
4    False
5     True
dtype: bool

meaning that row 3 and 4 do not contain a 1 and won't be selected.

The selection of the columns is done using Boolean indexing like this:

df.columns.map(lambda x: x.startswith('foo'))

In the example above this returns

array([False,  True,  True,  True,  True,  True, False], dtype=bool)

So, if a column does not start with foo, False is returned and the column is therefore not selected.

If you just want to return all rows that contain a 1 - as your desired output suggests - you can simply do

df.loc[(df == 1).any(axis=1)]

which returns

   bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
0      5.0     1.0         0             0        2         NA      NA
1      5.0     2.1         0             1        4          0       0
2      6.0     NaN         0           NaN        1          0       1
5      6.8     6.8         1             0        5          0       0

Why doesn't C++ have a garbage collector?

SHORT ANSWER: We don't know how to do garbage collection efficiently (with minor time and space overhead) and correctly all the time (in all possible cases).

LONG ANSWER: Just like C, C++ is a systems language; this means it is used when you are writing system code, e.g., operating system. In other words, C++ is designed, just like C, with best possible performance as the main target. The language' standard will not add any feature that might hinder the performance objective.

This pauses the question: Why garbage collection hinders performance? The main reason is that, when it comes to implementation, we [computer scientists] do not know how to do garbage collection with minimal overhead, for all cases. Hence it's impossible to the C++ compiler and runtime system to perform garbage collection efficiently all the time. On the other hand, a C++ programmer, should know his design/implementation and he's the best person to decide how to best do the garbage collection.

Last, if control (hardware, details, etc.) and performance (time, space, power, etc.) are not the main constraints, then C++ is not the write tool. Other language might serve better and offer more [hidden] runtime management, with the necessary overhead.

How to read/write files in .Net Core?

For writing any Text to a file.

public static void WriteToFile(string DirectoryPath,string FileName,string Text)
    {
        //Check Whether directory exist or not if not then create it
        if(!Directory.Exists(DirectoryPath))
        {
            Directory.CreateDirectory(DirectoryPath);
        }

        string FilePath = DirectoryPath + "\\" + FileName;
        //Check Whether file exist or not if not then create it new else append on same file
        if (!File.Exists(FilePath))
        {
            File.WriteAllText(FilePath, Text);
        }
        else
        {
            Text = $"{Environment.NewLine}{Text}";
            File.AppendAllText(FilePath, Text);
        }
    }

For reading a Text from file

public static string ReadFromFile(string DirectoryPath,string FileName)
    {
        if (Directory.Exists(DirectoryPath))
        {
            string FilePath = DirectoryPath + "\\" + FileName;
            if (File.Exists(FilePath))
            {
                return File.ReadAllText(FilePath);
            }
        }
        return "";
    }

For Reference here this is the official microsoft document link.

Assigning strings to arrays of characters

To expand on Sparr's answer

Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.

Think of it like this:

Imagine that there are 2 functions, called InitializeObject, and AssignObject. When the compiler sees thing = value, it looks at the context and calls one InitializeObject if you're making a new thing. If you're not, it instead calls AssignObject.

Normally this is fine as InitializeObject and AssignObject usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.

PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++

What is a callback?

Probably not the dictionary definition, but a callback usually refers to a function, which is external to a particular object, being stored and then called upon a specific event.

An example might be when a UI button is created, it stores a reference to a function which performs an action. The action is handled by a different part of the code but when the button is pressed, the callback is called and this invokes the action to perform.

C#, rather than use the term 'callback' uses 'events' and 'delegates' and you can find out more about delegates here.

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

How to remove all white spaces in java

The most intuitive way of doing this without using literals or regular expressions:

yourString.replaceAll(" ","");

How to format a URL to get a file from Amazon S3?

Perhaps not what the OP was after, but for those searching the URL to simply access a readable object on S3 is more like:

https://<region>.amazonaws.com/<bucket-name>/<key>

Where <region> is something like s3-ap-southeast-2.

Click on the item in the S3 GUI to get the link for your bucket.

Extracting Path from OpenFileDialog path/filename

if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
    strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}

Editing an item in a list<T>

  1. You can use the FindIndex() method to find the index of item.
  2. Create a new list item.
  3. Override indexed item with the new item.

List<Class1> list = new List<Class1>();

int index = list.FindIndex(item => item.Number == textBox6.Text);

Class1 newItem = new Class1();
newItem.Prob1 = "SomeValue";

list[index] = newItem;

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I have the same problem and i think the firewall is blocking the git protocol. So in the end I have to resort to using https:// to fetch and push. However this will always prompt the user to enter the password...

here is the example what working for me (just to share with those cant use git:// protocol :)

git fetch https://[user-name]@github.com/[user-name]/[project].git

if the above works, you can remove the origin and replace with

git remote rm origin  
git remote add origin https://[user-name]@github.com/[user-name]/[project].git

Find and replace - Add carriage return OR Newline

You can also try \x0d\x0a in the "Replace with" box with "Use regular Expression" box checked to get carriage return + line feed using Visual Studio Find/Replace. Using \n (line feed) is the same as \x0a

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

I had this issue with gulp. The problem was that gulp added a dependency to my source file and I think npm tried to open it:

{
  "name": "name",
  "version": "2.0.0",
  "description": "",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "appname": "file://gulp",
    "gulp-concat": "^2.6.1",
    "gulp-electron": "^0.1.3",
    "gulp-shell": "^0.5.2",
    "gulp-uglify": "^2.0.0",
    "gulp-util": "^3.0.7",
    "node-7z": "^0.4.0"
  }
}

Make sure that there are no strange references in you package.json file.

Adding a collaborator to my free GitHub account?

Please note that Github now allows an unlimited number of collaborators even on a free account. See https://github.com/pricing.

Convert Uri to String and String to Uri

You can use Drawable instead of Uri.

   ImageView iv=(ImageView)findViewById(R.id.imageView1);
   String pathName = "/external/images/media/470939"; 
   Drawable image = Drawable.createFromPath(pathName);
   iv.setImageDrawable(image);

This would work.

How to send value attribute from radio button in PHP

When you select a radio button and click on a submit button, you need to handle the submission of any selected values in your php code using $_POST[]
For example:
if your radio button is:

<input type="radio" name="rdb" value="male"/>

then in your php code you need to use:

$rdb_value = $_POST['rdb'];

replace special characters in a string python

You need to call replace on z and not on str, since you want to replace characters located in the string variable z

removeSpecialChars = z.replace("!@#$%^&*()[]{};:,./<>?\|`~-=_+", " ")

But this will not work, as replace looks for a substring, you will most likely need to use regular expression module re with the sub function:

import re
removeSpecialChars = re.sub("[!@#$%^&*()[]{};:,./<>?\|`~-=_+]", " ", z)

Don't forget the [], which indicates that this is a set of characters to be replaced.

What are some good Python ORM solutions?

If you're looking for lightweight and are already familiar with django-style declarative models, check out peewee: https://github.com/coleifer/peewee

Example:

import datetime
from peewee import *

class Blog(Model):
    name = CharField()

class Entry(Model):
    blog = ForeignKeyField(Blog)
    title = CharField()
    body = TextField()
    pub_date = DateTimeField(default=datetime.datetime.now)

# query it like django
Entry.filter(blog__name='Some great blog')

# or programmatically for finer-grained control
Entry.select().join(Blog).where(Blog.name == 'Some awesome blog')

Check the docs for more examples.

Volatile boolean vs AtomicBoolean

If there are multiple threads accessing class level variable then each thread can keep copy of that variable in its threadlocal cache.

Making the variable volatile will prevent threads from keeping the copy of variable in threadlocal cache.

Atomic variables are different and they allow atomic modification of their values.

Change old commit message on Git

It says:

When you save and exit the editor, it will rewind you back to that last commit in that list and drop you on the command line with the following message:

$ git rebase -i HEAD~3
Stopped at 7482e0d... updated the gemspec to hopefully work better
You can amend the commit now, with

It does not mean:

type again git rebase -i HEAD~3

Try to not typing git rebase -i HEAD~3 when exiting the editor, and it should work fine.
(otherwise, in your particular situation, a git rebase -i --abort might be needed to reset everything and allow you to try again)


As Dave Vogt mentions in the comments, git rebase --continue is for going to the next task in the rebasing process, after you've amended the first commit.

Also, Gregg Lind mentions in his answer the reword command of git rebase:

By replacing the command "pick" with the command "edit", you can tell git rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.

If you just want to edit the commit message for a commit, replace the command "pick" with the command "reword", since Git1.6.6 (January 2010).

It does the same thing ‘edit’ does during an interactive rebase, except it only lets you edit the commit message without returning control to the shell. This is extremely useful.
Currently if you want to clean up your commit messages you have to:

$ git rebase -i next

Then set all the commits to ‘edit’. Then on each one:

# Change the message in your editor.
$ git commit --amend
$ git rebase --continue

Using ‘reword’ instead of ‘edit’ lets you skip the git-commit and git-rebase calls.

openpyxl - adjust column width size

I had to change @User3759685 above answer to this when the openpxyl updated. I was getting an error. Well @phihag reported this in the comments as well

for column_cells in ws.columns:
    new_column_length = max(len(as_text(cell.value)) for cell in column_cells)
    new_column_letter = (openpyxl.utils.get_column_letter(column_cells[0].column))
    if new_column_length > 0:
        ws.column_dimensions[new_column_letter].width = new_column_length + 1

Can an Option in a Select tag carry multiple values?

I did this by using data attributes. Is a lot cleaner than other methods attempting to explode etc.

HTML

<select class="example">
    <option value="1" data-value="A">One</option>
    <option value="2" data-value="B">Two</option>
    <option value="3" data-value="C">Three</option>
    <option value="4" data-value="D">Four</option>
</select>

JS

$('select.example').change(function() {

    var other_val = $('select.example option[value="' + $(this).val() + '"]').data('value');

    console.log(other_val);

});

Import pandas dataframe column as string not int

This probably isn't the most elegant way to do it, but it gets the job done.

In[1]: import numpy as np

In[2]: import pandas as pd

In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])

In[4]: df
Out[4]: 
                       ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

Just replace '/Users/spencerlyon2/Desktop/test.csv' with the path to your file

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

This is an issue with the 64 bit version of Kepler and windows7 in my case. I downloaded the 32 bit and it worked immediately.

Open youtube video in Fancybox jquery

Thanx, Alexander!

And to set the fancy-close button above the youtube's flash-content add 'wmode' to 'swf' parameters:

'swf': {'allowfullscreen':'true', 'wmode':'transparent'}

How to convert int to float in python?

Other than John's answer, you could also make one of the variable float, and the result will yield float.

>>> 144 / 314.0
0.4585987261146497

Using group by on multiple columns

In simple English from GROUP BY with two parameters what we are doing is looking for similar value pairs and get the count to a 3rd column.

Look at the following example for reference. Here I'm using International football results from 1872 to 2020

+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|       _c0|             _c1|     _c2|_c3|_c4|     _c5|      _c6|                _c7|  _c8|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|1872-11-30|        Scotland| England|  0|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1873-03-08|         England|Scotland|  4|  2|Friendly|   London|            England|FALSE|
|1874-03-07|        Scotland| England|  2|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1875-03-06|         England|Scotland|  2|  2|Friendly|   London|            England|FALSE|
|1876-03-04|        Scotland| England|  3|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1876-03-25|        Scotland|   Wales|  4|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1877-03-03|         England|Scotland|  1|  3|Friendly|   London|            England|FALSE|
|1877-03-05|           Wales|Scotland|  0|  2|Friendly|  Wrexham|              Wales|FALSE|
|1878-03-02|        Scotland| England|  7|  2|Friendly|  Glasgow|           Scotland|FALSE|
|1878-03-23|        Scotland|   Wales|  9|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1879-01-18|         England|   Wales|  2|  1|Friendly|   London|            England|FALSE|
|1879-04-05|         England|Scotland|  5|  4|Friendly|   London|            England|FALSE|
|1879-04-07|           Wales|Scotland|  0|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-13|        Scotland| England|  5|  4|Friendly|  Glasgow|           Scotland|FALSE|
|1880-03-15|           Wales| England|  2|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-27|        Scotland|   Wales|  5|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1881-02-26|         England|   Wales|  0|  1|Friendly|Blackburn|            England|FALSE|
|1881-03-12|         England|Scotland|  1|  6|Friendly|   London|            England|FALSE|
|1881-03-14|           Wales|Scotland|  1|  5|Friendly|  Wrexham|              Wales|FALSE|
|1882-02-18|Northern Ireland| England|  0| 13|Friendly|  Belfast|Republic of Ireland|FALSE|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+

And now I'm going to group by similar country(column _c7) and tournament(_c5) value pairs by GROUP BY operation,

SELECT `_c5`,`_c7`,count(*)  FROM res GROUP BY `_c5`,`_c7`

+--------------------+-------------------+--------+
|                 _c5|                _c7|count(1)|
+--------------------+-------------------+--------+
|            Friendly|  Southern Rhodesia|      11|
|            Friendly|            Ecuador|      68|
|African Cup of Na...|           Ethiopia|      41|
|Gold Cup qualific...|Trinidad and Tobago|       9|
|AFC Asian Cup qua...|             Bhutan|       7|
|African Nations C...|              Gabon|       2|
|            Friendly|           China PR|     170|
|FIFA World Cup qu...|             Israel|      59|
|FIFA World Cup qu...|              Japan|      61|
|UEFA Euro qualifi...|            Romania|      62|
|AFC Asian Cup qua...|              Macau|       9|
|            Friendly|        South Sudan|       1|
|CONCACAF Nations ...|           Suriname|       3|
|         Copa Newton|          Argentina|      12|
|            Friendly|        Philippines|      38|
|FIFA World Cup qu...|              Chile|      68|
|African Cup of Na...|         Madagascar|      29|
|FIFA World Cup qu...|       Burkina Faso|      30|
| UEFA Nations League|            Denmark|       4|
|        Atlantic Cup|           Paraguay|       2|
+--------------------+-------------------+--------+

Explanation: The meaning of the first row is there were 11 Friendly tournaments held on Southern Rhodesia in total.

Note: Here it's mandatory to use a counter column in this case.

How can I get a list of all classes within current module in Python?

This is the line that I use to get all of the classes that have been defined in the current module (ie not imported). It's a little long according to PEP-8 but you can change it as you see fit.

import sys
import inspect

classes = [name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass) 
          if obj.__module__ is __name__]

This gives you a list of the class names. If you want the class objects themselves just keep obj instead.

classes = [obj for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isclass)
          if obj.__module__ is __name__]

This is has been more useful in my experience.

typeof !== "undefined" vs. != null

If you are really worried about undefined being redefined, you can protect against this with some helper method like this:

function is_undefined(value) {
   var undefined_check; // instantiate a new variable which gets initialized to the real undefined value
   return value === undefined_check;
}

This works because when someone writes undefined = "foo" he only lets the name undefined reference to a new value, but he doesn't change the actual value of undefined.

Changing the color of a clicked table row using jQuery

.highlight { background-color: papayawhip; }

$("#table tr").click(function() {    
 $("#table tr").removeClass("highlight");
            $(this).addClass("highlight");
});

"Sub or Function not defined" when trying to run a VBA script in Outlook

I need to add that, if the Module name and the sub name is the same you have such issue. Consider change the Module name to mod_Test instead of "Test" which is the same as the sub.

How to use LDFLAGS in makefile

Seems like the order of the linking flags was not an issue in older versions of gcc. Eg gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16) comes with Centos-6.7 happy with linker option before inputfile; but gcc with ubuntu 16.04 gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413 does not allow.

Its not the gcc version alone, I has got something to with the distros

What is difference between INNER join and OUTER join

Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.
Left outer join - A left outer join will give all rows in A, plus any common rows in B.
Full outer join - A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa. check this

Use jquery to set value of div tag

use as below:

<div id="getSessionStorage"></div>

For this to append anything use below code for reference:

$(document).ready(function () {
        var storageVal = sessionStorage.getItem("UserName");
        alert(storageVal);
        $("#getSessionStorage").append(storageVal);
     });

This will appear as below in html (assuming storageVal="Rishabh")

<div id="getSessionStorage">Rishabh</div>

Remove HTML Tags from an NSString on the iPhone

#import "RegexKitLite.h"

string text = [html stringByReplacingOccurrencesOfRegex:@"<[^>]+>" withString:@""]

How to add a custom HTTP header to every WCF call?

If you just want to add the same header to all the requests to the service, you can do it with out any coding!
Just add the headers node with required headers under the endpoint node in your client config file

<client>  
  <endpoint address="http://localhost/..." >  
    <headers>  
      <HeaderName>Value</HeaderName>  
    </headers>   
 </endpoint>  

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

Your method showFile() declares that it can throw an IOException. Since this is a checked exception, any call to showFile() method must handle the exception somehow. One option is to wrap the call to showFile() in a try-catch block.

 try {
     showFile();
 }
 catch(IOException e) {
    // Code to handle an IOException here
 }

How to remove a column from an existing table?

ALTER TABLE MEN DROP COLUMN Lname

what is the difference between XSD and WSDL

XSD is to validate the document, and contains metadata about the XML whereas WSDL is to describe the webservice location and operations.

How to get the xml node value in string

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    Console.WriteLine(n[0].InnerText); //Will output '08:29:57'
}

or you could wrap in foreach loop to print each value

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    foreach(XmlNode curr in n) {
        Console.WriteLine(curr.InnerText);
    }
}

ArrayList of String Arrays

private List<String[]> addresses = new ArrayList<String[]>();

this will work defenitely...

How to set radio button selected value using jquery

Can be done using the id of the element

example

<label><input type="radio" name="travel_mode"  value="Flight" id="Flight"> Flight </label>
<label><input type="radio" name="travel_mode"  value="Train" id="Train"> Train </label>
<label><input type="radio" name="travel_mode"  value="Bus" id="Bus"> Bus </label>
<label><input type="radio" name="travel_mode"  value="Road" id="Road"> Other </label>

js:

$('#' + selected).prop('checked',true);

CSS background image in :after element

As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:

background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;

Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).

No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.

What does mscorlib stand for?

It stands for

Microsoft's Common Object Runtime Library

and it is the primary assembly for the Framework Common Library.

It contains the following namespaces:

 System
 System.Collections
 System.Configuration.Assemblies
 System.Diagnostics
 System.Diagnostics.SymbolStore
 System.Globalization
 System.IO
 System.IO.IsolatedStorage
 System.Reflection
 System.Reflection.Emit
 System.Resources
 System.Runtime.CompilerServices
 System.Runtime.InteropServices
 System.Runtime.InteropServices.Expando
 System.Runtime.Remoting
 System.Runtime.Remoting.Activation
 System.Runtime.Remoting.Channels
 System.Runtime.Remoting.Contexts
 System.Runtime.Remoting.Lifetime
 System.Runtime.Remoting.Messaging
 System.Runtime.Remoting.Metadata
 System.Runtime.Remoting.Metadata.W3cXsd2001
 System.Runtime.Remoting.Proxies
 System.Runtime.Remoting.Services
 System.Runtime.Serialization
 System.Runtime.Serialization.Formatters
 System.Runtime.Serialization.Formatters.Binary
 System.Security
 System.Security.Cryptography
 System.Security.Cryptography.X509Certificates
 System.Security.Permissions
 System.Security.Policy
 System.Security.Principal
 System.Text
 System.Threading
 Microsoft.Win32 

Interesting info about MSCorlib:

  • The .NET 2.0 assembly will reference and use the 2.0 mscorlib.The .NET 1.1 assembly will reference the 1.1 mscorlib but will use the 2.0 mscorlib at runtime (due to hard-coded version redirects in theruntime itself)
  • In GAC there is only one version of mscorlib, you dont find 1.1 version on GAC even if you have 1.1 framework installed on your machine. It would be good if somebody can explain why MSCorlib 2.0 alone is in GAC whereas 1.x version live inside framework folder
  • Is it possible to force a different runtime to be loaded by the application by making a config setting in your app / web.config? you won’t be able to choose the CLR version by settings in the ConfigurationFile – at that point, a CLR will already be running, and there can only be one per process. Immediately after the CLR is chosen the MSCorlib appropriate for that CLR is loaded.

Bootstrap4 adding scrollbar to div

Yes, It is possible, Just add a class like anyclass and give some CSS style. Live

.anyClass {
  height:150px;
  overflow-y: scroll;
}

_x000D_
_x000D_
.anyClass {_x000D_
  height:150px;_x000D_
  overflow-y: scroll;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class=" col-md-2">_x000D_
  <ul class="nav nav-pills nav-stacked anyClass">_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link active" href="#">Active</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li><li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link" href="#">Link</a>_x000D_
    </li>_x000D_
    <li class="nav-item">_x000D_
      <a class="nav-link disabled" href="#">Disabled</a>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What "wmic bios get serialnumber" actually retrieves?

the wmic bios get serialnumber command call the Win32_BIOS wmi class and get the value of the SerialNumber property, which retrieves the serial number of the BIOS Chip of your system.

How to read an external local JSON file in JavaScript?

So, if you are planning to go with "Apache Tomcat" for hosting your JSON file,

1> After starting up the server, verify that your Apache Tomcat is up and running by going to this url: "localhost:8080" -

enter image description here



2> Next, go to the "webapps" folder - "C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps". And, create a project folder or copy your project folder.

enter image description here


3> Paste your json file over there. enter image description here



4> And that's it. You are done! Just go to - "http://localhost:8080/$project_name$/$jsonFile_name$.json"enter image description here

Access Tomcat Manager App from different host

For Tomcat v8.5.4 and above, the file <tomcat>/webapps/manager/META-INF/context.xml has been adjusted:

<Context antiResourceLocking="false" privileged="true" >
    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
</Context>

Change this file to comment the Valve:

<Context antiResourceLocking="false" privileged="true" >
    <!--
    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
    -->
</Context>

After that, refresh your browser (not need to restart Tomcat), you can see the manager page.

Find files containing a given text

find them and grep for the string:

This will find all files of your 3 types in /starting/path and grep for the regular expression '(document\.cookie|setcookie)'. Split over 2 lines with the backslash just for readability...

find /starting/path -type f -name "*.php" -o -name "*.html" -o -name "*.js" | \
 xargs egrep -i '(document\.cookie|setcookie)'

using BETWEEN in WHERE condition

You might also encounter an error message. "Operand type clash: date is incompatible with int.

Use single quotes around the dates. E.g.: $this->db->where("$accommodation BETWEEN '$minvalue' AND '$maxvalue'");

Column/Vertical selection with Keyboard in SublimeText 3

This should do it:

  1. Ctrl+A - select all.
  2. Ctrl+Shift+L - split selection into lines.
  3. Then move all cursors with left/right, select with Shift+left/right. Move all cursors to start of line with Home.

How to fix "'System.AggregateException' occurred in mscorlib.dll"

The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.

Task.Factory.StartNew(x=>
   throw new Exception("I didn't account for this");
)

However, if we do this, at least the application does not crash.

Task.Factory.StartNew(x=>
   try {
      throw new Exception("I didn't account for this");
   }
   catch(Exception ex) {
      //Log ex
   }
)

Is it possible to put CSS @media rules inline?

Problem

No, Media Queries cannot be used in this way

<span style="@media (...) { ... }"></span>

Solution

But if you want provided a specific behavior usable on the fly AND responsive, you can use the style markup and not the attribute.

e.i.

<style scoped>
.on-the-fly-behavior {
    background-image: url('particular_ad.png'); 
}
@media (max-width: 300px) {
    .on-the-fly-behavior {
        background-image: url('particular_ad_small.png');
    }
}
</style>
<span class="on-the-fly-behavior"></span>

See the code working in live on CodePen

In my Blog for example, I inject a <style> markup in <head> just after <link> declaration for CSS and it's contain the content of a textarea provided beside of real content textarea for create extra-class on the fly when I wrote an artitle.

Note : the scoped attribute is a part of HTML5 specification. If you do not use it, the validator will blame you but browsers currently not support the real purpose : scoped the content of <style> only on immediatly parent element and that element's child elements. Scoped is not mandatory if the <style> element is in <head> markup.


UPDATE: I advice to always use rules in the mobile first way so previous code should be:

<style scoped>
/* 0 to 299 */
.on-the-fly-behavior {
    background-image: url('particular_ad_small.png'); 
}
/* 300 to X */
@media (min-width: 300px) { /* or 301 if you want really the same as previously.  */
    .on-the-fly-behavior {   
        background-image: url('particular_ad.png');
    }
}
</style>
<span class="on-the-fly-behavior"></span>

How do I move a redis database from one server to another?

The simple way I found to export / Backup Redis data (create dump file ) is to start up a server via command line with slaveof flag and create live replica as follow (assuming the source Redis is 1.2.3.4 on port 6379):

/usr/bin/redis-server --port 6399 --dbfilename backup_of_master.rdb --slaveof 1.2.3.4 6379

android - setting LayoutParams programmatically

For Xamarin Android align to the left of an object

int dp24 = (int)TypedValue.ApplyDimension( ComplexUnitType.Dip, 24, Resources.System.DisplayMetrics );
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( dp24, dp24 );
            lp.AddRule( LayoutRules.CenterInParent, 1 );
            lp.AddRule( LayoutRules.LeftOf, //Id of the field Eg m_Button.Id ); 
            m_Button.LayoutParameters = lp;

Error in Eclipse: "The project cannot be built until build path errors are resolved"

I also had this problem in my system, but after looking inside the project I saw the XML structure of the .classpath file in the project path was incorrect. After amending that file the problem was solved.

! [rejected] master -> master (fetch first)

Try this git command

git push origin master --force

or short of force -f

git push origin master -f

How to install SignTool.exe for Windows 10

You need to install the Windows 10 SDK.

  1. Visual Studio 2015 Update 1 contains it already, but it is not installed by default. You should go to Control Panel -> Programs and Features, find Microsoft Visual Studio 2015 and select "Change".

Visual Studio 2015 setup will start. Select "Modify".

In Visual Studio components list find "Universal Windows App Development Tools", open the list of sub-items and select "Windows 10 SDK (10.0.10240)".

Windows 10 SDK in VS 2015 Update 1 Setup

  1. Of cause you can install Windows 10 SDK directly from Microsoft: https://go.microsoft.com/fwlink/?LinkID=698771

As josant already wrote - when the installation finishes you will find the SignTool.exe in the folders:

  • x86 -> c:\Program Files (x86)\Windows Kits\10\bin\x86
  • x64 -> c:\Program Files (x86)\Windows Kits\10\bin\x64\

Creating a Shopping Cart using only HTML/JavaScript

You simply need to use simpleCart

It is a free and open-source javascript shopping cart that easily integrates with your current website.

You will get the full source code at github

How to use youtube-dl from a python program?

I would like this

from subprocess import call

command = "youtube-dl https://www.youtube.com/watch?v=NG3WygJmiVs -c"
call(command.split(), shell=False)

Error checking for NULL in VBScript

I see lots of confusion in the comments. Null, IsNull() and vbNull are mainly used for database handling and normally not used in VBScript. If it is not explicitly stated in the documentation of the calling object/data, do not use it.

To test if a variable is uninitialized, use IsEmpty(). To test if a variable is uninitialized or contains "", test on "" or Empty. To test if a variable is an object, use IsObject and to see if this object has no reference test on Is Nothing.

In your case, you first want to test if the variable is an object, and then see if that variable is Nothing, because if it isn't an object, you get the "Object Required" error when you test on Nothing.

snippet to mix and match in your code:

If IsObject(provider) Then
    If Not provider Is Nothing Then
        ' Code to handle a NOT empty object / valid reference
    Else
        ' Code to handle an empty object / null reference
    End If
Else
    If IsEmpty(provider) Then
        ' Code to handle a not initialized variable or a variable explicitly set to empty
    ElseIf provider = "" Then
        ' Code to handle an empty variable (but initialized and set to "")
    Else
        ' Code to handle handle a filled variable
    End If
End If

Any way to make a WPF textblock selectable?

Use a TextBox with these settings instead to make it read only and to look like a TextBlock control.

<TextBox Background="Transparent"
         BorderThickness="0"
         Text="{Binding Text, Mode=OneWay}"
         IsReadOnly="True"
         TextWrapping="Wrap" />

Xcode 4: How do you view the console?

Here's an alternative.

  1. In XCode4 double-click your Project (Blueprint Icon).
  2. Select the Target (Gray Icon)
  3. Select the Build Phases (Top Center)
  4. Add Build Phase "Run Script" (Green Plus Button, bottom right)
  5. In the textbox below the Shell textfield replace "Type a script or drag a script file from your workspace" with "open ${TARGET_BUILD_DIR}/${TARGET_NAME}"

This will open a terminal window with your command-line app running in it.

This is not a great solution because XCode 4 still runs and debugs the app independently of what you're doing in the terminal window that pops up.

How to find the location of the Scheduled Tasks folder

Tasks are saved in filesystem AND registry

Tasks are stored in 3 locations: 1 file system location and 2 registry locations.

File system:

C:\Windows\System32\Tasks

Registry:

HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree

So, you need to delete a corrupted task in these 3 locations.

How can I verify if one list is a subset of another?

one = [1, 2, 3]
two = [9, 8, 5, 3, 2, 1]

set(x in two for x in one) == set([True])

If list1 is in list 2:

  • (x in two for x in one) generates a list of True.

  • when we do a set(x in two for x in one) has only one element (True).

How to test for $null array in PowerShell

How do you want things to behave?

If you want arrays with no elements to be treated the same as unassigned arrays, use:

[array]$foo = @() #example where we'd want TRUE to be returned
@($foo).Count -eq 0

If you want a blank array to be seen as having a value (albeit an empty one), use:

[array]$foo = @() #example where we'd want FALSE to be returned
$foo.PSObject -eq $null

If you want an array which is populated with only null values to be treated as null:

[array]$foo = $null,$null
@($foo | ?{$_.PSObject}).Count -eq 0 

NB: In the above I use $_.PSObject over $_ to avoid [bool]$false, [int]0, [string]'', etc from being filtered out; since here we're focussed solely on nulls.

write newline into a file

the other answers should work. however I wanna mention

from java doc:

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.

reading your method codes, you are about to write String to the file, what you were doing is convert String to raw bytes, then write so I think using FileWriter is not a bad idea.

And for the newline problem, Writer has method .write(String), which is convenient to use.

How to get cookie's expire time

When you create a cookie via PHP die Default Value is 0, from the manual:

If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes)

Otherwise you can set the cookies lifetime in seconds as the third parameter:

http://www.php.net/manual/en/function.setcookie.php

But if you mean to get the remaining lifetime of an already existing cookie, i fear that, is not possible (at least not in a direct way).

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

Either their security certificate has expired, or their hosting is broken/down.

Contact CVSDude and ask them whats up.

It could also be a timeout, because for me their site is exhaustively slow..

Reset input value in angular 2

If you want to clear the input by using the HTML ONLY, then you can do something like this:

<input type="text"
       (keyup)="0"
       #searchCollectorInput
       class="search-metrics"
       placeholder="Find">

Notice the importance of (keyup)=0 and the reference to the input of course.

Then reset it like this:

<span *ngIf="searchCollectorInput.value.length > 0"
      (click)="searchCollectorInput.value = ''"
      class="fa fa-close" ></span>

Calling a phone number in swift

Okay I got help and figured it out. Also I put in a nice little alert system just in case the phone number is not valid. My issue was I was calling it right but the number had spaces and unwanted characters such as ("123 456-7890"). UIApplication only works or accepts if your number is ("1234567890"). So you basically remove the space and invalid characters by making a new variable to pull only the numbers. Then calls those numbers with the UIApplication.

func callSellerPressed (sender: UIButton!){
        var newPhone = ""

        for (var i = 0; i < countElements(busPhone); i++){

            var current:Int = i
            switch (busPhone[i]){
                case "0","1","2","3","4","5","6","7","8","9" : newPhone = newPhone + String(busPhone[i])
                default : println("Removed invalid character.")
            }
        }

        if  (busPhone.utf16Count > 1){

        UIApplication.sharedApplication().openURL(NSURL(string: "tel://" + newPhone)!)
        }
        else{
            let alert = UIAlertView()
            alert.title = "Sorry!"
            alert.message = "Phone number is not available for this business"
            alert.addButtonWithTitle("Ok")
                alert.show()
        }
        }

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

$_SERVER['REMOTE_ADDR'] gives the IP address from which the request was sent to the web server. This is typically the visitor's address, but in your case, it sounds like there is some kind of proxy sitting right before the web server that intercepts the requests, hence to the web server it appears as though the requests are originating from there.

CSS file not refreshing in browser

Do Shift+F5 in Windows. The cache really frustrates in this kind of stuff

Properly Handling Errors in VBA (Excel)

This is what I'm teaching my students tomorrow. After years of looking at this stuff... ie all of the documentation above http://www.cpearson.com/excel/errorhandling.htm comes to mind as an excellent one...

I hope this summarizes it for others. There is an Err object and an active (or inactive) ErrorHandler. Both need to be handled and reset for new errors.

Paste this into a workbook and step through it with F8.

Sub ErrorHandlingDemonstration()

    On Error GoTo ErrorHandler

    'this will error
    Debug.Print (1 / 0)

    'this will also error
    dummy = Application.WorksheetFunction.VLookup("not gonna find me", Range("A1:B2"), 2, True)

    'silly error
    Dummy2 = "string" * 50

    Exit Sub

zeroDivisionErrorBlock:
    maybeWe = "did some cleanup on variables that shouldnt have been divided!"
    ' moves the code execution to the line AFTER the one that errored
    Resume Next

vlookupFailedErrorBlock:
    maybeThisTime = "we made sure the value we were looking for was in the range!"
    ' moves the code execution to the line AFTER the one that errored
    Resume Next

catchAllUnhandledErrors:
    MsgBox(thisErrorsDescription)
    Exit Sub

ErrorHandler:
    thisErrorsNumberBeforeReset = Err.Number
    thisErrorsDescription = Err.Description
    'this will reset the error object and error handling
    On Error GoTo 0
    'this will tell vba where to go for new errors, ie the new ErrorHandler that was previous just reset!
    On Error GoTo ErrorHandler

    ' 11 is the err.number for division by 0
    If thisErrorsNumberBeforeReset = 11 Then
        GoTo zeroDivisionErrorBlock
    ' 1004 is the err.number for vlookup failing
    ElseIf thisErrorsNumberBeforeReset = 1004 Then
        GoTo vlookupFailedErrorBlock
    Else
        GoTo catchAllUnhandledErrors
    End If

End Sub

Check if PHP session has already started

if (session_id() === "") { session_start(); }

hope it helps !

What is the best way to compare floats for almost-equality in Python?

I would agree that Gareth's answer is probably most appropriate as a lightweight function/solution.

But I thought it would be helpful to note that if you are using NumPy or are considering it, there is a packaged function for this.

numpy.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

A little disclaimer though: installing NumPy can be a non-trivial experience depending on your platform.

How do you use the "WITH" clause in MySQL?

'Common Table Expression' feature is not available in MySQL, so you have to go to make a view or temporary table to solve, here I have used a temporary table.

The stored procedure mentioned here will solve your need. If I want to get all my team members and their associated members, this stored procedure will help:

----------------------------------
user_id   |   team_id
----------------------------------
admin     |   NULL
ramu      |   admin
suresh    |   admin
kumar     |   ramu
mahesh    |   ramu
randiv    |   suresh
-----------------------------------

Code:

DROP PROCEDURE `user_hier`//
CREATE DEFINER=`root`@`localhost` PROCEDURE `user_hier`(in team_id varchar(50))
BEGIN
declare count int;
declare tmp_team_id varchar(50);
CREATE TEMPORARY TABLE res_hier(user_id varchar(50),team_id varchar(50))engine=memory;
CREATE TEMPORARY TABLE tmp_hier(user_id varchar(50),team_id varchar(50))engine=memory;
set tmp_team_id = team_id;
SELECT COUNT(*) INTO count FROM user_table WHERE user_table.team_id=tmp_team_id;
WHILE count>0 DO
insert into res_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
insert into tmp_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
select user_id into tmp_team_id from tmp_hier limit 0,1;
select count(*) into count from tmp_hier;
delete from tmp_hier where user_id=tmp_team_id;
end while;
select * from res_hier;
drop temporary table if exists res_hier;
drop temporary table if exists tmp_hier;
end

This can be called using:

mysql>call user_hier ('admin')//

How to revert multiple git commits?

I'm so frustrated that this question can't just be answered. Every other question is in relation to how to revert correctly and preserve history. This question says "I want the head of the branch to point to A, i.e. I want B, C, D, and HEAD to disappear and I want head to be synonymous with A."

git checkout <branch_name>
git reset --hard <commit Hash for A>
git push -f

I learned a lot reading Jakub's post, but some guy in the company (with access to push to our "testing" branch without Pull-Request) pushed like 5 bad commits trying to fix and fix and fix a mistake he made 5 commits ago. Not only that, but one or two Pull Requests were accepted, which were now bad. So forget it, I found the last good commit (abc1234) and just ran the basic script:

git checkout testing
git reset --hard abc1234
git push -f

I told the other 5 guys working in this repo that they better make note of their changes for the last few hours and Wipe/Re-Branch from the latest testing. End of the story.

Permanently Set Postgresql Schema Path

You can set the default search_path at the database level:

ALTER DATABASE <database_name> SET search_path TO schema1,schema2;

Or at the user or role level:

ALTER ROLE <role_name> SET search_path TO schema1,schema2;

Or if you have a common default schema in all your databases you could set the system-wide default in the config file with the search_path option.

When a database is created it is created by default from a hidden "template" database named template1, you could alter that database to specify a new default search path for all databases created in the future. You could also create another template database and use CREATE DATABASE <database_name> TEMPLATE <template_name> to create your databases.

Combine two (or more) PDF's

I've done this with PDFBox. I suppose it works similarly to iTextSharp.

How to show the last queries executed on MySQL?

You can enable a general query log for that sort of diagnostic. Generally you don't log all SELECT queries on a production server though, it's a performance killer.

Edit your MySQL config, e.g. /etc/mysql/my.cnf - look for, or add, a line like this

[mysqld]
log = /var/log/mysql/mysql.log

Restart mysql to pick up that change, now you can

tail -f /var/log/mysql/mysql.log

Hey presto, you can watch the queries as they come in.

How to send email using simple SMTP commands via Gmail?

As no one has mentioned - I would suggest to use great tool for such purpose - swaks

# yum info swaks
Installed Packages
Name        : swaks
Arch        : noarch
Version     : 20130209.0
Release     : 3.el6
Size        : 287 k
Repo        : installed
From repo   : epel
Summary     : Command-line SMTP transaction tester
URL         : http://www.jetmore.org/john/code/swaks
License     : GPLv2+
Description : Swiss Army Knife SMTP: A command line SMTP tester. Swaks can test
            : various aspects of your SMTP server, including TLS and AUTH.

It has a lot of options and can do almost everything you want.

GMAIL: STARTTLS, SSLv3 (and yes, in 2016 gmail still support sslv3)

$ echo "Hello world" | swaks -4 --server smtp.gmail.com:587 --from [email protected] --to [email protected] -tls --tls-protocol sslv3 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying smtp.gmail.com:587...
=== Connected to smtp.gmail.com.
<-  220 smtp.gmail.com ESMTP h8sm76342lbd.48 - gsmtp
 -> EHLO www.example.net
<-  250-smtp.gmail.com at your service, [193.243.156.26]
<-  250-SIZE 35882577
<-  250-8BITMIME
<-  250-STARTTLS
<-  250-ENHANCEDSTATUSCODES
<-  250-PIPELINING
<-  250-CHUNKING
<-  250 SMTPUTF8
 -> STARTTLS
<-  220 2.0.0 Ready to start TLS
=== TLS started with cipher SSLv3:RC4-SHA:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Mountain View/O=Google Inc/CN=smtp.gmail.com"
 ~> EHLO www.example.net
<~  250-smtp.gmail.com at your service, [193.243.156.26]
<~  250-SIZE 35882577
<~  250-8BITMIME
<~  250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
<~  250-ENHANCEDSTATUSCODES
<~  250-PIPELINING
<~  250-CHUNKING
<~  250 SMTPUTF8
 ~> AUTH PLAIN AGFhQxsZXguaGhMGdATGV4X2hoYtYWlsLmNvbQBS9TU1MjQ=
<~  235 2.7.0 Accepted
 ~> MAIL FROM:<[email protected]>
<~  250 2.1.0 OK h8sm76342lbd.48 - gsmtp
 ~> RCPT TO:<[email protected]>
<~  250 2.1.5 OK h8sm76342lbd.48 - gsmtp
 ~> DATA
<~  354  Go ahead h8sm76342lbd.48 - gsmtp
 ~> Date: Wed, 17 Feb 2016 09:49:03 +0000
 ~> To: [email protected]
 ~> From: [email protected]
 ~> Subject: Test message
 ~> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 ~>
 ~> Hello world
 ~>
 ~>
 ~> .
<~  250 2.0.0 OK 1455702544 h8sm76342lbd.48 - gsmtp
 ~> QUIT
<~  221 2.0.0 closing connection h8sm76342lbd.48 - gsmtp
=== Connection closed with remote host.

YAHOO: TLS aka SMTPS, tlsv1.2

$ echo "Hello world" | swaks -4 --server smtp.mail.yahoo.com:465 --from [email protected] --to [email protected] --tlsc --tls-protocol tlsv1_2 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying smtp.mail.yahoo.com:465...
=== Connected to smtp.mail.yahoo.com.
=== TLS started with cipher TLSv1.2:ECDHE-RSA-AES128-GCM-SHA256:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Sunnyvale/O=Yahoo Inc./OU=Information Technology/CN=smtp.mail.yahoo.com"
<~  220 smtp.mail.yahoo.com ESMTP ready
 ~> EHLO www.example.net
<~  250-smtp.mail.yahoo.com
<~  250-PIPELINING
<~  250-SIZE 41697280
<~  250-8 BITMIME
<~  250 AUTH PLAIN LOGIN XOAUTH2 XYMCOOKIE
 ~> AUTH PLAIN AGFhQxsZXguaGhMGdATGV4X2hoYtYWlsLmNvbQBS9TU1MjQ=
<~  235 2.0.0 OK
 ~> MAIL FROM:<[email protected]>
<~  250 OK , completed
 ~> RCPT TO:<[email protected]>
<~  250 OK , completed
 ~> DATA
<~  354 Start Mail. End with CRLF.CRLF
 ~> Date: Wed, 17 Feb 2016 10:08:28 +0000
 ~> To: [email protected]
 ~> From: [email protected]
 ~> Subject: Test message
 ~> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 ~>
 ~> Hello world
 ~>
 ~>
 ~> .
<~  250 OK , completed
 ~> QUIT
<~  221 Service Closing transmission
=== Connection closed with remote host.

I have been using swaks to send email notifications from nagios via gmail for last 5 years without any problem.

How to set a Fragment tag by code?

This is the best way I have found :

   public class MainActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
          // Let's first dynamically add a fragment into a frame container
          getSupportFragmentManager().beginTransaction(). 
              replace(R.id.flContainer, new DemoFragment(), "SOMETAG").
              commit();
          // Now later we can lookup the fragment by tag
          DemoFragment fragmentDemo = (DemoFragment) 
              getSupportFragmentManager().findFragmentByTag("SOMETAG");
        }
    }
}

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

How to handle login pop up window using Selenium WebDriver?

I used IE, then create code like that and works after modification several code:

       public class TestIEBrowser {
                          public static void main(String[] args) throws Exception {
               //Set path of IEDriverServer.exe.
              // Note : IEDriverServer.exe should be In D: drive.
              System.setProperty("webdriver.ie.driver", "path /IEDriverServer.exe");

              // Initialize InternetExplorerDriver Instance.
              WebDriver driver = new InternetExplorerDriver();

              // Load sample calc test URL.
              driver.get("http://...  /");

              //Code to handle Basic Browser Authentication in Selenium.
              Alert aa = driver.switchTo().alert();

              Robot a = new Robot();
              aa.sendKeys("host"+"\\"+"user");  

              a.keyPress(KeyEvent.VK_TAB);
              a.keyRelease(KeyEvent.VK_TAB);
              a.keyRelease(KeyEvent.VK_ADD);                

              setClipboardData("password");

              a.keyPress(KeyEvent.VK_CONTROL);
              a.keyPress(KeyEvent.VK_V);
              a.keyRelease(KeyEvent.VK_V);
              a.keyRelease(KeyEvent.VK_CONTROL);
              //Thread.sleep(5000);
              aa.accept();        




    }

             private static void setClipboardData(String string) {
            // TODO Auto-generated method stub
                        StringSelection stringSelection = new StringSelection(string);                            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
        }
}

docker cannot start on windows

I am using Windows 7 with Docker Toolbox and to fix it just open Docker Quickstart Terminal.

$ docker version Client: Version: 17.05.0-ce API version: 1.29 Go version: go1.7.5 Git commit: 89658be Built: Fri May 5 15:36:11 2017 OS/Arch: windows/amd64

Server: Version: 17.05.0-ce API version: 1.29 (minimum version 1.12) Go version: go1.7.5 Git commit: 89658be Built: Thu May 4 21:43:09 2017 OS/Arch: linux/amd64 Experimental: false

String replace method is not replacing characters

And when I debug this the logic does fall into the sentence.replace.

Yes, and then you discard the return value.

Strings in Java are immutable - when you call replace, it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:

sentence = sentence.replace("and", " ");

This applies to all the methods in String (substring, toLowerCase etc). None of them change the contents of the string.

Note that you don't really need to do this in a condition - after all, if the sentence doesn't contain "and", it does no harm to perform the replacement:

String sentence = "Define, Measure, Analyze, Design and Verify";
sentence = sentence.replace("and", " ");

In Powershell what is the idiomatic way of converting a string to an int?

$source = "number35"

$number=$null

$result = foreach ($_ in $source.ToCharArray()){$digit="0123456789".IndexOf($\_,0);if($digit -ne -1){$number +=$\_}}[int32]$number

Just feed it digits and it wil convert to an Int32

Enable binary mode while restoring a Database from an SQL dump

I had this error once, after running mysqldump on Windows PowerShell like so:

mysqldump -u root p my_db --no-data --no-create-db --no-create-info --routines --triggers --skip-opt --set-gtid-purged=OFF > db_objects.sql

What I did was change it to this (pipe instead to Set-Content):

mysqldump -u root p my_db --no-data --no-create-db --no-create-info --routines --triggers --skip-opt --set-gtid-purged=OFF | Set-Content db_objects.sql

And the problem went away!

How to copy part of an array to another array in C#?

int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
  • a = source array
  • 1 = start index in source array
  • b = destination array
  • 0 = start index in destination array
  • 3 = elements to copy

How to get the CPU Usage in C#?

CMS has it right, but also if you use the server explorer in visual studio and play around with the performance counter tab then you can figure out how to get lots of useful metrics.

How to use Spring Boot with MySQL database and JPA?

I created a project like you did. The structure looks like this

project structure

The Classes are just copy pasted from yours.

I changed the application.properties to this:

spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

But I think your problem is in your pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>

<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Check these files for differences. Hope this helps

Update 1: I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL

jQuery’s .bind() vs. .on()

Internally, .bind maps directly to .on in the current version of jQuery. (The same goes for .live.) So there is a tiny but practically insignificant performance hit if you use .bind instead.

However, .bind may be removed from future versions at any time. There is no reason to keep using .bind and every reason to prefer .on instead.

Angular-cli from css to scss

A brute force change can be applied. This will work to change, but it's a longer process.

Go to the app folder src/app

  1. Open this file: app.component.ts

  2. Change this code styleUrls: ['./app.component.css'] to styleUrls: ['./app.component.scss']

  3. Save and close.

In the same folder src/app

  1. Rename the extension for the app.component.css file to (app.component.scss)

  2. Follow this change for all the other components. (ex. home, about, contact, etc...)

The angular.json configuration file is next. It's located at the project root.

  1. Search and Replace the css change it to (scss).

  2. Save and close.

Lastly, Restart your ng serve -o.

If the compiler complains at you, go over the steps again.

Make sure to follow the steps in app/src closely.

How to Merge Two Eloquent Collections?

Creating a new base collection for each eloquent collection the merge works for me.

$foo = collect(Foo::all());
$bar = collect(Bar::all());
$merged = $foo->merge($bar);

In this case don't have conflits by its primary keys.

PostgreSQL: Why psql can't connect to server?

In my case I had this error, /var/run/postgresql/.s.PGSQL.5433 (note, one number up from the file it was looking for, .s.PGSQL.5432) was present. Tried the instructions at the top of this page but nothing worked.

Turns out there was an old directory for PostGreSQL 12 config files in /etc/postgresql/12, which I deleted, which solved the issue.

Why does corrcoef return a matrix?

Consider using matplotlib.cbook pieces

for example:

import matplotlib.cbook as cbook
segments = cbook.pieces(np.arange(20), 3)
for s in segments:
     print s

How to delete a file after checking whether it exists

If you want to avoid a DirectoryNotFoundException you will need to ensure that the directory of the file does indeed exist. File.Exists accomplishes this. Another way would be to utilize the Path and Directory utility classes like so:

string file = @"C:\subfolder\test.txt";
if (Directory.Exists(Path.GetDirectoryName(file)))
{
    File.Delete(file);
}

UTF-8 text is garbled when form is posted as multipart/form-data

I got stuck with this problem and found that it was the order of the call to

request.setCharacterEncoding("UTF-8");

that was causing the problem. It has to be called before any all call to request.getParameter(), so I made a special filter to use at the top of my filter chain.

https://rogerkeays.com/servletrequest-setcharactercoding-ignored

Angular 2 two way binding using ngModel is not working

instead of ng-model you can use this code:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<input #box (keyup)="0">
    <p>{{box.value}}</p>`,
})
export class AppComponent  {}

inside your app.component.ts

Error: Cannot invoke an expression whose type lacks a call signature

I had the same error message. In my case I had inadvertently mixed the ES6 export default function myFunc syntax with const myFunc = require('./myFunc');.

Using module.exports = myFunc; instead solved the issue.

Python 3 Float Decimal Points/Precision

Try to understand through this below function using python3

def floating_decimals(f_val, dec):
    prc = "{:."+str(dec)+"f}" #first cast decimal as str
    print(prc) #str format output is {:.3f}
    return prc.format(f_val)


print(floating_decimals(50.54187236456456564, 3))

Output is : 50.542

Hope this helps you!

Div with horizontal scrolling only

try this:

HTML:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
</div>

CSS:

.container {
  width: 200px;
  height: 100px;
  display: flex;
  overflow-x: auto;
}

.item {
  width: 100px;
  flex-shrink: 0;
  height: 100px;
}

The white-space: nowrap; property dont let you wrap text. Just see here for an example: https://codepen.io/oezkany/pen/YoVgYK

jQuery lose focus event

Like this:

$(selector).focusout(function () {
    //Your Code
});

Change background color on mouseover and remove it after mouseout

Set the original background-color in you CSS file:

.forum{
    background-color:#f0f;
}?

You don't have to capture the original color in jQuery. Remember that jQuery will alter the style INLINE, so by setting the background-color to null you will get the same result.

$(function() {
    $(".forum").hover(
    function() {
        $(this).css('background-color', '#ff0')
    }, function() {
        $(this).css('background-color', '')
    });
});?

How do I add a new sourceset to Gradle?

This was once written for Gradle 2.x / 3.x in 2016 and is far outdated!! Please have a look at the documented solutions in Gradle 4 and up


To sum up both old answers (get best and minimum viable of both worlds):

some warm words first:

  1. first, we need to define the sourceSet:

    sourceSets {
        integrationTest
    }
    
  2. next we expand the sourceSet from test, therefor we use the test.runtimeClasspath (which includes all dependenciess from test AND test itself) as classpath for the derived sourceSet:

    sourceSets {
        integrationTest {
            compileClasspath += sourceSets.test.runtimeClasspath
            runtimeClasspath += sourceSets.test.runtimeClasspath // ***)
        }
    }
    
    • note) somehow this redeclaration / extend for sourceSets.integrationTest.runtimeClasspath is needed, but should be irrelevant since runtimeClasspath always expands output + runtimeSourceSet, don't get it
  3. we define a dedicated task for just running integration tests:

    task integrationTest(type: Test) {
    }
    
  4. Configure the integrationTest test classes and classpaths use. The defaults from the java plugin use the test sourceSet

    task integrationTest(type: Test) {
        testClassesDir = sourceSets.integrationTest.output.classesDir
        classpath = sourceSets.integrationTest.runtimeClasspath
    }
    
  5. (optional) auto run after test

    integrationTest.dependsOn test
    

  6. (optional) add dependency from check (so it always runs when build or check are executed)

    tasks.check.dependsOn(tasks.integrationTest)
    
  7. (optional) add java,resources to the sourceSet to support auto-detection and create these "partials" in your IDE. i.e. IntelliJ IDEA will auto create sourceSet directories java and resources for each set if it doesn't exist:

    sourceSets {
         integrationTest {
             java
             resources
         }
    }
    

tl;dr

apply plugin: 'java'

// apply the runtimeClasspath from "test" sourceSet to the new one
// to include any needed assets: test, main, test-dependencies and main-dependencies
sourceSets {
    integrationTest {
        // not necessary but nice for IDEa's
        java
        resources

        compileClasspath += sourceSets.test.runtimeClasspath
        // somehow this redeclaration is needed, but should be irrelevant
        // since runtimeClasspath always expands compileClasspath
        runtimeClasspath += sourceSets.test.runtimeClasspath
    }
}

// define custom test task for running integration tests
task integrationTest(type: Test) {
    testClassesDir = sourceSets.integrationTest.output.classesDir
    classpath = sourceSets.integrationTest.runtimeClasspath
}
tasks.integrationTest.dependsOn(tasks.test)

referring to:

Unfortunatly, the example code on github.com/gradle/gradle/subprojects/docs/src/samples/java/customizedLayout/build.gradle or …/gradle/…/withIntegrationTests/build.gradle seems not to handle this or has a different / more complex / for me no clearer solution anyway!

How to check if JSON return is empty with jquery

Just test if the array is empty.

$.getJSON(url,function(json){
    if ( json.length == 0 ) {
        console.log("NO DATA!")
    }
});

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

The Python 3 range() object doesn't produce numbers immediately; it is a smart sequence object that produces numbers on demand. All it contains is your start, stop and step values, then as you iterate over the object the next integer is calculated each iteration.

The object also implements the object.__contains__ hook, and calculates if your number is part of its range. Calculating is a (near) constant time operation *. There is never a need to scan through all possible integers in the range.

From the range() object documentation:

The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).

So at a minimum, your range() object would do:

class my_range:
    def __init__(self, start, stop=None, step=1, /):
        if stop is None:
            start, stop = 0, start
        self.start, self.stop, self.step = start, stop, step
        if step < 0:
            lo, hi, step = stop, start, -step
        else:
            lo, hi = start, stop
        self.length = 0 if lo > hi else ((hi - lo - 1) // step) + 1

    def __iter__(self):
        current = self.start
        if self.step < 0:
            while current > self.stop:
                yield current
                current += self.step
        else:
            while current < self.stop:
                yield current
                current += self.step

    def __len__(self):
        return self.length

    def __getitem__(self, i):
        if i < 0:
            i += self.length
        if 0 <= i < self.length:
            return self.start + i * self.step
        raise IndexError('my_range object index out of range')

    def __contains__(self, num):
        if self.step < 0:
            if not (self.stop < num <= self.start):
                return False
        else:
            if not (self.start <= num < self.stop):
                return False
        return (num - self.start) % self.step == 0

This is still missing several things that a real range() supports (such as the .index() or .count() methods, hashing, equality testing, or slicing), but should give you an idea.

I also simplified the __contains__ implementation to only focus on integer tests; if you give a real range() object a non-integer value (including subclasses of int), a slow scan is initiated to see if there is a match, just as if you use a containment test against a list of all the contained values. This was done to continue to support other numeric types that just happen to support equality testing with integers but are not expected to support integer arithmetic as well. See the original Python issue that implemented the containment test.


* Near constant time because Python integers are unbounded and so math operations also grow in time as N grows, making this a O(log N) operation. Since it’s all executed in optimised C code and Python stores integer values in 30-bit chunks, you’d run out of memory before you saw any performance impact due to the size of the integers involved here.

Function vs. Stored Procedure in SQL Server

              STORE PROCEDURE                 FUNCTION (USER DEFINED FUNCTION)    
 * Procedure can return 0, single or   | * Function can return only single value   
   multiple values.                    |
                                       |
 * Procedure can have input, output    | * Function  can have only input 
   parameters.                         |   parameters.         
                                       |
 * Procedure cannot be called from     | * Functions can be called from 
   function.                           |   procedure.
                                       |
 * Procedure allows select as well as  | * Function allows only select statement 
   DML statement in it.                |   in it.
                                       |
 * Exception can be handled by         | * Try-catch block cannot be used in a 
   try-catch block in a procedure.     |   function.
                                       |
 * We can go for transaction management| * We can not go for transaction 
   in procedure.                       |   management in function.
                                       |
 * Procedure cannot be utilized in a   | * Function can be embedded in a select 
   select statement                    |   statement.
                                       |
 * Procedure can affect the state      | * Function can not affect the state 
   of database means it can perform    |   of database means it can not    
   CRUD operation on database.         |   perform CRUD operation on 
                                       |   database. 
                                       |
 * Procedure can use temporary tables. | * Function can not use 
                                       |   temporary tables. 
                                       |
 * Procedure can alter the server      | * Function can not alter the  
   environment parameters.             |   environment parameters.
                                       |   
 * Procedure can use when we want      | * Function can use when we want
   instead is to group a possibly-     |   to compute and return a value
   complex set of SQL statements.      |   for use in other SQL 
                                       |   statements.

How to import a SQL Server .bak file into MySQL?

Although my MySQL background is limited, I don't think you have much luck doing that. However, you should be able to migrate over all of your data by restoring the db to a MSSQL server, then creating a SSIS or DTS package to send your tables and data to the MySQL server.

hope this helps

Converting between datetime, Timestamp and datetime64

Welcome to hell.

You can just pass a datetime64 object to pandas.Timestamp:

In [16]: Timestamp(numpy.datetime64('2012-05-01T01:00:00.000000'))
Out[16]: <Timestamp: 2012-05-01 01:00:00>

I noticed that this doesn't work right though in NumPy 1.6.1:

numpy.datetime64('2012-05-01T01:00:00.000000+0100')

Also, pandas.to_datetime can be used (this is off of the dev version, haven't checked v0.9.1):

In [24]: pandas.to_datetime('2012-05-01T01:00:00.000000+0100')
Out[24]: datetime.datetime(2012, 5, 1, 1, 0, tzinfo=tzoffset(None, 3600))

How to create war files

You can use Ant to set up, compile, WAR, and deploy your solution.

<target name="default" depends="setup,compile,buildwar,deploy"></target>

You can then execute one click in Eclipse to run that Ant target. Here are examples of each of the steps:

Preconditions

We'll assume that you have your code organized like:

  • ${basedir}/src: Java files, properties, XML config files
  • ${basedir}/web: Your JSP files
  • ${basedir}/web/lib: Any JARs required at runtime
  • ${basedir}/web/META-INF: Your manifest
  • ${basedir}/web/WEB-INF: Your web.xml files

Set up

Define a setup task that creates the distribution directory and copies any artifacts that need to be WARred directly:

<target name="setup">
    <mkdir dir="dist" />
    <echo>Copying web into dist</echo>
    <copydir dest="dist/web" src="web" />
    <copydir dest="dist/web/WEB-INF/lib" src="${basedir}/../web/WEB-INF/lib" />
</target>

Compile

Build your Java files into classes and copy over any non-Java artifacts that reside under src but need to be available at runtime (e.g. properties, XML files, etc.):

<target name="compile">
    <delete dir="${dist.dir}/web/WEB-INF/classes" />
    <mkdir dir="${dist.dir}/web/WEB-INF/classes" />
    <javac destdir="${dist.dir}/web/WEB-INF/classes" srcdir="src">
        <classpath>
            <fileset dir="${basedir}/../web/WEB-INF/lib">
                  <include name="*" />
            </fileset>
        </classpath>
    </javac>
    <copy todir="${dist.dir}/web/WEB-INF/classes">
        <fileset dir="src">
            <include name="**/*.properties" />
            <include name="**/*.xml" />
        </fileset>
    </copy>
</target>

Build WAR

Create the WAR itself:

<target name="buildwar">
    <war basedir="${basedir}/dist/web" destfile="My.war"
     webxml="${basedir}/dist/web/WEB-INF/web.xml">
        <exclude name="WEB-INF/**" />
        <webinf dir="${basedir}/dist/web/WEB-INF/">
            <include name="**/*.jar" />
        </webinf>
    </war>
</target>

Deploy

Finally, you can set up a task to deploy the WAR directly into your Tomcat deploy location:

<target name="deploy">
    <copy file="My.war" todir="${tomcat.deploydir}" />
</target>

Click and go!

Once all this is set up, simply launching the default target from Eclipse will compile, WAR, and deploy your solution.

The advantage of this approach is that it will work outside Eclipse as well as within Eclipse and can be used to easily share your deployment strategy (e.g. via source control) with other developers who are also working on your project.

php pdo: get the columns name of a table

My contribution ONLY for SQLite:

/**
 * Returns an array of column names for a given table.
 * Arg. $dsn should be replaced by $this->dsn in a class definition.
 *
 * @param string $dsn Database connection string, 
 * e.g.'sqlite:/home/user3/db/mydb.sq3'
 * @param string $table The name of the table
 * 
 * @return string[] An array of table names
 */
public function getTableColumns($dsn, $table) {
   $dbh = new \PDO($dsn);
   return $dbh->query('PRAGMA table_info(`'.$table.'`)')->fetchAll(\PDO::FETCH_COLUMN, 1);
}

How to unescape HTML character entities in Java?

I have used the Apache Commons StringEscapeUtils.unescapeHtml4() for this:

Unescapes a string containing entity escapes to a string containing the actual Unicode characters corresponding to the escapes. Supports HTML 4.0 entities.

JavaScript backslash (\) in variables is causing an error

You have to escape each \ to be \\:

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

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

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

I think the scenario is like:

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

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

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

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

var ttt = "aa ///\";

Hence, we assume the asker having problem with escaping.

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

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

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

Now, you only need to do is

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

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

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

When should you use a class vs a struct in C++?

Class.

Class members are private by default.

class test_one {
    int main_one();
};

Is equivalent to

class test_one {
  private:
    int main_one();
};

So if you try

int two = one.main_one();

We will get an error: main_one is private because its not accessible. We can solve it by initializing it by specifying its a public ie

class test_one {
  public:
    int main_one();
};

Struct.

A struct is a class where members are public by default.

struct test_one {
    int main_one;
};

Means main_one is private ie

class test_one {
  public:
    int main_one;
};

I use structs for data structures where the members can take any value, it's easier that way.

Bootstrap 3 - disable navbar collapse

The following solution worked for me in Bootstrap 3.3.4:

CSS:

/*no collapse*/

.navbar-collapse.collapse.off {
    display: block!important;
}
.navbar-collapse.collapse.off ul {
    margin: 0;
    padding: 0;
}

.navbar-nav.no-collapse>li,
.navbar-nav.no-collapse {
    float: left !important;
}

.navbar-right.no-collapse {
    float: right!important;
}

then add the .no-collapse class to each of the lists and the .off class to the main container. Here is an example written in jade:

nav.navbar.navbar-default.navbar-fixed-top
        .container-fluid
            .collapse.navbar-collapse.off
                ul.nav.navbar-nav.no-collapse
                    li
                        a(href='#' class='glyph')
                            i(class='glyphicon glyphicon-info-sign')
                ul.nav.navbar-nav.navbar-right.no-collapse
                    li.dropdown
                        a.dropdown-toggle(href='#', data-toggle='dropdown' role='button' aria-expanded='false')
                            | Tools
                            span.caret
                        ul.dropdown-menu(role='menu')
                            li
                                a(href='#') Tool #1
                    li
                        a(href='#')
                            | Logout

display:inline vs display:block

Block Elements: Elements liked div, p, headings are block level. They start from new line and occupy full width of parent element. Inline Elements: Elements liked b, i, span, img are inline level. They never start from new line and occupy width of content.

Address validation using Google Maps API

Google basis (free) does not provide address verification (Geocoding) as there is no UK postcode license.

This means postcode searches are very in-accurate. The proximity search is very poor, even for town searches, often not recognising locations.

This is why Google have a premier and a enterprise solution which still is more expensive and not as good as business mapping specialists like bIng and Via Michelin who also have API's.

As a free lance developer, so serious business would use Google as the system is weak and really provides a watered down solution.

When to use IMG vs. CSS background-image?

Just a small one to add, you should use the img tag if you want users to be able to 'right click' and 'save-image'/'save-picture', so if you intend to provide the image as a resource for others.

Using background image will (as far as I'm aware on most browsers) disable the option to save the image directly.

Update multiple rows with different values in a single SQL query

I could not make @Clockwork-Muse work actually. But I could make this variation work:

WITH Tmp AS (SELECT * FROM (VALUES (id1, newsPosX1, newPosY1), 
                                   (id2, newsPosX2, newPosY2),
                                   ......................... ,
                                   (idN, newsPosXN, newPosYN)) d(id, px, py))

UPDATE t

SET posX = (SELECT px FROM Tmp WHERE t.id = Tmp.id),
    posY = (SELECT py FROM Tmp WHERE t.id = Tmp.id)

FROM TableToUpdate t

I hope this works for you too!

Plot two histograms on single chart with matplotlib

You should use bins from the values returned by hist:

import numpy as np
import matplotlib.pyplot as plt

foo = np.random.normal(loc=1, size=100) # a normal distribution
bar = np.random.normal(loc=-1, size=10000) # a normal distribution

_, bins, _ = plt.hist(foo, bins=50, range=[-6, 6], normed=True)
_ = plt.hist(bar, bins=bins, alpha=0.5, normed=True)

Two matplotlib histograms with same binning

Number of lines in a file in Java

This is the fastest version I have found so far, about 6 times faster than readLines. On a 150MB log file this takes 0.35 seconds, versus 2.40 seconds when using readLines(). Just for fun, linux' wc -l command takes 0.15 seconds.

public static int countLinesOld(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
}

EDIT, 9 1/2 years later: I have practically no java experience, but anyways I have tried to benchmark this code against the LineNumberReader solution below since it bothered me that nobody did it. It seems that especially for large files my solution is faster. Although it seems to take a few runs until the optimizer does a decent job. I've played a bit with the code, and have produced a new version that is consistently fastest:

public static int countLinesNew(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];

        int readChars = is.read(c);
        if (readChars == -1) {
            // bail out if nothing to read
            return 0;
        }

        // make it easy for the optimizer to tune this loop
        int count = 0;
        while (readChars == 1024) {
            for (int i=0; i<1024;) {
                if (c[i++] == '\n') {
                    ++count;
                }
            }
            readChars = is.read(c);
        }

        // count remaining characters
        while (readChars != -1) {
            System.out.println(readChars);
            for (int i=0; i<readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
            readChars = is.read(c);
        }

        return count == 0 ? 1 : count;
    } finally {
        is.close();
    }
}

Benchmark resuls for a 1.3GB text file, y axis in seconds. I've performed 100 runs with the same file, and measured each run with System.nanoTime(). You can see that countLinesOld has a few outliers, and countLinesNew has none and while it's only a bit faster, the difference is statistically significant. LineNumberReader is clearly slower.

Benchmark Plot

Fastest way to check if a string matches a regexp in ruby?

Depending on how complicated your regular expression is, you could possibly just use simple string slicing. I'm not sure about the practicality of this for your application or whether or not it would actually offer any speed improvements.

'testsentence'['stsen']
=> 'stsen' # evaluates to true
'testsentence'['koala']
=> nil # evaluates to false

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

Wherever you invoke a generator from within a generator you need a "pump" to re-yield the values: for v in inner_generator: yield v. As the PEP points out there are subtle complexities to this which most people ignore. Non-local flow-control like throw() is one example given in the PEP. The new syntax yield from inner_generator is used wherever you would have written the explicit for loop before. It's not merely syntactic sugar, though: It handles all of the corner cases that are ignored by the for loop. Being "sugary" encourages people to use it and thus get the right behaviors.

This message in the discussion thread talks about these complexities:

With the additional generator features introduced by PEP 342, that is no longer the case: as described in Greg's PEP, simple iteration doesn't support send() and throw() correctly. The gymnastics needed to support send() and throw() actually aren't that complex when you break them down, but they aren't trivial either.

I can't speak to a comparison with micro-threads, other than to observe that generators are a type of paralellism. You can consider the suspended generator to be a thread which sends values via yield to a consumer thread. The actual implementation may be nothing like this (and the actual implementation is obviously of great interest to the Python developers) but this does not concern the users.

The new yield from syntax does not add any additional capability to the language in terms of threading, it just makes it easier to use existing features correctly. Or more precisely it makes it easier for a novice consumer of a complex inner generator written by an expert to pass through that generator without breaking any of its complex features.

Escape @ character in razor view engine

You can use @@ for this purpose. Like var email = firstName + '\@@' + domain;

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

Difference between logical addresses, and physical addresses?

Logical address:- Logical address generated by the CPU . when we are give the problem to the computer then our computer pass the problem to the processor through logical address , which we are not seen this address called logical address .

Physical address :- when our processor create process and solve our problem then we store data in secondary memory through address called physical address

Why do you create a View in a database?

Here is how to use a View along with permissions to limit the columns a user can update in the table.

/* This creates the view, limiting user to only 2 columns from MyTestTable */
CREATE VIEW dbo.myTESTview 
WITH SCHEMABINDING AS
SELECT ID, Quantity FROM dbo.MyTestTable;

/* This uses the view to execute an update on the table MyTestTable */
UPDATE dbo.myTESTview
SET Quantity = 7
WHERE ID = 1

Custom Adapter for List View

public class CustomAdapter extends BaseAdapter{

    ArrayList<BookPojo> data;
    Context ctx;
    int index=0;

    public CustomAdapter(ArrayList<BookPojo> data, Context ctx) {
        super();
        this.data = data;
        this.ctx = ctx;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertview, ViewGroup parent) {
        // TODO Auto-generated method stub
        View v=convertview;

        if(v==null){
            LayoutInflater vi=LayoutInflater.from(ctx);
            v=vi.inflate(R.layout.messgeview,null);

        }

        RelativeLayout rlmessage=(RelativeLayout)v.findViewById(R.id.rlmessgeview);

        TextView tvisdn=(TextView)v.findViewById(R.id.tvisdn);
        TextView tvtitle=(TextView)v.findViewById(R.id.tvtitle);
        TextView tvauthor=(TextView)v.findViewById(R.id.tvauthor);
        TextView tvprice=(TextView)v.findViewById(R.id.tvprice);

        BookPojo bpj=data.get(position);

        tvisdn.setText(bpj.isdn+"");
        tvtitle.setText(bpj.title);
        tvauthor.setText(bpj.author);
        tvprice.setText(bpj.price+"");

        if(index%2==0)
        {
            rlmessage.setBackgroundColor(Color.BLUE);
        }
        else
        {
            rlmessage.setBackgroundColor(Color.YELLOW);

        }

        index++;

        return v;
    }
}

Change working directory in my current shell context when running Node script

There is no built-in method for Node to change the CWD of the underlying shell running the Node process.

You can change the current working directory of the Node process through the command process.chdir().

var process = require('process');
process.chdir('../');

When the Node process exists, you will find yourself back in the CWD you started the process in.

How to set headers in http get request?

Go's net/http package has many functions that deal with headers. Among them are Add, Del, Get and Set methods. The way to use Set is:

func yourHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("header_name", "header_value")
}

Run a vbscript from another vbscript

In case you don't want to get mad with spaces in arguments and want to use variables try this:

objshell.run "cscript ""99 Writelog.vbs"" /r:" &  r & " /f:""" & wscript.scriptname & """ /c:""" & c & ""

where

r=123
c="Whatever comment you like"

NuGet Package Restore Not Working

For me, I had an empty tag NuGetPackageImportStamp in .csproj

<NuGetPackageImportStamp>
    </NuGetPackageImportStamp>

It should ideally contain some valid GUID.

Removing this tag and then "Restore Nugets" worked for me.

set font size in jquery

Try:

$("#"+styleTarget).css({ 'font-size': $(this).val() });

By putting the value in quotes, it becomes a string, and "+$(this).val()+"px is definitely not close to a font value. There are a couple of ways of setting the style properties of an element:

Using a map:

$("#elem").css({
    fontSize: 20
});

Using key and value parameters:

All of these are valid.

$("#elem").css("fontSize", 20);
$("#elem").css("fontSize", "20px");
$("#elem").css("font-size", "20");
$("#elem").css("font-size", "20px");

You can replace "fontSize" with "font-size" but it will have to be quoted then.

Test if string is URL encoded in PHP

I am using the following test to see if strings have been urlencoded:

if(urlencode($str) != str_replace(['%','+'], ['%25','%2B'], $str))

If a string has already been urlencoded, the only characters that will changed by double encoding are % (which starts all encoded character strings) and + (which replaces spaces.) Change them back and you should have the original string.

Let me know if this works for you.

Using an index to get an item, Python

values = ['A', 'B', 'C', 'D', 'E']
values[0] # returns 'A'
values[2] # returns 'C'
# etc.