Programs & Examples On #Gtkbuilder

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

How to retrieve GET parameters from JavaScript

var getQueryParam = function(param) {
    var found;
    window.location.search.substr(1).split("&").forEach(function(item) {
        if (param ==  item.split("=")[0]) {
            found = item.split("=")[1];
        }
    });
    return found;
};

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

The problem in my case was that the database name was incorrect.
I solved the problem by referring the correct database name in the field as below

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDatabase</property>

Why should the static field be accessed in a static way?

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

Not on an instance as in

m.MILLISECONDS;

Edit To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.

How to get domain root url in Laravel 4?

UPDATE (2017-07-12)

A better solution is actually to use Request::getHost()

Previous answer:

I just checked and Request::root(); does return http://www.example.com in my case, no matter which route I'm on. You can then do the following to strip off the http:// part:

if (starts_with(Request::root(), 'http://'))
{
    $domain = substr (Request::root(), 7); // $domain is now 'www.example.com'
}

You may want to double check or post more code (routes.php, controller code, ...) if the problem persists.

Another solution is to simply use $_SERVER['SERVER_NAME'].

Playing Sound In Hidden Tag

I hope people would allow them to turn things such as music off, as for button clicks, Sometimes, those are pretty cool. Use the

<audio controls autoplay hidden="hidden"> <source src="*file here*" type="*file extension (.mp3 .ogg etc.)*"> <!--This displays an error to users that don't have it supported--> Your browser does not support the audio element. </audio>

As you can see, I don't like to repeat myself much, But I decided with the hidden tag.

Hope this helps.

Increasing nesting function calls limit

Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.

I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.

How can I trigger a JavaScript event click

What

 l.onclick();

does is exactly calling the onclick function of l, that is, if you have set one with l.onclick = myFunction;. If you haven't set l.onclick, it does nothing. In contrast,

 l.click();

simulates a click and fires all event handlers, whether added with l.addEventHandler('click', myFunction);, in HTML, or in any other way.

iReport not starting using JRE 8

There's another way if you don't want to have older Java versions installed you can do the following:

1) Download the iReport-5.6.0.zip from https://sourceforge.net/projects/ireport/files/iReport/iReport-5.6.0/

2) Download jre-7u67-windows-x64.tar.gz (the one packed in a tar) from https://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html

3) Extract the iReport and in the extracted folder that contains the bin and etc folders throw in the jre. For example if you unpack twice the jre-7u67-windows-x64.tar.gz you end up with a folder named jre1.7.0_67. Put that folder in the iReport-5.6.0 directory:

enter image description here

and then go into the etc folder and edit the file ireport.conf and add the following line into it:

For Windows jdkhome=".\jre1.7.0_67"

For Linux jdkhome="./jre1.7.0_67"

Note : jre version may change! according to your download of 1.7

enter image description here

now if you run the ireport_w.exe from the bin folder in the iReport directory it should load just fine.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

ValueError when checking if variable is None or numpy.array

To stick to == without consideration of the other type, the following is also possible.
type(a) == type(None)

How to fix C++ error: expected unqualified-id

Semicolon should be at the end of the class definition rather than after the name:

class WordGame
{
};

How to add a 'or' condition in #ifdef

May use this-

#if defined CONDITION1 || defined CONDITION2
//your code here
#endif

This also does the same-

#if defined(CONDITION1) || defined(CONDITION2)
//your code here
#endif

Further-

  • AND: #if defined CONDITION1 && defined CONDITION2
  • XOR: #if defined CONDITION1 ^ defined CONDITION2
  • AND NOT: #if defined CONDITION1 && !defined CONDITION2

How to run an application as "run as administrator" from the command prompt?

Try this:

runas.exe /savecred /user:administrator "%sysdrive%\testScripts\testscript1.ps1" 

It saves the password the first time and never asks again. Maybe when you change the administrator password you will be prompted again.

How can I access a hover state in reactjs?

I know the accepted answer is great but for anyone who is looking for a hover like feel you can use setTimeout on mouseover and save the handle in a map (of let's say list ids to setTimeout Handle). On mouseover clear the handle from setTimeout and delete it from the map

onMouseOver={() => this.onMouseOver(someId)}
onMouseOut={() => this.onMouseOut(someId)

And implement the map as follows:

onMouseOver(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = setTimeout(() => {
    scrollPreviewToComponentId(listId);
  }, 1000); // Replace 1000ms with any time you feel is good enough for your hover action
  this.hoverHandleMap[listId] = handle;
}

onMouseOut(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = this.hoverHandleMap[listId];
  clearTimeout(handle);
  delete this.hoverHandleMap[listId];
}

And the map is like so,

hoverHandleMap: { [listId: string]: NodeJS.Timeout } = {};

I prefer onMouseOver and onMouseOut because it also applies to all the children in the HTMLElement. If this is not required you may use onMouseEnter and onMouseLeave respectively.

How to check if a service is running on Android?

Got it!

You MUST call startService() for your service to be properly registered and passing BIND_AUTO_CREATE will not suffice.

Intent bindIntent = new Intent(this,ServiceTask.class);
startService(bindIntent);
bindService(bindIntent,mConnection,0);

And now the ServiceTools class:

public class ServiceTools {
    private static String LOG_TAG = ServiceTools.class.getName();

    public static boolean isServiceRunning(String serviceClassName){
        final ActivityManager activityManager = (ActivityManager)Application.getContext().getSystemService(Context.ACTIVITY_SERVICE);
        final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        for (RunningServiceInfo runningServiceInfo : services) {
            if (runningServiceInfo.service.getClassName().equals(serviceClassName)){
                return true;
            }
        }
        return false;
     }
}

jQuery .val change doesn't change input value

$('#link').prop('value', 'new value');

Explanation: Attr will work on jQuery 1.6 but as of jQuery 1.6.1 things have changed. In the majority of cases, prop() does what attr() used to do. Replacing calls to attr() with prop() in your code will generally work. Attr will give you the value of element as it was defined in the html on page load and prop gives the updated values of elements which are modified via jQuery.

Spring cron expression for every after 30 minutes

in web app java spring what worked for me

cron="0 0/30 * * * ?"

This will trigger on for example 10:00AM then 10:30AM etc...

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/task 
    http://www.springframework.org/schema/task/spring-task.xsd">

    <beans profile="cron">
        <bean id="executorService" class="java.util.concurrent.Executors" factory-method="newFixedThreadPool">
            <beans:constructor-arg value="5" />
        </bean>

        <task:executor id="threadPoolTaskExecutor" pool-size="5" />
        <task:annotation-driven executor="executorService" />

        <beans:bean id="expireCronJob" class="com.cron.ExpireCron"/>

        <task:scheduler id="serverScheduler" pool-size="5"/>
        <task:scheduled-tasks scheduler="serverScheduler">
            <task:scheduled ref="expireCronJob" method="runTask" cron="0 0/30 * * * ?"/> <!-- every thirty minute -->
        </task:scheduled-tasks>

    </beans>

</beans>

I dont know why but this is working on my local develop and production, but other changes if i made i have to be careful because it may work local and on develop but not on production

What should a Multipart HTTP request with multiple files look like?

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

how to measure running time of algorithms in python

For small algorithms you can use the module timeit from python documentation:

def test():
    "Stupid test function"
    L = []
    for i in range(100):
        L.append(i)

if __name__=='__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit()

Less accurately but still valid you can use module time like this:

from time import time
t0 = time()
call_mifuntion_vers_1()
t1 = time()
call_mifunction_vers_2()
t2 = time()

print 'function vers1 takes %f' %(t1-t0)
print 'function vers2 takes %f' %(t2-t1)

Get selected key/value of a combo box using jQuery

<select name="foo" id="foo">
 <option value="1">a</option>
 <option value="2">b</option>
 <option value="3">c</option>
  </select>
  <input type="button" id="button" value="Button" />
  });
  <script> ("#foo").val() </script>

which returns 1 if you have selected a and so on..

Python list iterator behavior and next(iterator)

What you see is the interpreter echoing back the return value of next() in addition to i being printed each iteration:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    next(a)
... 
0
1
2
3
4
5
6
7
8
9

So 0 is the output of print(i), 1 the return value from next(), echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.

If you assign the output of next() things work as expected:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    _ = next(a)
... 
0
2
4
6
8

or print extra information to differentiate the print() output from the interactive interpreter echo:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print('Printing: {}'.format(i))
...    next(a)
... 
Printing: 0
1
Printing: 2
3
Printing: 4
5
Printing: 6
7
Printing: 8
9

In other words, next() is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.

init-param and context-param

What is the difference between <init-param> and <context-param> !?

Single servlet versus multiple servlets.

Other Answers give details, but here is the summary:

A web app, that is, a “context”, is made up of one or more servlets.

  • <init-param> defines a value available to a single specific servlet within a context.
  • <context-param> defines a value available to all the servlets within a context.

How to push changes to github after jenkins build completes?

I followed the below Steps. It worked for me.

In Jenkins execute shell under Build, creating a file and trying to push that file from Jenkins workspace to GitHub.

enter image description here

Download Git Publisher Plugin and Configure as shown below snapshot.

enter image description here

Click on Save and Build. Now you can check your git repository whether the file was pushed successfully or not.

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

If you have just one query I don't know how to set timeout on T-SQL level.

However if you have a few queries (i.e. collecting data into temporary tables) inside stored procedure you can just control time of execution with GETDATE(), DATEDIFF() and a few INT variables storing time of execution of each part.

Identify duplicate values in a list in Python

These answers are O(n), so a little more code than using mylist.count() but much more efficient as mylist gets longer

If you just want to know the duplicates, use collections.Counter

from collections import Counter
mylist = [20, 30, 25, 20]
[k for k,v in Counter(mylist).items() if v>1]

If you need to know the indices,

from collections import defaultdict
D = defaultdict(list)
for i,item in enumerate(mylist):
    D[item].append(i)
D = {k:v for k,v in D.items() if len(v)>1}

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

From Apple documentation

If you’re developing a new app, you should use HTTPS exclusively. If you have an existing app, you should use HTTPS as much as you can right now, and create a plan for migrating the rest of your app as soon as possible. In addition, your communication through higher-level APIs needs to be encrypted using TLS version 1.2 with forward secrecy. If you try to make a connection that doesn't follow this requirement, an error is thrown. If your app needs to make a request to an insecure domain, you have to specify this domain in your app's Info.plist file.

To Bypass App Transport Security:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

To allow all insecure domains

<key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

Read More: Configuring App Transport Security Exceptions in iOS 9 and OSX 10.11

Downloading an entire S3 bucket?

Here is some stuff to download all buckets, list them, list their contents.

    //connection string
    private static void dBConnection() {
    app.setAwsCredentials(CONST.getAccessKey(), CONST.getSecretKey());
    conn = new AmazonS3Client(app.getAwsCredentials());
    app.setListOfBuckets(conn.listBuckets());
    System.out.println(CONST.getConnectionSuccessfullMessage());
    }

    private static void downloadBucket() {

    do {
        for (S3ObjectSummary objectSummary : app.getS3Object().getObjectSummaries()) {
            app.setBucketKey(objectSummary.getKey());
            app.setBucketName(objectSummary.getBucketName());
            if(objectSummary.getKey().contains(CONST.getDesiredKey())){
                //DOWNLOAD
                try 
                {
                    s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
                    s3Client.getObject(
                            new GetObjectRequest(app.getBucketName(),app.getBucketKey()),
                            new File(app.getDownloadedBucket())
                            );
                } catch (IOException e) {
                    e.printStackTrace();
                }

                do
                {
                     if(app.getBackUpExist() == true){
                        System.out.println("Converting back up file");
                        app.setCurrentPacsId(objectSummary.getKey());
                        passIn = app.getDataBaseFile();
                        CONVERT= new DataConversion(passIn);
                        System.out.println(CONST.getFileDownloadedMessage());
                    }
                }
                while(app.getObjectExist()==true);

                if(app.getObjectExist()== false)
                {
                    app.setNoObjectFound(true);
                }
            }
        }
        app.setS3Object(conn.listNextBatchOfObjects(app.getS3Object()));
    } 
    while (app.getS3Object().isTruncated());
}

/----------------------------Extension Methods-------------------------------------/

//Unzip bucket after download 
public static void unzipBucket() throws IOException {
    unzip = new UnZipBuckets();
    unzip.unZipIt(app.getDownloadedBucket());
    System.out.println(CONST.getFileUnzippedMessage());
}

//list all S3 buckets
public static void listAllBuckets(){
    for (Bucket bucket : app.getListOfBuckets()) {
        String bucketName = bucket.getName();
        System.out.println(bucketName + "\t" + StringUtils.fromDate(bucket.getCreationDate()));
    }
}

//Get the contents from the auto back up bucket
public static void listAllBucketContents(){     
    do {
        for (S3ObjectSummary objectSummary : app.getS3Object().getObjectSummaries()) {
            if(objectSummary.getKey().contains(CONST.getDesiredKey())){
                System.out.println(objectSummary.getKey() + "\t" + objectSummary.getSize() + "\t" + StringUtils.fromDate(objectSummary.getLastModified()));
                app.setBackUpCount(app.getBackUpCount() + 1);   
            }
        }
        app.setS3Object(conn.listNextBatchOfObjects(app.getS3Object()));
    } 
    while (app.getS3Object().isTruncated());
    System.out.println("There are a total of : " + app.getBackUpCount() + " buckets.");
}

}

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

Here's a quick and dirty example of how a class could fire different versions of a save method depending on which operating system it's being executed on using getattr().

import os

class Log(object):
    def __init__(self):
        self.os = os.name
    def __getattr__(self, name):
        """ look for a 'save' attribute, or just 
          return whatever attribute was specified """
        if name == 'save':
            try:
                # try to dynamically return a save 
                # method appropriate for the user's system
                return getattr(self, self.os)
            except:
                # bail and try to return 
                # a default save method
                return getattr(self, '_save')
        else:
            return getattr(self, name)

    # each of these methods could have save logic specific to 
    # the system on which the script is executed
    def posix(self): print 'saving on a posix machine'
    def nt(self): print 'saving on an nt machine'
    def os2(self): print 'saving on an os2 machine'
    def ce(self): print 'saving on a ce machine'
    def java(self): print 'saving on a java machine'
    def riscos(self): print 'saving on a riscos machine'
    def _save(self): print 'saving on an unknown operating system'

    def which_os(self): print os.name

Now let's use this class in an example:

logger = Log()

# Now you can do one of two things:
save_func = logger.save
# and execute it, or pass it along 
# somewhere else as 1st class:
save_func()

# or you can just call it directly:
logger.save()

# other attributes will hit the else 
# statement and still work as expected
logger.which_os()

How to call a method in another class of the same package?

Do it in this format:

classmehodisin.methodname();

For example:

MyClass1.clearscreen();

I hope this helped.` Note:The method must be static.

Programmatically getting the MAC of an Android device

I think I just found a way to read MAC addresses without LOCATION permission: Run ip link and parse its output. (you could probably do the similar by looking at this binary's source code)

Click through div to underlying elements

Yes, you CAN force overlapping layers to pass through (ignore) click events.
PLUS you CAN have specific children excluded from this behavior...

You can do this, using pointer-events

pointer-events influences the reaction to click-, tap-, scroll- und hover events.


In a layer that should ignore / pass-through mentioned events you set

pointer-events: none; 

Children of that unresponsive layer that need to react mouse / tap events again need:

pointer-events: auto; 

That second part is very helpful if you work with multiple overlapping div layers (probably some parents being transparent), where you need to be able to click on child elements and only that child elements.

Example usage:

    <style>
        .parent {
            pointer-events:none;        
        }
        .child {
            pointer-events:auto;
        }
    </style>
    
    <div class="parent">
      <a href="#">I'm unresponsive</a>
      <a href="#" class="child">I'm clickable again, wohoo !</a>
    </div>

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

What do pty and tty mean?

tty: teletype. Usually refers to the serial ports of a computer, to which terminals were attached.

pty: pseudoteletype. Kernel provided pseudoserial port connected to programs emulating terminals, such as xterm, or screen.

Convert datetime value into string

Use DATE_FORMAT()

SELECT
  DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;

Remove quotes from a character vector in R

I'm just guessing, is this in the ball park of what you're trying to achieve?

> a <- "a"
> a
[1] "a" # quote yes
> as.factor(a)
[1] a #quote no

What's a Good Javascript Time Picker?

CSS Gallery has variety of Time Pickers. Have a look.

Perifer Design's time picker is similar to google one

Set the value of a variable with the result of a command in a Windows batch file

Here's how I do it when I need a database query's results in my batch file:

sqlplus -S schema/schema@db @query.sql> __query.tmp
set /p result=<__query.tmp
del __query.tmp

The key is in line 2: "set /p" sets the value of "result" to the value of the first line (only) in "__query.tmp" via the "<" redirection operator.

Comparing the contents of two files in Sublime Text

Compare Side-By-Side looks like the most convenient to me though it's not the most popular:

UPD: I need to add that this plugin can freeze ST while comparing big files. It is certainly not the best decision if you are going to compare large texts.

How does "FOR" work in cmd batch file?

You've got the right idea, but for /f is designed to work on multi-line files or commands, not individual strings.

In its simplest form, for is like Perl's for, or every other language's foreach. You pass it a list of tokens, and it iterates over them, calling the same command each time.

for %a in (hello world) do @echo %a

The extensions merely provide automatic ways of building the list of tokens. The reason your current code is coming up with nothing is that ';' is the default end of line (comment) symbol. But even if you change that, you'd have to use %%g, %%h, %%i, ... to access the individual tokens, which will severely limit your batch file.

The closest you can get to what you ask for is:

set TabbedPath=%PATH:;= %
for %%g in (%TabbedPath%) do echo %%g

But that will fail for quoted paths that contain semicolons.

In my experience, for /l and for /r are good for extending existing commands, but otherwise for is extremely limited. You can make it slightly more powerful (and confusing) with delayed variable expansion (cmd /v:on), but it's really only good for lists of filenames.

I'd suggest using WSH or PowerShell if you need to perform string manipulation. If you're trying to write whereis for Windows, try where /?.

how to use javascript Object.defineProperty

get is a function that is called when you try to read the value player.health, like in:

console.log(player.health);

It's effectively not much different than:

player.getHealth = function(){
  return 10 + this.level*15;
}
console.log(player.getHealth());

The opposite of get is set, which would be used when you assign to the value. Since there is no setter, it seems that assigning to the player's health is not intended:

player.health = 5; // Doesn't do anything, since there is no set function defined

A very simple example:

_x000D_
_x000D_
var player = {_x000D_
  level: 5_x000D_
};_x000D_
_x000D_
Object.defineProperty(player, "health", {_x000D_
  get: function() {_x000D_
    return 10 + (player.level * 15);_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log(player.health); // 85_x000D_
player.level++;_x000D_
console.log(player.health); // 100_x000D_
_x000D_
player.health = 5; // Does nothing_x000D_
console.log(player.health); // 100
_x000D_
_x000D_
_x000D_

Selenium C# WebDriver: Wait until element is present

You can use the following

WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0,0,5));
wait.Until(ExpectedConditions.ElementToBeClickable((By.Id("login")));

How to animate button in android?

Dependency

Add it in your root build.gradle at the end of repositories:

allprojects {
repositories {
    ...
    maven { url "https://jitpack.io" }
}}

and then add dependency dependencies { compile 'com.github.varunest:sparkbutton:1.0.5' }

Usage

XML

<com.varunest.sparkbutton.SparkButton
        android:id="@+id/spark_button"
        android:layout_width="40dp"
        android:layout_height="40dp"
        app:sparkbutton_activeImage="@drawable/active_image"
        app:sparkbutton_inActiveImage="@drawable/inactive_image"
        app:sparkbutton_iconSize="40dp"
        app:sparkbutton_primaryColor="@color/primary_color"
        app:sparkbutton_secondaryColor="@color/secondary_color" />

Java (Optional)

SparkButton button  = new SparkButtonBuilder(context)
            .setActiveImage(R.drawable.active_image)
            .setInActiveImage(R.drawable.inactive_image)
            .setDisabledImage(R.drawable.disabled_image)
            .setImageSizePx(getResources().getDimensionPixelOffset(R.dimen.button_size))
            .setPrimaryColor(ContextCompat.getColor(context, R.color.primary_color))
            .setSecondaryColor(ContextCompat.getColor(context, R.color.secondary_color))
            .build();

$rootScope.$broadcast vs. $scope.$emit

Use RxJS in a Service

What about in a situation where you have a Service that's holding state for example. How could I push changes to that Service, and other random components on the page be aware of such a change? Been struggling with tackling this problem lately

Build a service with RxJS Extensions for Angular.

<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/rx/dist/rx.all.js"></script>
<script src="//unpkg.com/rx-angular/dist/rx.angular.js"></script>
var app = angular.module('myApp', ['rx']);

app.factory("DataService", function(rx) {
  var subject = new rx.Subject(); 
  var data = "Initial";

  return {
      set: function set(d){
        data = d;
        subject.onNext(d);
      },
      get: function get() {
        return data;
      },
      subscribe: function (o) {
         return subject.subscribe(o);
      }
  };
});

Then simply subscribe to the changes.

app.controller('displayCtrl', function(DataService) {
  var $ctrl = this;

  $ctrl.data = DataService.get();
  var subscription = DataService.subscribe(function onNext(d) {
      $ctrl.data = d;
  });

  this.$onDestroy = function() {
      subscription.dispose();
  };
});

Clients can subscribe to changes with DataService.subscribe and producers can push changes with DataService.set.

The DEMO on PLNKR.

How to parse a JSON Input stream

For those that pointed out the fact that you can't use the toString method of InputStream like this see https://stackoverflow.com/a/5445161/1304830 :

My correct answer would be then :

import org.json.JSONObject;

public static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

...

JSONObject json = new JSONObject(convertStreamToString(url.openStream());

Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

Find text in string with C#

Except for @Prashant's answer, the above answers have been answered incorrectly. Where is the "replace" feature of the answer? The OP asked, "After that, I'd like to create a new string between that and something else".

Based on @Oscar's excellent response, I have expanded his function to be a "Search And Replace" function in one.

I think @Prashant's answer should have been the accepted answer by the OP, as it does a replace.

Anyway, I've called my variant - ReplaceBetween().

public static string ReplaceBetween(string strSource, string strStart, string strEnd, string strReplace)
{
    int Start, End;
    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
    {
        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        End = strSource.IndexOf(strEnd, Start);
        string strToReplace = strSource.Substring(Start, End - Start);
        string newString = strSource.Concat(Start,strReplace,End - Start);
        return newString;
    }
    else
    {
        return string.Empty;
    }
}

How to loop through a JSON object with typescript (Angular2)

ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

Why does typeof array with objects return "object" and not "array"?

Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.

Associative Array

var a = new Array(1,2,3); 
a['key'] = 'experiment';
Array.isArray(a);

returns true

Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.

Object

var a = {1:1, 2:2, 3:3,'key':'experiment'}; 
Array.isArray(a)

returns false

JSON returns an Object ... could return an Associative Array ... but it is not like that

How does Java deal with multiple conditions inside a single IF statement

Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?

Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.

if(s != null && s.length() > 0)

or

if(s == null || s.length() == 0)

BTW if you use & and | it will always evaluate both sides of the expression.

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

This should do the trick!

// convert object => json
$json = json_encode($myObject);

// convert json => object
$obj = json_decode($json);

Here's an example

$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";

$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}

print_r(json_decode($json));
// stdClass Object
// (
//   [hello] => world
//   [bar] => baz
// )

If you want the output as an Array instead of an Object, pass true to json_decode

print_r(json_decode($json, true));
// Array
// (
//   [hello] => world
//   [bar] => baz
// )    

More about json_encode()

See also: json_decode()

Get Substring - everything before certain char

The LINQy way

String.Concat( "223232-1.jpg".TakeWhile(c => c != '-') )

(But, you do need to test for null ;)

How to make shadow on border-bottom?

New method for an old question

enter image description here

It seems like in the answers provided the issue was always how the box border would either be visible on the left and right of the object or you'd have to inset it so far that it didn't shadow the whole length of the container properly.

This example uses the :after pseudo element along with a linear gradient with transparency in order to put a drop shadow on a container that extends exactly to the sides of the element you wish to shadow.

Worth noting with this solution is that if you use padding on the element that you wish to drop shadow, it won't display correctly. This is because the after pseudo element appends it's content directly after the elements inner content. So if you have padding, the shadow will appear inside the box. This can be overcome by eliminating padding on outer container (where the shadow applies) and using an inner container where you apply needed padding.

Example with padding and background color on the shadowed div:

enter image description here

If you want to change the depth of the shadow, simply increase the height style in the after pseudo element. You can also obviously darken, lighten, or change colors in the linear gradient styles.

_x000D_
_x000D_
body {_x000D_
  background: #eee;_x000D_
}_x000D_
_x000D_
.bottom-shadow {_x000D_
  width: 80%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
.bottom-shadow:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  height: 8px;_x000D_
  background: transparent;_x000D_
  background: -moz-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%); /* FF3.6-15 */_x000D_
  background: -webkit-linear-gradient(top, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* Chrome10-25,Safari5.1-6 */_x000D_
  background: linear-gradient(to bottom, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(   startColorstr='#a6000000', endColorstr='#00000000',GradientType=0 ); /* IE6-9 */_x000D_
}_x000D_
_x000D_
.bottom-shadow div {_x000D_
  padding: 18px;_x000D_
  background: #fff;_x000D_
}
_x000D_
<div class="bottom-shadow">_x000D_
  <div>_x000D_
    Shadows, FTW!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get/pick an image from Android's built-in Gallery app programmatically

This is a complete solution. I've just updated this example code with the information provided in the answer below by @mad. Also check the solution below from @Khobaib explaining how to deal with picasa images.

Update

I've just reviewed my original answer and created a simple Android Studio project you can checkout from github and import directly on your system.

https://github.com/hanscappelle/SO-2169649

(note that the multiple file selection still needs work)

Single Picture Selection

With support for images from file explorers thanks to user mad.

public class BrowsePictureActivity extends Activity {

    // this is the action code we use in our intent, 
    // this way we know we're looking at the response from our own action
    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViewById(R.id.Button01)
                .setOnClickListener(new OnClickListener() {

                    public void onClick(View arg0) {

                        // in onCreate or any event where your want the user to
                        // select a file
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(Intent.createChooser(intent,
                                "Select Picture"), SELECT_PICTURE);
                    }
                });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
            }
        }
    }

    /**
     * helper to retrieve the path of an image URI
     */
    public String getPath(Uri uri) {
            // just some safety built in 
            if( uri == null ) {
                // TODO perform some logging or show user feedback
                return null;
            }
            // try to retrieve the image from the media store first
            // this will only work for images selected from gallery
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            if( cursor != null ){
                int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                String path = cursor.getString(column_index);
                cursor.close();
                return path;
            }
            // this is our fallback here
            return uri.getPath();
    }

}

Selecting Multiple Pictures

Since someone requested that information in a comment and it's better to have information gathered.

Set an extra parameter EXTRA_ALLOW_MULTIPLE on the intent:

intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);

And in the Result handling check for that parameter:

if (Intent.ACTION_SEND_MULTIPLE.equals(data.getAction()))
        && Intent.hasExtra(Intent.EXTRA_STREAM)) {
    // retrieve a collection of selected images
    ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
    // iterate over these images
    if( list != null ) {
       for (Parcelable parcel : list) {
         Uri uri = (Uri) parcel;
         // TODO handle the images one by one here
       }
   }
} 

Note that this is only supported by API level 18+.

How can I delay a :hover effect in CSS?

div {
     background: #dbdbdb;
    -webkit-transition: .5s all;   
    -webkit-transition-delay: 5s; 
    -moz-transition: .5s all;   
    -moz-transition-delay: 5s; 
    -ms-transition: .5s all;   
    -ms-transition-delay: 5s; 
    -o-transition: .5s all;   
    -o-transition-delay: 5s; 
    transition: .5s all;   
    transition-delay: 5s; 
}

div:hover {
    background:#5AC900;
    -webkit-transition-delay: 0s;
    -moz-transition-delay: 0s;
    -ms-transition-delay: 0s;
    -o-transition-delay: 0s;
    transition-delay: 0s;
}

This will add a transition delay, which will be applicable to almost every browser..

Thymeleaf using path variables to th:href

A cleaner and easier way to do this

<a href="somepage.html" th:href="@{|/my/url/${variable}|}">A Link</a>

I found this solution in Thymeleaf Documentation on "4.8 Literal substitutions".

What is "entropy and information gain"?

Informally

entropy is availability of information or knowledge, Lack of information will leads to difficulties in prediction of future which is high entropy (next word prediction in text mining) and availability of information/knowledge will help us more realistic prediction of future (low entropy).

Relevant information of any type will reduce entropy and helps us predict more realistic future, that information can be word "meat" is present in sentence or word "meat" is not present. This is called Information Gain


Formally

entropy is lack of order of predicability

The multi-part identifier could not be bound

If this error happens in an UPDATE, double-check the JOIN on the table with the column/field that is causing the error.

In my case this was due to the lack of the JOIN itself, which generated the same error due to an unknown field (as Andriy pointed out).

How to download image using requests

my approach was to use response.content (blob) and save to the file in binary mode

img_blob = requests.get(url, timeout=5).content
     with open(destination + '/' + title, 'wb') as img_file:
         img_file.write(img_blob)

Check out my python project that downloads images from unsplash.com based on keywords.

git still shows files as modified after adding to .gitignore

Your .gitignore is working, but it still tracks the files because they were already in the index.

To stop this you have to do : git rm -r --cached .idea/

When you commit the .idea/ directory will be removed from your git repository and the following commits will ignore the .idea/ directory.

PS: You could use .idea/ instead of .idea/* to ignore a directory. You can find more info about the patterns on the .gitignore man page.


Helpful quote from the git-rm man page

--cached
    Use this option to unstage and remove paths only from the index. 
    Working tree files, whether modified or not, will be left alone.

In CSS how do you change font size of h1 and h2

 h1 { font-size: 150%; }
 h2 { font-size: 120%; }

Tune as needed.

Accessing JPEG EXIF rotation data in JavaScript on the client side

If you want it cross-browser, your best bet is to do it on the server. You could have an API that takes a file URL and returns you the EXIF data; PHP has a module for that.

This could be done using Ajax so it would be seamless to the user. If you don't care about cross-browser compatibility, and can rely on HTML5 file functionality, look into the library JsJPEGmeta that will allow you to get that data in native JavaScript.

Android sqlite how to check if a record exists

because of possible data leaks best solution via cursor:

 Cursor cursor = null;
    try {
          cursor =  .... some query (raw or not your choice)
          return cursor.moveToNext();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

1) From API KITKAT u can use resources try()

try (cursor = ...some query)

2) if u query against VARCHAR TYPE use '...' eg. COLUMN_NAME='string_to_search'

3) dont use moveToFirst() is used when you need to start iterating from beggining

4) avoid getCount() is expensive - it iterates over many records to count them. It doesn't return a stored variable. There may be some caching on a second call, but the first call doesn't know the answer until it is counted.

How to find substring from string?

Use std::string and find.

std::string str = "/user/desktop/abc/post/";
bool exists = str.find("/abc/") != std::string::npos;

C# equivalent to Java's charAt()?

Simply use String.ElementAt(). It's quite similar to java's String.charAt(). Have fun coding!

Pandas column of lists, create a row for each list element

you can also use pd.concat and pd.melt for this:

>>> objs = [df, pd.DataFrame(df['samples'].tolist())]
>>> pd.concat(objs, axis=1).drop('samples', axis=1)
   subject  trial_num     0     1     2
0        1          1 -0.49 -1.00  0.44
1        1          2 -0.28  1.48  2.01
2        1          3 -0.52 -1.84  0.02
3        2          1  1.23 -1.36 -1.06
4        2          2  0.54  0.18  0.51
5        2          3 -2.18 -0.13 -1.35
>>> pd.melt(_, var_name='sample_num', value_name='sample', 
...         value_vars=[0, 1, 2], id_vars=['subject', 'trial_num'])
    subject  trial_num sample_num  sample
0         1          1          0   -0.49
1         1          2          0   -0.28
2         1          3          0   -0.52
3         2          1          0    1.23
4         2          2          0    0.54
5         2          3          0   -2.18
6         1          1          1   -1.00
7         1          2          1    1.48
8         1          3          1   -1.84
9         2          1          1   -1.36
10        2          2          1    0.18
11        2          3          1   -0.13
12        1          1          2    0.44
13        1          2          2    2.01
14        1          3          2    0.02
15        2          1          2   -1.06
16        2          2          2    0.51
17        2          3          2   -1.35

last, if you need you can sort base on the first the first three columns.

Can I use multiple versions of jQuery on the same page?

Taken from http://forum.jquery.com/topic/multiple-versions-of-jquery-on-the-same-page:

  • Original page loads his "jquery.versionX.js" -- $ and jQuery belong to versionX.
  • You call your "jquery.versionY.js" -- now $ and jQuery belong to versionY, plus _$ and _jQuery belong to versionX.
  • my_jQuery = jQuery.noConflict(true); -- now $ and jQuery belong to versionX, _$ and _jQuery are probably null, and my_jQuery is versionY.

How to open a web page from my application?

I've been using this line to launch the default browser:

System.Diagnostics.Process.Start("http://www.google.com"); 

Convert string to date then format the date

enter image description here

String myFormat= "yyyy-MM-dd";
String finalString = "";
try {
DateFormat formatter = new SimpleDateFormat("yyyy MMM dd");
Date date = (Date) formatter .parse("2015 Oct 09");
SimpleDateFormat newFormat = new SimpleDateFormat(myFormat);
finalString= newFormat .format(date );
newDate.setText(finalString);
} catch (Exception e) {

}

writing a batch file that opens a chrome URL

It's very simple. Just try:

start chrome https://www.google.co.in/

it will open the Google page in the Chrome browser.

If you wish to open the page in Firefox, try:

start firefox https://www.google.co.in/

Have Fun!

Is it possible to focus on a <div> using JavaScript focus() function?

_x000D_
_x000D_
document.getElementById('test').onclick = function () {_x000D_
    document.getElementById('scripted').focus();_x000D_
};
_x000D_
div:focus {_x000D_
    background-color: Aqua;_x000D_
}
_x000D_
<div>Element X (not focusable)</div>_x000D_
<div tabindex="0">Element Y (user or script focusable)</div>_x000D_
<div tabindex="-1" id="scripted">Element Z (script-only focusable)</div>_x000D_
<div id="test">Set Focus To Element Z</div>
_x000D_
_x000D_
_x000D_

Using Python's ftplib to get a directory listing, portably

Try to use ftp.nlst(dir).

However, note that if the folder is empty, it might throw an error:

files = []

try:
    files = ftp.nlst()
except ftplib.error_perm, resp:
    if str(resp) == "550 No files found":
        print "No files in this directory"
    else:
        raise

for f in files:
    print f

How to check if a string contains text from an array of substrings in JavaScript?

var yourstring = 'tasty food'; // the string to check against


var substrings = ['foo','bar'],
    length = substrings.length;
while(length--) {
   if (yourstring.indexOf(substrings[length])!=-1) {
       // one of the substrings is in yourstring
   }
}

Certificate is trusted by PC but not by Android

You have to create a crt bundle then it will be fine. You will be receiving three crt files. Use them all! If you only used the domain.crt then there will be warning on android but not on PC.

I am on nginx. I opened domain_name.crt and then opened positivesslca2.crt, select all and copy to the end of domain_name.crt. Then open AddTrustExternalCARoot.crt, copy to the end of domain_name.crt again. Then install the domain_name.crt

works good.

Dynamic type languages versus static type languages

Static Typing: The languages such as Java and Scala are static typed.

The variables have to be defined and initialized before they are used in a code.

for ex. int x; x = 10;

System.out.println(x);

Dynamic Typing: Perl is an dynamic typed language.

Variables need not be initialized before they are used in code.

y=10; use this variable in the later part of code

How do you truncate all tables in a database using TSQL?

Before truncating the tables you have to remove all foreign keys. Use this script to generate final scripts to drop and recreate all foreign keys in database. Please set the @action variable to 'CREATE' or 'DROP'.

How to make --no-ri --no-rdoc the default for gem install?

On Windows XP the path to the .gemrc file is

c:\Documents and Settings\All Users\Application Data\gemrc 

and this file is not created by default, you should create it yourself.

How to get value in the session in jQuery

Assuming you are using this plugin, you are misusing the .set method. .set must be passed the name of the key as a string as well as the value. I suppose you meant to write:

$.session.set("userName", $("#uname").val());

This sets the userName key in session storage to the value of the input, and allows you to retrieve it using:

$.session.get('userName');

File Upload to HTTP server in iphone programming

This is a great wrapper, but when posting to a asp.net web page, two additional post values need to be set:

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //ADD THESE, BECAUSE ASP.NET is Expecting them for validation
    //Even if they are empty you will be able to post the file
    [request setPostValue:@"" forKey:@"__VIEWSTATE"];
    [request setPostValue:@"" forKey:@"__EVENTVALIDATION"]; 
    ///

    [request setFile:FIleName forKey:@"fileupload_control_Name"];
    [request startSynchronous];

Count(*) vs Count(1) - SQL Server

Clearly, COUNT(*) and COUNT(1) will always return the same result. Therefore, if one were slower than the other it would effectively be due to an optimiser bug. Since both forms are used very frequently in queries, it would make no sense for a DBMS to allow such a bug to remain unfixed. Hence you will find that the performance of both forms is (probably) identical in all major SQL DBMSs.

How to clear https proxy setting of NPM?

If you want to switch between proxy for company network and remove proxy for home/personal network you can use --no-proxy

Sample usage:

npm install --save-dev "@angular/[email protected]" --no-proxy

How to fix "The ConnectionString property has not been initialized"

Use [] instead of () as below example.

SqlDataAdapter adapter = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["FADB_ConnectionString"].ConnectionString);
            DataTable data = new DataTable();
            DataSet ds = new DataSet();

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

Android - Back button in the title bar

I needed to mix some answers to get the right answer for me because my app has 3 activities that can go and back at any time. Activity1 > Activity2 > Activity3. When I was doing something on my activity3, the back button was backing correctly to Activity2. However, from the Activity2, using finish(), it was backing to Activity3 and not Activity1. And I'm extending AppCompatActivity. So, my solution was:

public class Activity2 extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            ...

            getSupportActionBar().setHomeButtonEnabled(true);
        }
    }

on AndroidManifest.xml:

<activity android:name=".activities.Activity2"
           android:parentActivityName="com.example.appname.activities.Activity1">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.appname.activities.Activity1" />
        </activity>

and finally, the action button on my menu (actionbar):

public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            ...

            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;

        }

        return super.onOptionsItemSelected(item);

    }

Using NavUtils.navigateUpFromSameTask(this); worked for me, instead of finish().

How to add 10 days to current time in Rails

Try this on Rails

Time.new + 10.days 

Try this on Ruby

require 'date'
DateTime.now.next_day(10).to_time

Show history of a file?

You can use git log to display the diffs while searching:

git log -p -- path/to/file

Clang vs GCC - which produces faster binaries?

A peculiar difference I have noted on gcc 5.2.1 and clang 3.6.2 is that if you have a critical loop like:

for (;;) {
    if (!visited) {
        ....
    }
    node++;
    if (!*node) break;
  }

Then gcc will, when compiling with -O3 or -O2, speculatively unroll the loop eight times. Clang will not unroll it at all. Through trial and error I found that in my specific case with my program data, the right amount of unrolling is five so gcc overshot and clang undershot. However, overshooting was more detrimental to performance, so gcc performed much worse here.

I have no idea if the unrolling difference is a general trend or just something that was specific to my scenario.

A while back I wrote a few garbage collectors to teach myself more about performance optimization in C. And the results I got is in my mind enough to slightly favor clang. Especially since garbage collection is mostly about pointer chasing and copying memory.

The results are (numbers in seconds):

+---------------------+-----+-----+
|Type                 |GCC  |Clang|
+---------------------+-----+-----+
|Copying GC           |22.46|22.55|
|Copying GC, optimized|22.01|20.22|
|Mark & Sweep         | 8.72| 8.38|
|Ref Counting/Cycles  |15.14|14.49|
|Ref Counting/Plain   | 9.94| 9.32|
+---------------------+-----+-----+

This is all pure C code, and I make no claim about either compiler's performance when compiling C++ code.

On Ubuntu 15.10, x86.64, and an AMD Phenom(tm) II X6 1090T processor.

Posting a File and Associated Data to a RESTful WebService preferably as JSON

You can send the file and data over in one request using the multipart/form-data content type:

In many applications, it is possible for a user to be presented with a form. The user will fill out the form, including information that is typed, generated by user input, or included from files that the user has selected. When the form is filled out, the data from the form is sent from the user to the receiving application.

The definition of MultiPart/Form-Data is derived from one of those applications...

From http://www.faqs.org/rfcs/rfc2388.html:

"multipart/form-data" contains a series of parts. Each part is expected to contain a content-disposition header [RFC 2183] where the disposition type is "form-data", and where the disposition contains an (additional) parameter of "name", where the value of that parameter is the original field name in the form. For example, a part might contain a header:

Content-Disposition: form-data; name="user"

with the value corresponding to the entry of the "user" field.

You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.

The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.

Uncaught TypeError: Cannot read property 'value' of undefined

Either document.getElementById('i1'), document.getElementById('i2'), or document.getElementsByName("username")[0] is returning no element. Check, that all elements exist.

SQL: How to perform string does not equal

Try the following query

select * from table
where NOT (tester = 'username')

Completely removing phpMyAdmin

If your system is using dpkg and apt (debian, ubuntu, etc), try running the following commands in that order (be careful with the sudo rm commands):

sudo apt-get -f install
sudo dpkg -P phpmyadmin  
sudo rm -vf /etc/apache2/conf.d/phpmyadmin.conf
sudo rm -vfR /usr/share/phpmyadmin
sudo service apache2 restart

String array initialization in Java

First up, this has got nothing to do with String, it is about arrays.. and that too specifically about declarative initialization of arrays.

As discussed by everyone in almost every answer here, you can, while declaring a variable, use:

String names[] = {"x","y","z"};

However, post declaration, if you want to assign an instance of an Array:

names = new String[] {"a","b","c"};

AFAIK, the declaration syntax is just a syntactic sugar and it is not applicable anymore when assigning values to variables because when values are assigned you need to create an instance properly.

However, if you ask us why it is so? Well... good luck getting an answer to that. Unless someone from the Java committee answers that or there is explicit documentation citing the said syntactic sugar.

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

php is null or empty?

As is shown in the following table, empty($foo) is equivalent to $foo==null and is_null($foo) has the same function of $foo===null. The table also shows some tricky values regarding the null comparison. (? denotes an uninitialized variables. )

         empty    is_null 
         ==null  ===null  isset   array_key_exists
      ? |   T   |   T   |   F   |   F   
   null |   T   |   T   |   F   |   T   
     "" |   T   |   F   |   T   |   T   
     [] |   T   |   F   |   T   |   T
      0 |   T   |   F   |   T   |   T      
  false |   T   |   F   |   T   |   T   
   true |   F   |   F   |   T   |   T   
      1 |   F   |   F   |   T   |   T   
     \0 |   F   |   F   |   T   |   T   

How to press back button in android programmatically?

Simply add finish(); in your first class' (login activity) onPause(); method. that's all

How to load my app from Eclipse to my Android phone instead of AVD

Thanks this helped. It was a little tricky getting the USB debugging option enabled on the Samsung G3 after the update.

See below Instructions on Samsung G3 Jellybean

  1. Settings
  2. Click --> About the phone
  3. Tap on the build number
  4. “You are now 4 steps away from being a developer.” Keep tapping until it says “You are now a developer.”
  5. Go back to Setting-->System --> Developer option: Enable USB Debugging

Virtual member call in a constructor

Because until the constructor has completed executing, the object is not fully instantiated. Any members referenced by the virtual function may not be initialised. In C++, when you are in a constructor, this only refers to the static type of the constructor you are in, and not the actual dynamic type of the object that is being created. This means that the virtual function call might not even go where you expect it to.

How to detect IE11?

Try This:

var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var net = !!navigator.userAgent.match(/.NET4.0E/);
var IE11 = trident && net
var IEold = ( navigator.userAgent.match(/MSIE/i) ? true : false );
if(IE11 || IEold){
alert("IE")
}else{
alert("Other")
}

Angularjs simple file download causes router to redirect

We also had to develop a solution which would even work with APIs requiring authentication (see this article)

Using AngularJS in a nutshell here is how we did it:

Step 1: Create a dedicated directive

// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
    restrict: 'E',
    templateUrl: '/path/to/pdfDownload.tpl.html',
    scope: true,
    link: function(scope, element, attr) {
        var anchor = element.children()[0];

        // When the download starts, disable the link
        scope.$on('download-start', function() {
            $(anchor).attr('disabled', 'disabled');
        });

        // When the download finishes, attach the data to the link. Enable the link and change its appearance.
        scope.$on('downloaded', function(event, data) {
            $(anchor).attr({
                href: 'data:application/pdf;base64,' + data,
                download: attr.filename
            })
                .removeAttr('disabled')
                .text('Save')
                .removeClass('btn-primary')
                .addClass('btn-success');

            // Also overwrite the download pdf function to do nothing.
            scope.downloadPdf = function() {
            };
        });
    },
    controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
        $scope.downloadPdf = function() {
            $scope.$emit('download-start');
            $http.get($attrs.url).then(function(response) {
                $scope.$emit('downloaded', response.data);
            });
        };
    }] 
});

Step 2: Create a template

<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>

Step 3: Use it

<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>

This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.

Our example uses PDF files, but apparently you could provide any binary format given it's properly encoded.

css width: calc(100% -100px); alternative using jquery

100%-100px is the same

div.thediv {
  width: auto;
  margin-right:100px;
}

With jQuery:

$(window).resize(function(){
  $('.thediv').each(function(){
    $(this).css('width', $(this).parent().width()-100);
  })
});

Similar way is to use jQuery resize plugin

maximum value of int

I know it's an old question but maybe someone can use this solution:

int size = 0; // Fill all bits with zero (0)
size = ~size; // Negate all bits, thus all bits are set to one (1)

So far we have -1 as result 'till size is a signed int.

size = (unsigned int)size >> 1; // Shift the bits of size one position to the right.

As Standard says, bits that are shifted in are 1 if variable is signed and negative and 0 if variable would be unsigned or signed and positive.

As size is signed and negative we would shift in sign bit which is 1, which is not helping much, so we cast to unsigned int, forcing to shift in 0 instead, setting the sign bit to 0 while letting all other bits remain 1.

cout << size << endl; // Prints out size which is now set to maximum positive value.

We could also use a mask and xor but then we had to know the exact bitsize of the variable. With shifting in bits front, we don't have to know at any time how many bits the int has on machine or compiler nor need we include extra libraries.

"unable to locate adb" using Android Studio

If you are using Anti-Virus, you can first check virus chest and restore from there. Otherwise, just go to your SDK Manager and install Android SDK Tools.

Passing a dictionary to a function as keyword parameters

In python, this is called "unpacking", and you can find a bit about it in the tutorial. The documentation of it sucks, I agree, especially because of how fantasically useful it is.

Connection Strings for Entity Framework

Silverlight applications do not have direct access to machine.config.

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

In the console is telling you that is a conflict with login. I think that you should declare also in the index.html thymeleaf. Something like:

    <html xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:th="http://www.thymeleaf.org" 
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>k</title> 
</head>

Difference in make_shared and normal shared_ptr in C++

The difference is that std::make_shared performs one heap-allocation, whereas calling the std::shared_ptr constructor performs two.

Where do the heap-allocations happen?

std::shared_ptr manages two entities:

  • the control block (stores meta data such as ref-counts, type-erased deleter, etc)
  • the object being managed

std::make_shared performs a single heap-allocation accounting for the space necessary for both the control block and the data. In the other case, new Obj("foo") invokes a heap-allocation for the managed data and the std::shared_ptr constructor performs another one for the control block.

For further information, check out the implementation notes at cppreference.

Update I: Exception-Safety

NOTE (2019/08/30): This is not a problem since C++17, due to the changes in the evaluation order of function arguments. Specifically, each argument to a function is required to fully execute before evaluation of other arguments.

Since the OP seem to be wondering about the exception-safety side of things, I've updated my answer.

Consider this example,

void F(const std::shared_ptr<Lhs> &lhs, const std::shared_ptr<Rhs> &rhs) { /* ... */ }

F(std::shared_ptr<Lhs>(new Lhs("foo")),
  std::shared_ptr<Rhs>(new Rhs("bar")));

Because C++ allows arbitrary order of evaluation of subexpressions, one possible ordering is:

  1. new Lhs("foo"))
  2. new Rhs("bar"))
  3. std::shared_ptr<Lhs>
  4. std::shared_ptr<Rhs>

Now, suppose we get an exception thrown at step 2 (e.g., out of memory exception, Rhs constructor threw some exception). We then lose memory allocated at step 1, since nothing will have had a chance to clean it up. The core of the problem here is that the raw pointer didn't get passed to the std::shared_ptr constructor immediately.

One way to fix this is to do them on separate lines so that this arbitary ordering cannot occur.

auto lhs = std::shared_ptr<Lhs>(new Lhs("foo"));
auto rhs = std::shared_ptr<Rhs>(new Rhs("bar"));
F(lhs, rhs);

The preferred way to solve this of course is to use std::make_shared instead.

F(std::make_shared<Lhs>("foo"), std::make_shared<Rhs>("bar"));

Update II: Disadvantage of std::make_shared

Quoting Casey's comments:

Since there there's only one allocation, the pointee's memory cannot be deallocated until the control block is no longer in use. A weak_ptr can keep the control block alive indefinitely.

Why do instances of weak_ptrs keep the control block alive?

There must be a way for weak_ptrs to determine if the managed object is still valid (eg. for lock). They do this by checking the number of shared_ptrs that own the managed object, which is stored in the control block. The result is that the control blocks are alive until the shared_ptr count and the weak_ptr count both hit 0.

Back to std::make_shared

Since std::make_shared makes a single heap-allocation for both the control block and the managed object, there is no way to free the memory for control block and the managed object independently. We must wait until we can free both the control block and the managed object, which happens to be until there are no shared_ptrs or weak_ptrs alive.

Suppose we instead performed two heap-allocations for the control block and the managed object via new and shared_ptr constructor. Then we free the memory for the managed object (maybe earlier) when there are no shared_ptrs alive, and free the memory for the control block (maybe later) when there are no weak_ptrs alive.

How to negate the whole regex?

\b(?=\w)(?!(ma|(t){1}))\b(\w*)

this is for the given regex.
the \b is to find word boundary.
the positive look ahead (?=\w) is here to avoid spaces.
the negative look ahead over the original regex is to prevent matches of it.
and finally the (\w*) is to catch all the words that are left.
the group that will hold the words is group 3.
the simple (?!pattern) will not work as any sub-string will match
the simple ^(?!(?:m{2}|t)$).*$ will not work as it's granularity is full lines

Problems installing the devtools package

None of the above answers worked for me on Ubuntu 18.04.3 LTS using R version 3.6.1

My guess is this might have something to do with Anaconda3...

What worked for me is:

conda install -c r r-devtools 

Then in R

install.packages("rlang")
install.packages("devtools")

sessionInfo()

R version 3.6.1 (2019-07-05)
Platform: x86_64-conda_cos6-linux-gnu (64-bit)
Running under: Ubuntu 18.04.3 LTS

Matrix products: default
BLAS/LAPACK: /home/tsundoku/anaconda3/lib/R/lib/libRblas.so

locale:
 [1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_CA.UTF-8        LC_COLLATE=en_CA.UTF-8    
 [5] LC_MONETARY=en_CA.UTF-8    LC_MESSAGES=en_CA.UTF-8   
 [7] LC_PAPER=en_CA.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_CA.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_3.6.1 tools_3.6.1    tcltk_3.6.1   

How to create a new branch from a tag?

An exemple of the only solution that works for me in the simple usecase where I am on a fork and I want to checkout a new branch from a tag that is on the main project repository ( here upstream )

git fetch upstream --tags

Give me

From https://github.com/keycloak/keycloak
   90b29b0e31..0ba9055d28  stage      -> upstream/stage
 * [new tag]    11.0.0     -> 11.0.0

Then I can create a new branch from this tag and checkout on it

git checkout -b tags/<name> <newbranch>

git checkout tags/11.0.0 -b v11.0.0

Simpler way to check if variable is not equal to multiple string values?

You can make use of in_array() in PHP.

$os = array("uk", "us"); // You can set multiple check conditions here
if (in_array("uk", $os)) //Founds a match !
{
    echo "Got you"; 
}

Spring get current ApplicationContext

Even after adding @Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:

@Component
public class SpringContext implements ApplicationContextAware{

   private static ApplicationContext applicationContext;

   @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws 
     BeansException {
    this.applicationContext=applicationContext;
   }
 }

you can then implement a getter method in the same class as per your need like getting the Implemented class reference by:

    applicationContext.getBean(String serviceName,Interface.Class)

Very simple log4j2 XML configuration file using Console and File appender

Here is my simplistic log4j2.xml that prints to console and writes to a daily rolling file:

// java
private static final Logger LOGGER = LogManager.getLogger(MyClass.class);


// log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="logPath">target/cucumber-logs</Property>
        <Property name="rollingFileName">cucumber</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
        </Console>
        <RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
            <Policies>
                <!-- Causes a rollover if the log file is older than the current JVM's start time -->
                <OnStartupTriggeringPolicy />
                <!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="DEBUG" additivity="false">
            <AppenderRef ref="console" />
            <AppenderRef ref="rollingFile" />
        </Root>
    </Loggers>
</Configuration>

TimeBasedTriggeringPolicy

interval (integer) - How often a rollover should occur based on the most specific time unit in the date pattern. For example, with a date pattern with hours as the most specific item and and increment of 4 rollovers would occur every 4 hours. The default value is 1.

modulate (boolean) - Indicates whether the interval should be adjusted to cause the next rollover to occur on the interval boundary. For example, if the item is hours, the current hour is 3 am and the interval is 4 then the first rollover will occur at 4 am and then next ones will occur at 8 am, noon, 4pm, etc.

Source: https://logging.apache.org/log4j/2.x/manual/appenders.html

Output:

[INFO ] 2018-07-21 12:03:47,412 ScenarioHook.beforeScenario() - Browser=CHROME32_NOHEAD
[INFO ] 2018-07-21 12:03:48,623 ScenarioHook.beforeScenario() - Screen Resolution (WxH)=1366x768
[DEBUG] 2018-07-21 12:03:52,125 HomePageNavigationSteps.I_Am_At_The_Home_Page() - Base URL=http://simplydo.com/projector/
[DEBUG] 2018-07-21 12:03:52,700 NetIncomeProjectorSteps.I_Enter_My_Start_Balance() - Start Balance=348000

A new log file will be created daily with previous day automatically renamed to:

cucumber_yyyy-MM-dd.log

In a Maven project, you would put the log4j2.xml in src/main/resources or src/test/resources.

How to remove files from git staging area?

Use the following to remove a specific file from the staging area:

git restore --staged <individual_file>

Or use the following to remove all the files that are currently staged:

git restore --staged .

In your git bash terminal after adding files to the staging area you can run a git status and the command is displayed for you above the current staged files: enter image description here

Statically rotate font-awesome icons

New Font-Awesome v5 has Power Transforms

You can rotate any icon by adding attribute data-fa-transform to icon

<i class="fas fa-magic" data-fa-transform="rotate-45"></i>

Here is a fiddle

For more information, check this out : Font-Awesome5 Power Tranforms

What does ^M character mean in Vim?

:%s/\r//g 

worked for me today. But my situation may have been slightly different.

How do I add a library project to Android Studio?

A simple way to add a JAR file as a library to your Android Studio project:

a) Copy your *.jar files

b) Paste into the libs directory under your projects:

Enter image description here

c) Add to build.gradle:

dependencies {
    ...
    compile files('libs/ScanAPIAndroid.jar', 'libs/ScanAPIFactoryAndroid.jar', .., ..)
}

b) If your project from example com.example.MYProject and libraries com.example.ScanAPI has the same namespace com.example, Android Studio will check your build and create all necessary changes in your project. After that you can review these settings in menu File -> Project Structure.

c) If your project and libraries have a different namespace you have to right click on the library and select option "Add as Library" and select the type what you need.

Remember the "Project structure" option is not doing any auto changes in "build.gradle" in the current version of Android Studio (0.2.3). Maybe this feature will be available in the next versions.

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

we forgot mention "enctype" posting "multi-part" form data. One of my another scenario that I've just now face...

Binding a WPF ComboBox to a custom list

I had a similar issue where the SelectedItem never got updated.

My problem was that the selected item was not the same instance as the item contained in the list. So I simply had to override the Equals() method in my MyCustomObject and compare the IDs of those two instances to tell the ComboBox that it's the same object.

public override bool Equals(object obj)
{
    return this.Id == (obj as MyCustomObject).Id;
}

Compare one String with multiple values in one expression

For those who came here for exact equality checks (not ignoring case), I find that

if (Arrays.asList(str1, str2, str3).contains(strToCheck)) {
    ...
}

is one of, if the most concise solution, and is available on Java 7.

How can I compile my Perl script so it can be executed on systems without perl installed?

On MaxOSX there may be perlcc. Type man perlcc. On my system (10.6.8) it's in /usr/bin. YMMV

See http://search.cpan.org/~nwclark/perl-5.8.9/utils/perlcc.PL

Add element to a list In Scala

I will try to explain the results of all the commands you tried.

scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)

First of all, List is a type alias to scala.collection.immutable.List (defined in Predef.scala).

Using the List companion object is more straightforward way to instantiate a List. Ex: List(1.0,5.5)

scala> l
res0: List[Double] = List(1.0, 5.5)

scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)

::: returns a list resulting from the concatenation of the given list prefix and this list

The original List is NOT modified

scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)

List(l) is a List[List[Double]] Definitely not what you want.

:+ returns a new list consisting of all elements of this list followed by elem.

The type is List[Any] because it is the common superclass between List[Double] and Double

scala> l
res3: List[Double] = List(1.0, 5.5)

l is left unmodified because no method on immutable.List modified the List.

Add class to an element in Angular 4

If you want to set only one specific class, you might write a TypeScript function returning a boolean to determine when the class should be appended.

TypeScript

function hideThumbnail():boolean{
    if (/* Your criteria here */)
        return true;
}

CSS:

.request-card-hidden {
    display: none;
}

HTML:

<ion-note [class.request-card-hidden]="hideThumbnail()"></ion-note>

How to disable the ability to select in a DataGridView?

I fixed this by setting the Enabled property to false.

Eclipse Optimize Imports to Include Static Imports

If you highlight the method Assert.assertEquals(val1, val2) and hit Ctrl + Shift + M (Add Import), it will add it as a static import, at least in Eclipse 3.4.

Connecting to remote MySQL server using PHP

This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:

The client have two network cards,a wireless one and a normal one. The ping to server can be succeed.However telnet serverAddress 3306 would fail. And would complain

Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)

when try to connect to server.So I forbidden the normal network adapters. And tried telnet serverAddress 3306 it works.And then it work when connect to MySQL server.

How to run a single test with Mocha?

Depending on your usage pattern, you might just like to use only. We use the TDD style; it looks like this:

test.only('Date part of valid Partition Key', function (done) {
    //...
}

Only this test will run from all the files/suites.

Two div blocks on same line

HTML File

 <div id="container">
      <div id="bloc1">Copyright &copy; All Rights Reserved.</div>
      <div id="bloc2"><img src="..."></div>
    </div>

CSS File

 #container
    {
        text-align:center;
    }
    #bloc1, #bloc2
    {
        display:inline;
    }

javascript - pass selected value from popup window to parent window input box

My approach: use a div instead of a pop-up window.

See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/

Or save the code below as test.html and try it locally.

<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(window).load(function(){
            $('.btnChoice').on('click', function(){
                $('#divChoices').show()
                thefield = $(this).prev()
                $('.btnselect').on('click', function(){
                    theselected = $(this).prev()
                    thefield.val( theselected.val() )
                    $('#divChoices').hide()
                })
            })

            $('#divChoices').css({
                'border':'2px solid red',
                'position':'fixed',
                'top':'100',
                'left':'200',
                'display':'none'
            })
        });
    </script>
</head>

<body>

<div class="divform">
    <input type="checkbox" name="kvi1" id="kvi1" value="1">
    <label>Field 1: </label>
    <input size="10" type="number" id="sku1" name="sku1">
    <button id="choice1" class="btnChoice">?</button>
    <br>
    <input type="checkbox" name="kvi2" id="kvi2" value="2">
    <label>Field 2: </label>
    <input size="10"  type="number" id="sku2" name="sku2">
    <button id="choice2" class="btnChoice">?</button>
</div>

<div id="divChoices">
    Select something: 
    <br>
    <input size="10" type="number" id="ch1" name="ch1" value="11">
    <button id="btnsel1" class="btnselect">Select</button>
    <label for="ch1">bla bla bla</label>
    <br>
    <input size="10" type="number" id="ch2" name="ch2" value="22">
    <button id="btnsel2" class="btnselect">Select</button>
    <label for="ch2">ble ble ble</label>
</div>

</body>

</html>

clean and simple.

Subtract 1 day with PHP

$date = new DateTime("2017-05-18"); // For today/now, don't pass an arg.
$date->modify("-1 day");
echo $date->format("Y-m-d H:i:s");

Using DateTime has significantly reduced the amount of headaches endured whilst manipulating dates.

How can I install a package with go get?

Command go

Download and install packages and dependencies

Usage:

go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]

Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.

The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.

The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.

The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.

The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.

The -t flag instructs get to also download the packages required to build the tests for the specified packages.

The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.

The -v flag enables verbose progress and debug output.

Get also accepts build flags to control the installation. See 'go help build'.

When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.

When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.

When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.

Get never checks out or updates code stored in vendor directories.

For more about specifying packages, see 'go help packages'.

For more about how 'go get' finds source code to download, see 'go help importpath'.

This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.

See also: go build, go install, go clean.


For example, showing verbose output,

$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$ 

SQL Server check case-sensitivity?

You're interested in the collation. You could build something based on this snippet:

SELECT DATABASEPROPERTYEX('master', 'Collation');

Update
Based on your edit — If @test and @TEST can ever refer to two different variables, it's not SQL Server. If you see problems where the same variable is not equal to itself, check if that variable is NULL, because NULL = NULL returns `false.

How to convert wstring into string?

I spent many sad days trying to come up with a way to do this for C++17, which deprecated code_cvt facets, and this is the best I was able to come up with by combining code from a few different sources:

setlocale( LC_ALL, "en_US.UTF-8" ); //Invoked in main()

std::string wideToMultiByte( std::wstring const & wideString )
{
     std::string ret;
     std::string buff( MB_CUR_MAX, '\0' );

     for ( wchar_t const & wc : wideString )
     {
         int mbCharLen = std::wctomb( &buff[ 0 ], wc );

         if ( mbCharLen < 1 ) { break; }

         for ( int i = 0; i < mbCharLen; ++i ) 
         { 
             ret += buff[ i ]; 
         }
     }

     return ret;
 }

 std::wstring multiByteToWide( std::string const & multiByteString )
 {
     std::wstring ws( multiByteString.size(), L' ' );
     ws.resize( 
         std::mbstowcs( &ws[ 0 ], 
             multiByteString.c_str(), 
             multiByteString.size() ) );

     return ws;
 }

I tested this code on Windows 10, and at least for my purposes, it seems to work fine. Please don't lynch me if this doesn't consider some crazy edge cases that you might need to handle, I'm sure someone with more experience can improve on this! :-)

Also, credit where it's due:

Adapted for wideToMultiByte()

Copied for multiByteToWide

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

What are some good SSH Servers for windows?

copssh - OpenSSH for Windows

http://www.itefix.no/i2/copssh

Packages essential Cygwin binaries.

IIS Config Error - This configuration section cannot be used at this path

I think the better way is that you must remove you configuration from your web.config. Publish your code on the server and do what you want to remove directly from the IIS server interface.

Thanks to this method if you sucessfully do what you want, you just have to get the web.config and compare the differences. After that you just have to post the solution in this post :-P.

Is there "\n" equivalent in VBscript?

This page has a table of string constants including vbCrLf

vbCrLf | Chr(13) & Chr(10) | Carriage return–linefeed combination

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

I experienced this error when trying to embed an iframe and then opening the site with Brave. The error went away when I changed to "Shields Down" for the site in question. Obviously, this is not a full solution, since anyone else visiting the site with Brave will run into the same issue. To actually resolve it I would need to do one of the other things listed on this page. But at least I now know where the problem lies.

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

SQL JOIN, GROUP BY on three tables to get totals

I have a tip for those, who want to get various aggregated values from the same table.

Lets say I have table with users and table with points the users acquire. So the connection between them is 1:N (one user, many points records).

Now in the table 'points' I also store the information about for what did the user get the points (login, clicking a banner etc.). And I want to list all users ordered by SUM(points) AND then by SUM(points WHERE type = x). That is to say ordered by all the points user has and then by points the user got for a specific action (eg. login).

The SQL would be:

SELECT SUM(points.points) AS points_all, SUM(points.points * (points.type = 7)) AS points_login
FROM user
LEFT JOIN points ON user.id = points.user_id
GROUP BY user.id

The beauty of this is in the SUM(points.points * (points.type = 7)) where the inner parenthesis evaluates to either 0 or 1 thus multiplying the given points value by 0 or 1, depending on wheteher it equals to the the type of points we want.

Get the week start date and week end date from week number

Not sure how useful this is, but I ended up here from looking for a solution on Netezza SQL and couldn't find one on stack overflow.

For IBM netezza you would use something (for week start mon, week end sun) like:

select next_day (WeddingDate, 'SUN') -6 as WeekStart,

next_day (WeddingDate, 'SUN') as WeekEnd

How do I find which program is using port 80 in Windows?

Right click on "Command prompt" or "PowerShell", in menu click "Run as Administrator" (on Windows XP you can just run it as usual).

As Rick Vanover mentions in See what process is using a TCP port in Windows Server 2008

The following command will show what network traffic is in use at the port level:

Netstat -a -n -o

or

Netstat -a -n -o >%USERPROFILE%\ports.txt

(to open the port and process list in a text editor, where you can search for information you want)

Then,

with the PIDs listed in the netstat output, you can follow up with the Windows Task Manager (taskmgr.exe) or run a script with a specific PID that is using a port from the previous step. You can then use the "tasklist" command with the specific PID that corresponds to a port in question.

Example:

tasklist /svc /FI "PID eq 1348"

Suppress warning messages using mysql from within Terminal, but password written in bash script

Here is a solution for Docker in a script /bin/sh :

docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "[client]" > /root/mysql-credentials.cnf'

docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "user=root" >> /root/mysql-credentials.cnf'

docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "password=$MYSQL_ROOT_PASSWORD" >> /root/mysql-credentials.cnf'

docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec mysqldump --defaults-extra-file=/root/mysql-credentials.cnf --all-databases'

Replace [MYSQL_CONTAINER_NAME] and be sure that the environment variable MYSQL_ROOT_PASSWORD is set in your container.

Hope it will help you like it could help me !

Awaiting multiple Tasks with different results

After you use WhenAll, you can pull the results out individually with await:

var catTask = FeedCat();
var houseTask = SellHouse();
var carTask = BuyCar();

await Task.WhenAll(catTask, houseTask, carTask);

var cat = await catTask;
var house = await houseTask;
var car = await carTask;

You can also use Task.Result (since you know by this point they have all completed successfully). However, I recommend using await because it's clearly correct, while Result can cause problems in other scenarios.

Create unique constraint with null columns

I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.

That would lead to the reduced table definition:

CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);

Field 'browser' doesn't contain a valid alias configuration

I'm building a React server-side renderer and found this can also occur when building a separate server config from scratch. If you're seeing this error, try the following:

  1. Make sure your "entry" value is properly pathed relative to your "context" value. Mine was missing the preceeding "./" before the entry file name.
  2. Make sure you have your "resolve" value included. Your imports on anything in node_modules will default to looking in your "context" folder, otherwise.

Example:

const serverConfig = {
name: 'server',
context: path.join(__dirname, 'src'),
entry: {serverEntry: ['./server-entry.js']},
output: {
    path: path.join(__dirname, 'public'),
    filename: 'server.js',
    publicPath: 'public/',
    libraryTarget: 'commonjs2'
},
module: {
    rules: [/*...*/]
},
resolveLoader: {
    modules: [
        path.join(__dirname, 'node_modules')
    ]
},
resolve: {
    modules: [
        path.join(__dirname, 'node_modules')
    ]
}
};

Creating .pem file for APNS?

I never remember the openssl command needed to create a .pem file, so I made this bash script to simplify the process:

#!/bin/bash
if [ $# -eq 2 ]
then
    echo "Signing $1..."

    if ! openssl pkcs12 -in $1 -out $2 -nodes -clcerts; then
        echo "Error signing certificate."
    else
        echo "Certificate created successfully: $2"
    fi
else
    if [ $# -gt 2 ]
    then
        echo "Too many arguments"
        echo "Syntax: $0 <input.p12> <output.pem>"
    else
        echo "Missing arguments"
        echo "Syntax: $0 <input.p12> <output.pem>"
    fi
fi

Name it, for example, signpem.sh and save it on your user's folder (/Users/<username>?). After creating the file, do a chmod +x signpem.sh to make it executable and then you can run:

~/signpem myCertificate.p12 myCertificate.pem

And myCertificate.pem will be created.

How to calculate date difference in JavaScript?

_x000D_
_x000D_
function daysInMonth (month, year) {_x000D_
    return new Date(year, month, 0).getDate();_x000D_
}_x000D_
function getduration(){_x000D_
_x000D_
let A= document.getElementById("date1_id").value_x000D_
let B= document.getElementById("date2_id").value_x000D_
_x000D_
let C=Number(A.substring(3,5))_x000D_
let D=Number(B.substring(3,5))_x000D_
let dif=D-C_x000D_
let arr=[];_x000D_
let sum=0;_x000D_
for (let i=0;i<dif+1;i++){_x000D_
  sum+=Number(daysInMonth(i+C,2019))_x000D_
}_x000D_
let sum_alter=0;_x000D_
for (let i=0;i<dif;i++){_x000D_
  sum_alter+=Number(daysInMonth(i+C,2019))_x000D_
}_x000D_
let no_of_month=(Number(B.substring(3,5)) - Number(A.substring(3,5)))_x000D_
let days=[];_x000D_
if ((Number(B.substring(3,5)) - Number(A.substring(3,5)))>0||Number(B.substring(0,2)) - Number(A.substring(0,2))<0){_x000D_
days=Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter_x000D_
}_x000D_
_x000D_
if ((Number(B.substring(3,5)) == Number(A.substring(3,5)))){_x000D_
console.log(Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter)_x000D_
}_x000D_
_x000D_
time_1=[]; time_2=[]; let hour=[];_x000D_
 time_1=document.getElementById("time1_id").value_x000D_
 time_2=document.getElementById("time2_id").value_x000D_
  if (time_1.substring(0,2)=="12"){_x000D_
     time_1="00:00:00 PM"_x000D_
  }_x000D_
if (time_1.substring(9,11)==time_2.substring(9,11)){_x000D_
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))_x000D_
}_x000D_
if (time_1.substring(9,11)!=time_2.substring(9,11)){_x000D_
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))+12_x000D_
}_x000D_
let min=Math.abs(Number(time_1.substring(3,5))-Number(time_2.substring(3,5)))_x000D_
document.getElementById("duration_id").value=days +" days "+ hour+"  hour " + min+"  min " _x000D_
}
_x000D_
<input type="text" id="date1_id" placeholder="28/05/2019">_x000D_
<input type="text" id="date2_id" placeholder="29/06/2019">_x000D_
<br><br>_x000D_
<input type="text" id="time1_id" placeholder="08:01:00 AM">_x000D_
<input type="text" id="time2_id" placeholder="00:00:00 PM">_x000D_
<br><br>_x000D_
<button class="text" onClick="getduration()">Submit </button>_x000D_
<br><br>_x000D_
<input type="text" id="duration_id" placeholder="days hour min">
_x000D_
_x000D_
_x000D_

Python: Removing spaces from list objects

List comprehension [num.strip() for num in hello] is the fastest.

>>> import timeit
>>> hello = ['999 ',' 666 ']

>>> t1 = lambda: map(str.strip, hello)
>>> timeit.timeit(t1)
1.825870468015296

>>> t2 = lambda: list(map(str.strip, hello))
>>> timeit.timeit(t2)
2.2825958750515269

>>> t3 = lambda: [num.strip() for num in hello]
>>> timeit.timeit(t3)
1.4320335103944899

>>> t4 = lambda: [num.replace(' ', '') for num in hello]
>>> timeit.timeit(t4)
1.7670568718943969

Available text color classes in Bootstrap

You can use text classes:

.text-primary
.text-secondary
.text-success
.text-danger
.text-warning
.text-info
.text-light
.text-dark
.text-muted
.text-white

use text classes in any tag where needed.

<p class="text-primary">.text-primary</p>
<p class="text-secondary">.text-secondary</p>
<p class="text-success">.text-success</p>
<p class="text-danger">.text-danger</p>
<p class="text-warning">.text-warning</p>
<p class="text-info">.text-info</p>
<p class="text-light bg-dark">.text-light</p>
<p class="text-dark">.text-dark</p>
<p class="text-muted">.text-muted</p>
<p class="text-white bg-dark">.text-white</p>

You can add your own classes or modify above classes as your requirement.

What are the best practices for using a GUID as a primary key, specifically regarding performance?

If you use GUID as primary key and create clustered index then I suggest use the default of NEWSEQUENTIALID() value for it.

How to loop through each and every row, column and cells in a GridView and get its value

The easiest would be using a foreach:

foreach(GridViewRow row in GridView2.Rows)
{
    // here you'll get all rows with RowType=DataRow
    // others like Header are omitted in a foreach
}

Edit: According to your edits, you are accessing the column incorrectly, you should start with 0:

foreach(GridViewRow row in GridView2.Rows)
{
    for(int i = 0; i < GridView2.Columns.Count; i++)
    {
        String header = GridView2.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

Start/Stop and Restart Jenkins service on Windows

Open Console/Command line --> Go to your Jenkins installation directory. Execute the following commands respectively:

to stop:
jenkins.exe stop

to start:
jenkins.exe start

to restart:
jenkins.exe restart

I want to show all tables that have specified column name

select table_name
from information_schema.columns
where COLUMN_NAME = 'MyColumn'

How to send email attachments?

You can also specify the type of attachment you want in your e-mail, as an example I used pdf:

def send_email_pdf_figs(path_to_pdf, subject, message, destination, password_path=None):
    ## credits: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script
    from socket import gethostname
    #import email
    from email.mime.application import MIMEApplication
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    import smtplib
    import json

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    with open(password_path) as f:
        config = json.load(f)
        server.login('[email protected]', config['password'])
        # Craft message (obj)
        msg = MIMEMultipart()

        message = f'{message}\nSend from Hostname: {gethostname()}'
        msg['Subject'] = subject
        msg['From'] = '[email protected]'
        msg['To'] = destination
        # Insert the text to the msg going by e-mail
        msg.attach(MIMEText(message, "plain"))
        # Attach the pdf to the msg going by e-mail
        with open(path_to_pdf, "rb") as f:
            #attach = email.mime.application.MIMEApplication(f.read(),_subtype="pdf")
            attach = MIMEApplication(f.read(),_subtype="pdf")
        attach.add_header('Content-Disposition','attachment',filename=str(path_to_pdf))
        msg.attach(attach)
        # send msg
        server.send_message(msg)

inspirations/credits to: http://linuxcursor.com/python-programming/06-how-to-send-pdf-ppt-attachment-with-html-body-in-python-script

Printing pointers in C

If you pass the name of an array as an argument to a function, it is treated as if you had passed the address of the array. So &s and s are identical arguments. See K&R 5.3. &s[0] is the same as &s, since it takes the address of the first element of the array, which is the same as taking the address of the array itself.

For all the others, although all pointers are essentially memory locations they are still typed, and the compiler will warn about assigning one type of pointer to another.

  • void* p; says p is a memory address, but I don't know what's in the memory
  • char* s; says s is a memory address, and the first byte contains a character
  • char** ps; says ps is a memory address, and the four bytes there (for a 32-bit system) contain a pointer of type char*.

cf http://www.oberon2005.ru/paper/kr_c.pdf (e-book version of K&R)

How can I get the height of an element using css only

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I get the domain originating the request in express.js?

In Express 4.x you can use req.hostname, which returns the domain name, without port. i.e.:

// Host: "example.com:3000"
req.hostname
// => "example.com"

See: http://expressjs.com/en/4x/api.html#req.hostname

Renaming a branch in GitHub

I've found three commands on how you can change your Git branch name, and these commands are a faster way to do that:

git branch -m old_branch new_branch         # Rename branch locally
git push origin :old_branch                 # Delete the old branch
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote

If you need step-by-step you can read this great article:

How to Rename Git Local and Remote Branches

link_to method and click event in Rails

You can use link_to_function (removed in Rails 4.1):

link_to_function 'My link with obtrusive JavaScript', 'alert("Oh no!")'

Or, if you absolutely need to use link_to:

link_to 'Another link with obtrusive JavaScript', '#',
        :onclick => 'alert("Please no!")'

However, putting JavaScript right into your generated HTML is obtrusive, and is bad practice.

Instead, your Rails code should simply be something like this:

link_to 'Link with unobtrusive JavaScript',
        '/actual/url/in/case/javascript/is/broken',
        :id => 'my-link'

And assuming you're using the Prototype JS framework, JS like this in your application.js:

$('my-link').observe('click', function (event) {
  alert('Hooray!');
  event.stop(); // Prevent link from following through to its given href
});

Or if you're using jQuery:

$('#my-link').click(function (event) {
  alert('Hooray!');
  event.preventDefault(); // Prevent link from following its href
});

By using this third technique, you guarantee that the link will follow through to some other page—not just fail silently—if JavaScript is unavailable for the user. Remember, JS could be unavailable because the user has a poor internet connection (e.g., mobile device, public wifi), the user or user's sysadmin disabled it, or an unexpected JS error occurred (i.e., developer error).

is it possible to get the MAC address for machine using nmap

Not using nmap... but this is an alternative...

arp -n|grep -i B0:D3:93|awk '{print $1}'

Waiting for background processes to finish before exiting script

GNU parallel and xargs

These two tools that can make scripts simpler, and also control the maximum number of threads (thread pool). E.g.:

seq 10 | xargs -P4 -I'{}' echo '{}'

or:

seq 10 | parallel -j4  echo '{}'

See also: how to write a process-pool bash shell

How to run cron job every 2 hours

To Enter into crontab :

crontab -e

write this into the file:

0 */2 * * * python/php/java yourfilepath

Example :0 */2 * * * python ec2-user/home/demo.py

and make sure you have keep one blank line after the last cron job in your crontab file

How to access Winform textbox control from another class?

I Found an easy way to do this,I've tested it,it works Properly. First I created a Windows Project,on the form I Inserted a TextBox and I named it textBox1 then I inserted a button named button1,then add a class named class1. in the class1 I created a TextBox:

class class1
    {
     public static TextBox txt1=new TextBox();  //a global textbox to interfece with      form1
    public static void Hello()
      {
       txt1.Text="Hello";
      }
    }

Now in your Form Do this:

public partial class Form1 : Form
    {
     public Form1()
     {
      InitializeComponent();  
     }
     private void button1_Click(object sender, EventArgs e)
      {
       class1.txt1=textBox1;
       class1.Hello();
       }
    }

in the button1_Click I coppied the object textBox1 into txt1,so now txt1 has the properties of textBox1 and u can change textBox1 text in another form or class.

Best way to increase heap size in catalina.bat file

increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin

enter image description here

heap size can be changed based on Requirements.

  set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

POST: sending a post request in a url itself

In windows this command does not work for me..I have tried the following command and it works..using this command I created session in couchdb sync gate way for the specific user...

curl -v -H "Content-Type: application/json" -X POST -d "{ \"name\": \"abc\",\"password\": \"abc123\" }" http://localhost:4984/todo/_session

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

Key elements of a zero-downtime migration is:

In short:

  1. setup a target redis (empty) as slave of a source redis (with your data)
  2. wait for replication finish
  3. permit writes to a target redis (which is currently slave)
  4. switch your apps to a target redis
  5. wait for finish datastream from master to slave
  6. turn a target redis from master to slave

Additionally redis have options which allows to disable a source redis to accept writes right after detaching a target:

  • min-slaves-to-write
  • min-slaves-max-lag

This topic covered by

Very good explanation from RedisLabs team https://redislabs.com/blog/real-time-synchronization-tool-for-redis-migration (use web.archive.org)

And even their interactive tool for migrate: https://github.com/RedisLabs/redis-migrate

How do you get git to always pull from a specific branch?

Your immediate question of how to make it pull master, you need to do what it says. Specify the refspec to pull from in your branch config.

[branch "master"]
    merge = refs/heads/master

What's the yield keyword in JavaScript?

To give a complete answer: yield is working similar to return, but in a generator.

As for the commonly given example, this works as follows:

function *squareGen(x) {
    var i;
    for (i = 0; i < x; i++) {
        yield i*i;
    }
}

var gen = squareGen(3);

console.log(gen.next().value); // prints 0
console.log(gen.next().value); // prints 1
console.log(gen.next().value); // prints 4

But theres also a second purpose of the yield keyword. It can be used to send values to the generator.

To clarify, a small example:

function *sendStuff() {
    y = yield (0);
    yield y*y;
}

var gen = sendStuff();

console.log(gen.next().value); // prints 0
console.log(gen.next(2).value); // prints 4

This works, as the value 2 is assigned to y, by sending it to the generator, after it stopped at the first yield (which returned 0).

This enables us to to some really funky stuff. (look up coroutine)

RegEx for Javascript to allow only alphanumeric

Save this constant

const letters = /^[a-zA-Z0-9]+$/

now, for checking part use .match()

const string = 'Hey there...' // get string from a keyup listner
let id = ''
// iterate through each letters
for (var i = 0; i < string.length; i++) {
  if (string[i].match(letters) ) {
    id += string[i]
  } else {
    // In case you want to replace with something else
    id += '-'  
  }
}
return id

How to convert a Map to List in Java?

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("java", 20);
    map.put("C++", 45);

    Set <Entry<String, Integer>> set = map.entrySet();

    List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);

we can have both key and value pair in list.Also can get key and value using Map.Entry by iterating over list.

How can I return two values from a function in Python?

def test():
    r1 = 1
    r2 = 2
    r3 = 3
    return r1, r2, r3

x,y,z = test()
print x
print y
print z


> test.py 
1
2
3

Importing larger sql files into MySQL

Since you state (in a clarification comment to another person's answer) that you are using MySQL Workbench, you could try using the "sql script" option there. This will avoid the need to use the commandline (although I agree with the other answer that it's good to climb up on that horse and learn to ride).

  1. In MySQL Workbench, go to File menu, then select "open script". This is probably going to take a long time and might even crash the app since it's not made to open things that are as big as what you describe.

  2. The better way is to use the commandline. Make sure you have MySQL client installed on your machine. This means the actual MySQL (not Workbench GUI or PhpMyAdmin or anything like that). Here is a link describing the command-line tool. Once you have that downloaded and installed, open a terminal window on your machine, and you have two choices for slurping data from your file system (such as in a backup file) up into your target database. One is to use 'source' command and the other is to use the < redirection operator.

Option 1: from the directory where your backup file is:

$mysql -u username -p -h hostname databasename < backupfile.sql

Option 2: from the directory where your backup file is:

$mysql -u username -p -h hostname
[enter your password]
> use databasename;
> source backupfile.sql

Obviously, both of these options require that you have a backup file that is SQL.

How to sum all column values in multi-dimensional array?

You can try this:

$c = array_map(function () {
      return array_sum(func_get_args());
     },$a, $b);

and finally:

print_r($c);

jQuery Ajax File Upload

Using pure js it is easier

_x000D_
_x000D_
async function saveFile(inp) 
{
    let formData = new FormData();           
    formData.append("file", inp.files[0]);
    await fetch('/upload/somedata', {method: "POST", body: formData});    
    alert('success');
}
_x000D_
<input type="file" onchange="saveFile(this)" >
_x000D_
_x000D_
_x000D_

  • In server side you can read original file name (and other info) which is automatically included to request.
  • You do NOT need to set header "Content-Type" to "multipart/form-data" browser will set it automatically
  • This solutions should work on all major browsers.

Here is more developed snippet with error handling, timeout and additional json sending

_x000D_
_x000D_
async function saveFile(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user));  
    
    const ctrl = new AbortController() // timeout
    setTimeout(() => ctrl.abort(), 50000);

    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
       alert('success');
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}
_x000D_
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
_x000D_
_x000D_
_x000D_

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

The HTTP Content-Type for .ogg should be application/ogg (video/ogg for .ogv) and for .mp4 it should be video/mp4. You can check using the Web Sniffer.

How can I remove all objects but one from the workspace in R?

To keep all objects whose names match a pattern, you could use grep, like so:

to.remove <- ls()
to.remove <- c(to.remove[!grepl("^obj", to.remove)], "to.remove")
rm(list=to.remove)

How to turn off Wifi via ADB?

adb shell "svc wifi enable"

This worked & it makes action in background without opening related option !!

cmake and libpthread

@Manuel was part way there. You can add the compiler option as well, like this:

If you have CMake 3.1.0+, this becomes even easier:

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)

If you are using CMake 2.8.12+, you can simplify this to:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

Older CMake versions may require:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
  set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON) there too.

How do I skip a header from CSV files in Spark?

In PySpark you can use a dataframe and set header as True:

df = spark.read.csv(dataPath, header=True)

How to create id with AUTO_INCREMENT on Oracle?

Oracle Database 12c introduced Identity, an auto-incremental (system-generated) column. In the previous database versions (until 11g), you usually implement an Identity by creating a Sequence and a Trigger. From 12c onward, you can create your own Table and define the column that has to be generated as an Identity.

The following article explains how to use it:

Identity columns - A new entry in Oracle Database 12c

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

How do I insert an image in an activity with android studio?

since you followed the tutorial, I presume you have a screen that says Hello World.

that means you have some code in your layout xml that looks like this

<TextView        
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

you want to display an image, so instead of TextView you want to have ImageView. and instead of a text attribute you want an src attribute, that links to your drawable resource

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/cool_pic"
/>

How to parse JSON string in Typescript

JSON.parse is available in TypeScript, so you can just use it :

JSON.parse('{"name": "Bob", "error": false}') // Returns a value of type 'any'

However, you will often want to parse a JSON object while making sure it matches a certain type, rather than dealing with a value of type any. In that case, you can define a function such as the following :

function parse_json<TargetType extends Object>(
  json: string,
  type_definitions: { [Key in keyof TargetType]: (raw_value: any) => TargetType[Key] }
): TargetType {
  const raw = JSON.parse(json); 
  const result: any = {};
  for (const key in type_definitions) result[key] = type_definitions[key](raw[key]);
  return result;
}

This function takes a JSON string and an object containing individual functions that load each field of the object you are creating. You can use it like so:

const value = parse_json(
  '{"name": "Bob", "error": false}',
  { name: String, error: Boolean, }
);

Use grep to report back only line numbers

If you're open to using AWK:

awk '/textstring/ {print FNR}' textfile

In this case, FNR is the line number. AWK is a great tool when you're looking at grep|cut, or any time you're looking to take grep output and manipulate it.

SQL Server error on update command - "A severe error occurred on the current command"

This error is exactly what it means: Something bad happened, that would not normally happen.

In my most recent case, the REAL error was:

Msg 9002, Level 17, State 2, Procedure MyProcedure, Line 2 [Batch Start Line 3]
The transaction log for database 'MyDb' is full due to 'LOG_BACKUP'.

Here is my checklist of things to try, perhaps in this exact order:

  1. Check if you're out of disk space (this was my real problem; our NOC did not catch this)
  2. Check if you're low on memory
  3. Check if the Windows Event Log shows any serious system failures like hard drives failing
  4. Check if you have any unsafe code loaded through extended procedures or SQLCLR unsafe assemblies that could de-stabilize the SQLServer.exe process.
  5. Run CheckDB to see if your database has any corruption issues. On a very large database, if this stored procedure only touches a sub-set of tables, you can save time by seeing which partitions (filegroups) the stored procedure touches, and only checking those specific filegroups.
    1. I would do this for your database and master db as well.

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

enter image description hereI found a shortcut: File - Project Structure - Tab:Dependencies Click on the green + sign, select support-v4 (or any other you need), click OK.

now go to your gradle file and see that is been added

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

Detecting superfluous #includes in C/C++?

If you are using Eclipse CDT you can try http://includator.com which is free for beta testers (at the time of this writing) and automatically removes superfluous #includes or adds missing ones. For those users who have FlexeLint or PC-Lint and are using Elicpse CDT, http://linticator.com might be an option (also free for beta test). While it uses Lint's analysis, it provides quick-fixes for automatically remove the superfluous #include statements.

Call to getLayoutInflater() in places not in activity

or

View.inflate(context, layout, parent)

Double decimal formatting in Java

Works 100%.

import java.text.DecimalFormat;

public class Formatting {

    public static void main(String[] args) {
        double value = 22.2323242434342;
        // or  value = Math.round(value*100) / 100.0;

        System.out.println("this is before formatting: "+value);
        DecimalFormat df = new DecimalFormat("####0.00");

        System.out.println("Value: " + df.format(value));
    }

}

Oracle client and networking components were not found

Simplest solution: The Oracle client is not installed on the remote server where the SSIS package is being executed.

Slightly less simple solution: The Oracle client is installed on the remote server, but in the wrong bit-count for the SSIS installation. For example, if the 64-bit Oracle client is installed but SSIS is being executed with the 32-bit dtexec executable, SSIS will not be able to find the Oracle client. The solution in this case would be to install the 32-bit Oracle client side-by-side with the 64-bit client.

jQuery Ajax PUT with parameters

For others who wind up here like I did, you can use AJAX to do a PUT with parameters, but they are sent as the body, not as query strings.

MySQL create stored procedure syntax with delimiter

Here is the sample MYSQL Stored Procedure with delimiter and how to call..

DELIMITER $$

DROP PROCEDURE IF EXISTS `sp_user_login` $$
CREATE DEFINER=`root`@`%` PROCEDURE `sp_user_login`(
  IN loc_username VARCHAR(255),
  IN loc_password VARCHAR(255)
)
BEGIN

  SELECT user_id,
         user_name,
         user_emailid,
         user_profileimage,
         last_update
    FROM tbl_user
   WHERE user_name = loc_username
     AND password = loc_password
     AND status = 1;

END $$

DELIMITER ;

and call by, mysql_connection specification and

$loginCheck="call sp_user_login('".$username."','".$password."');";

it will return the result from the procedure.

How to declare 2D array in bash

For simulating a 2-dimensional array, I first load the first n-elements (the elements of the first column)

local pano_array=()  

i=0

for line in $(grep  "filename" "$file")
do 
  url=$(extract_url_from_xml $line)
  pano_array[i]="$url"
  i=$((i+1))
done

To add the second column, I define the size of the first column and calculate the values in an offset variable

array_len="${#pano_array[@]}"

i=0

while [[ $i -lt $array_len ]]
do
  url="${pano_array[$i]}"
  offset=$(($array_len+i)) 
  found_file=$(get_file $url)
  pano_array[$offset]=$found_file

  i=$((i+1))
done

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.

Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.

How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.

How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.

NodeJs : TypeError: require(...) is not a function

For me, this was an issue with cyclic dependencies.

IOW, module A required module B, and module B required module A.

So in module B, require('./A') is an empty object rather than a function.

How to deal with cyclic dependencies in Node.js

Unmount the directory which is mounted by sshfs in Mac

The following worked for me:

hdiutil detach <path to sshfs mount>

Example:

hdiutil detach /Users/user1/sshfs

One can also locate the volume created by sshfs in Finder, right-click, and select Eject. Which is, to the best of my knowledge, the GUI version of the above command.

Semaphore vs. Monitors - what's the difference?

A semaphore is a signaling mechanism used to coordinate between threads. Example: One thread is downloading files from the internet and another thread is analyzing the files. This is a classic producer/consumer scenario. The producer calls signal() on the semaphore when a file is downloaded. The consumer calls wait() on the same semaphore in order to be blocked until the signal indicates a file is ready. If the semaphore is already signaled when the consumer calls wait, the call does not block. Multiple threads can wait on a semaphore, but each signal will only unblock a single thread.

A counting semaphore keeps track of the number of signals. E.g. if the producer signals three times in a row, wait() can be called three times without blocking. A binary semaphore does not count but just have the "waiting" and "signalled" states.

A mutex (mutual exclusion lock) is a lock which is owned by a single thread. Only the thread which have acquired the lock can realease it again. Other threads which try to acquire the lock will be blocked until the current owner thread releases it. A mutex lock does not in itself lock anything - it is really just a flag. But code can check for ownership of a mutex lock to ensure that only one thread at a time can access some object or resource.

A monitor is a higher-level construct which uses an underlying mutex lock to ensure thread-safe access to some object. Unfortunately the word "monitor" is used in a few different meanings depending on context and platform and context, but in Java for example, a monitor is a mutex lock which is implicitly associated with an object, and which can be invoked with the synchronized keyword. The synchronized keyword can be applied to a class, method or block and ensures only one thread can execute the code at a time.