Programs & Examples On #Messageboard

When should we use Observer and Observable?

If the interviewer asks to implement Observer design pattern without using Observer classes and interfaces, you can use the following simple example!

MyObserver as observer interface

interface MyObserver {

    void update(MyObservable o, Object arg);
}

MyObservable as Observable class

class MyObservable
{
    ArrayList<MyObserver> myObserverList = new ArrayList<MyObserver>();

    boolean changeFlag = false;

    public void notifyObservers(Object o)
    {
        if (hasChanged())
        {
            for(MyObserver mo : myObserverList) {
                mo.update(this, o);
            }
            clearChanged();
        }
    }


    public void addObserver(MyObserver o) {
        myObserverList.add(o);        
    }

    public void setChanged() {
        changeFlag = true;
    }

    public boolean hasChanged() {
        return changeFlag;
    }

    protected void clearChanged() {
        changeFlag = false;
    }

    // ...
}

Your example with MyObserver and MyObservable!

class MessageBoard extends MyObservable {
  private String message;

  public String getMessage() {
    return message;
  }

  public void changeMessage(String message) {
    this.message = message;
    setChanged();
    notifyObservers(message);
  }

  public static void main(String[] args) {
    MessageBoard board = new MessageBoard();
    Student bob = new Student();
    Student joe = new Student();
    board.addObserver(bob);
    board.addObserver(joe);
    board.changeMessage("More Homework!");
  }
}

class Student implements MyObserver {

  @Override
  public void update(MyObservable o, Object arg) {
    System.out.println("Message board changed: " + arg);
  }

}

Node.js for() loop returning the same values at each loop

  for(var i = 0; i < BoardMessages.length;i++){
        (function(j){
            console.log("Loading message %d".green, j);
            htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);
        })(i);
  }

That should work; however, you should never create a function in a loop. Therefore,

  for(var i = 0; i < BoardMessages.length;i++){
        composeMessage(BoardMessages[i]);
  }

  function composeMessage(message){
      console.log("Loading message %d".green, message);
      htmlMessageboardString += MessageToHTMLString(message);
  }

Is there a command like "watch" or "inotifywait" on the Mac?

If you want to use NodeJS, you can use a package called chokidar (or chokidar-cli actually) for the watching and then use rsync (included with Mac):

Rsync command:

$ rsync -avz --exclude 'some-file' --exclude 'some-dir' './' '/my/destination'

Chokidar cli (installed globally via npm):

chokidar \"**/*\" -c \"your-rsync-command-above\"

java.util.Date to XMLGregorianCalendar

Assuming you are decoding or encoding xml and using JAXB, then it's possible to replace the dateTime binding entirely and use something else than `XMLGregorianCalendar' for every date in the schema.

In that way you can have JAXB do the repetitive stuff while you can spend the time on writing awesome code that delivers value.

Example for a jodatime DateTime: (Doing this with java.util.Date would also work - but with certain limitations. I prefer jodatime and it's copied from my code so I know it works...)

<jxb:globalBindings>
    <jxb:javaType name="org.joda.time.LocalDateTime" xmlType="xs:dateTime"
        parseMethod="test.util.JaxbConverter.parseDateTime"
        printMethod="se.seb.bis.test.util.JaxbConverter.printDateTime" />
    <jxb:javaType name="org.joda.time.LocalDate" xmlType="xs:date"
        parseMethod="test.util.JaxbConverter.parseDate"
        printMethod="test.util.JaxbConverter.printDate" />
    <jxb:javaType name="org.joda.time.LocalTime" xmlType="xs:time"
        parseMethod="test.util.JaxbConverter.parseTime"
        printMethod="test.util.JaxbConverter.printTime" />
    <jxb:serializable uid="2" />
</jxb:globalBindings>

And the converter:

public class JaxbConverter {
static final DateTimeFormatter dtf = ISODateTimeFormat.dateTimeNoMillis();
static final DateTimeFormatter df = ISODateTimeFormat.date();
static final DateTimeFormatter tf = ISODateTimeFormat.time();

public static LocalDateTime parseDateTime(String s) {
    try {
        if (StringUtils.trimToEmpty(s).isEmpty())
            return null;
        LocalDateTime r = dtf.parseLocalDateTime(s);
        return r;
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static String printDateTime(LocalDateTime d) {
    try {
        if (d == null)
            return null;
        return dtf.print(d);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static LocalDate parseDate(String s) {
    try {
        if (StringUtils.trimToEmpty(s).isEmpty())
            return null;
        return df.parseLocalDate(s);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static String printDate(LocalDate d) {
    try {
        if (d == null)
            return null;
        return df.print(d);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static String printTime(LocalTime d) {
    try {
        if (d == null)
            return null;
        return tf.print(d);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static LocalTime parseTime(String s) {
    try {
        if (StringUtils.trimToEmpty(s).isEmpty())
            return null;
        return df.parseLocalTime(s);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

See here: how replace XmlGregorianCalendar by Date?

If you are happy to just map to an instant based on the timezone+timestamp, and the original timezone is not really relevant, then java.util.Date is probably fine too.

Vue.js data-bind style backgroundImage not working

Another solution:

<template>
  <div :style="cssProps"></div>
</template>

<script>
  export default {
    data() {
      return {
        cssProps: {
          backgroundImage: `url(${require('@/assets/path/to/your/img.jpg')})`
        }
      }
    }
  }
</script>

What makes this solution more convenient? Firstly, it's cleaner. And then, if you're using Vue CLI (I assume you do), you can load it with webpack.

Note: don't forget that require() is always relative to the current file's path.

What does "implements" do on a class?

You should look into Java's interfaces. A quick Google search revealed this page, which looks pretty good.

I like to think of an interface as a "promise" of sorts: Any class that implements it has certain behavior that can be expected of it, and therefore you can put an instance of an implementing class into an interface-type reference.

A simple example is the java.lang.Comparable interface. By implementing all methods in this interface in your own class, you are claiming that your objects are "comparable" to one another, and can be partially ordered.

Implementing an interface requires two steps:

  1. Declaring that the interface is implemented in the class declaration
  2. Providing definitions for ALL methods that are part of the interface.

Interface java.lang.Comparable has just one method in it, public int compareTo(Object other). So you need to provide that method.

Here's an example. Given this class RationalNumber:

public class RationalNumber
{
    public int numerator;
    public int denominator;

    public RationalNumber(int num, int den)
    {
        this.numerator = num;
        this.denominator = den;
    }
}

(Note: It's generally bad practice in Java to have public fields, but I am intending this to be a very simple plain-old-data type so I don't care about public fields!)

If I want to be able to compare two RationalNumber instances (for sorting purposes, maybe?), I can do that by implementing the java.lang.Comparable interface. In order to do that, two things need to be done: provide a definition for compareTo and declare that the interface is implemented.

Here's how the fleshed-out class might look:

public class RationalNumber implements java.lang.Comparable
{
    public int numerator;
    public int denominator;

    public RationalNumber(int num, int den)
    {
        this.numerator = num;
        this.denominator = den;
    }

    public int compareTo(Object other)
    {
        if (other == null || !(other instanceof RationalNumber))
        {
            return -1; // Put this object before non-RationalNumber objects
        }

        RationalNumber r = (RationalNumber)other;

        // Do the calculations by cross-multiplying. This isn't really important to
        // the answer, but the point is we're comparing the two rational numbers.
        // And no, I don't care if it's mathematically inaccurate.

        int myTotal = this.numerator * other.denominator;
        int theirTotal = other.numerator * this.denominator;

        if (myTotal < theirTotal) return -1;
        if (myTotal > theirTotal) return 1;
        return 0;
    }
}

You're probably thinking, what was the point of all this? The answer is when you look at methods like this: sorting algorithms that just expect "some kind of comparable object". (Note the requirement that all objects must implement java.lang.Comparable!) That method can take lists of ANY kind of comparable objects, be they Strings or Integers or RationalNumbers.

NOTE: I'm using practices from Java 1.4 in this answer. java.lang.Comparable is now a generic interface, but I don't have time to explain generics.

What does 'corrupted double-linked list' mean

I ran into this error in some code where someone was calling exit() in one thread about the same time as main() returned, so all the global/static constructors were being kicked off in two separate threads simultaneously.

This error also manifests as double free or corruption, or a segfault/sig11 inside exit() or inside malloc_consolidate, and likely others. The call stack for the malloc_consolidate crash may resemble:

#0  0xabcdabcd in malloc_consolidate () from /lib/libc.so.6
#1  0xabcdabcd in _int_free () from /lib/libc.so.6
#2  0xabcdabcd in operator delete (...)
#3  0xabcdabcd in operator delete[] (...)
(...)

I couldn't get it to exhibit this problem while running under valgrind.

"Could not find bundler" error

I had the same problem. This worked for me:

  1. run rvm/script/rvm and also add it to your .profile or .bash_profile as shown in https://rvm.io/rvm/install/

  2. use bundle without sudo

Delete sql rows where IDs do not have a match from another table

DELETE FROM blob 
WHERE fileid NOT IN 
       (SELECT id 
        FROM files 
        WHERE id is NOT NULL/*This line is unlikely to be needed 
                               but using NOT IN...*/
      )

How to get PID by process name?

For posix (Linux, BSD, etc... only need /proc directory to be mounted) it's easier to work with os files in /proc. It's pure python, no need to call shell programs outside.

Works on python 2 and 3 ( The only difference (2to3) is the Exception tree, therefore the "except Exception", which I dislike but kept to maintain compatibility. Also could've created a custom exception.)

#!/usr/bin/env python

import os
import sys


for dirname in os.listdir('/proc'):
    if dirname == 'curproc':
        continue

    try:
        with open('/proc/{}/cmdline'.format(dirname), mode='rb') as fd:
            content = fd.read().decode().split('\x00')
    except Exception:
        continue

    for i in sys.argv[1:]:
        if i in content[0]:
            print('{0:<12} : {1}'.format(dirname, ' '.join(content)))

Sample Output (it works like pgrep):

phoemur ~/python $ ./pgrep.py bash
1487         : -bash 
1779         : /bin/bash

How do I find where JDK is installed on my windows machine?

Plain and simple on Windows platforms:

where java

How to get xdebug var_dump to show full object/array

I know this is late but it might be of some use:

echo "<pre>";
print_r($array);
echo "</pre>";

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

I have written code that sniffs IE4 or greater and is currently functioning perfectly in sites for my company's clients, as well as my own personal sites.

Include the following enumerated constant and function variables into a javascript include file on your page...

//methods
var BrowserTypes = {
    Unknown: 0,
    FireFox: 1,
    Chrome: 2,
    Safari: 3,
    IE: 4,
    IE7: 5,
    IE8: 6,
    IE9: 7,
    IE10: 8,
    IE11: 8,
    IE12: 8
};

var Browser = function () {
    try {
        //declares
        var type;
        var version;
        var sVersion;

        //process
        switch (navigator.appName.toLowerCase()) {
            case "microsoft internet explorer":
                type = BrowserTypes.IE;
                sVersion = navigator.appVersion.substring(navigator.appVersion.indexOf('MSIE') + 5, navigator.appVersion.length);
                version = parseFloat(sVersion.split(";")[0]);
                switch (parseInt(version)) {
                    case 7:
                        type = BrowserTypes.IE7;
                        break;
                    case 8:
                        type = BrowserTypes.IE8;
                        break;
                    case 9:
                        type = BrowserTypes.IE9;
                        break;
                    case 10:
                        type = BrowserTypes.IE10;
                        break;
                    case 11:
                        type = BrowserTypes.IE11;
                        break;
                    case 12:
                        type = BrowserTypes.IE12;
                        break;
                }
                break;
            case "netscape":
                if (navigator.userAgent.toLowerCase().indexOf("chrome") > -1) { type = BrowserTypes.Chrome; }
                else { if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) { type = BrowserTypes.FireFox } };
                break;
            default:
                type = BrowserTypes.Unknown;
                break;
        }

        //returns
        return type;
    } catch (ex) {
    }
};

Then all you have to do is use any conditional functionality such as...

ie. value = (Browser() >= BrowserTypes.IE) ? node.text : node.textContent;

or WindowWidth = (((Browser() >= BrowserTypes.IE9) || (Browser() < BrowserTypes.IE)) ? window.innerWidth : document.documentElement.clientWidth);

or sJSON = (Browser() >= BrowserTypes.IE) ? xmlElement.text : xmlElement.textContent;

Get the idea? Hope this helps.

Oh, you might want to keep it in mind to QA the Browser() function after IE10 is released, just to verify they didn't change the rules.

How to automatically crop and center an image

I created an angularjs directive using @Russ's and @Alex's answers

Could be interesting in 2014 and beyond :P

html

<div ng-app="croppy">
  <cropped-image src="http://placehold.it/200x200" width="100" height="100"></cropped-image>
</div>

js

angular.module('croppy', [])
  .directive('croppedImage', function () {
      return {
          restrict: "E",
          replace: true,
          template: "<div class='center-cropped'></div>",
          link: function(scope, element, attrs) {
              var width = attrs.width;
              var height = attrs.height;
              element.css('width', width + "px");
              element.css('height', height + "px");
              element.css('backgroundPosition', 'center center');
              element.css('backgroundRepeat', 'no-repeat');
              element.css('backgroundImage', "url('" + attrs.src + "')");
          }
      }
  });

fiddle link

JavaScript query string

It is worth noting, the library that John Slegers mentioned does have a jQuery dependency, however here is a version that is vanilla Javascript.

https://github.com/EldonMcGuinness/querystring.js

I would have simply commented on his post, but I lack the reputation to do so. :/

Example:

The example below process the following, albeit irregular, query string:

?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab 

_x000D_
_x000D_
var qs = "?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab";_x000D_
//var qs = "?=&=";_x000D_
//var qs = ""_x000D_
_x000D_
var results = querystring(qs);_x000D_
_x000D_
(document.getElementById("results")).innerHTML =JSON.stringify(results, null, 2);
_x000D_
<script _x000D_
src="https://rawgit.com/EldonMcGuinness/querystring.js/master/dist/querystring.min.js"></script>_x000D_
<pre id="results">RESULTS: Waiting...</pre>
_x000D_
_x000D_
_x000D_

How to secure RESTful web services?

There's another, very secure method. It's client certificates. Know how servers present an SSL Cert when you contact them on https? Well servers can request a cert from a client so they know the client is who they say they are. Clients generate certs and give them to you over a secure channel (like coming into your office with a USB key - preferably a non-trojaned USB key).

You load the public key of the cert client certificates (and their signer's certificate(s), if necessary) into your web server, and the web server won't accept connections from anyone except the people who have the corresponding private keys for the certs it knows about. It runs on the HTTPS layer, so you may even be able to completely skip application-level authentication like OAuth (depending on your requirements). You can abstract a layer away and create a local Certificate Authority and sign Cert Requests from clients, allowing you to skip the 'make them come into the office' and 'load certs onto the server' steps.

Pain the neck? Absolutely. Good for everything? Nope. Very secure? Yup.

It does rely on clients keeping their certificates safe however (they can't post their private keys online), and it's usually used when you sell a service to clients rather then letting anyone register and connect.

Anyway, it may not be the solution you're looking for (it probably isn't to be honest), but it's another option.

How to fit in an image inside span tag?

Try using a div tag and block for span!

<div>
  <span style="padding-right:3px; padding-top: 3px; display:block;">
    <img class="manImg" src="images/ico_mandatory.gif"></img>
  </span>
</div>

How to get substring from string in c#?

Riya,

Making the assumption that you want to split on the full stop (.), then here's an approach that would capture all occurences:

// add @ to the string to allow split over multiple lines 
// (display purposes to save scroll bar appearing on SO question :))
string strBig = @"Retrieves a substring from this instance. 
            The substring starts at a specified character position. great";

// split the string on the fullstop, if it has a length>0
// then, trim that string to remove any undesired spaces
IEnumerable<string> subwords = strBig.Split('.')
    .Where(x => x.Length > 0).Select(x => x.Trim());

// iterate around the new 'collection' to sanity check it
foreach (var subword in subwords)
{
    Console.WriteLine(subword);
}

enjoy...

Setting up and using Meld as your git difftool and mergetool

While the other answer is correct, here's the fastest way to just go ahead and configure Meld as your visual diff tool. Just copy/paste this:

git config --global diff.tool meld
git config --global difftool.prompt false

Now run git difftool in a directory and Meld will be launched for each different file.

Side note: Meld is surprisingly slow at comparing CSV files, and no Linux diff tool I've found is faster than this Windows tool called Compare It! (last updated in 2010).

break/exit script

Not pretty, but here is a way to implement an exit() command in R which works for me.

exit <- function() {
  .Internal(.invokeRestart(list(NULL, NULL), NULL))
}

print("this is the last message")
exit()
print("you should not see this")

Only lightly tested, but when I run this, I see this is the last message and then the script aborts without any error message.

How to replace four spaces with a tab in Sublime Text 2?

You could add easy key binding:

Preference > Key binding - user :

[
    { "keys": ["super+l"], "command": "reindent"},
]

Now select the line or file and hit: command + l

sending email via php mail function goes to spam

If you are sending this through your own mail server you might need to add a "Sender" header which will contain an email address of from your own domain. Gmail will probably be spamming the email because the FROM address is a gmail address but has not been sent from their own server.

How to make a gap between two DIV within the same column

I know this was an old answer, but i would like to share my simple solution.

give style="margin-top:5px"

<div style="margin-top:5px">
  div 1
</div>
<div style="margin-top:5px">
  div2 elements
</div> 
div3 elements

Clearing an input text field in Angular2

You can just change the reference of input value, as below

<div>
    <input type="text" placeholder="Search..." #reference>
    <button (click)="reference.value=''">Clear</button>
</div>

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

Do the simple things first.

Check that part of your solution is not locked by a running process.

For instance, I ran "InstallUtil ' on my windows service(which I normally unit test from a console).

This locked some of my dlls in the bin folder of the windows service project. When I did a rebuild I got the exception in this issue.

I stopped the windows service, rebuilt and it succeeded.

Check Windows Task Manager for your Application, before doing any of the advance steps in this issue.

So when you hear footsteps, think horses not zebras! (from medical student friend)

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

How to center horizontal table-cell

Sometimes you have things other than text inside a table cell that you'd like to be horizontally centered. In order to do this, first set up some css...

<style>
    div.centered {
        margin: auto;
        width: 100%;
        display: flex;
        justify-content: center;
    }
</style>

Then declare a div with class="centered" inside each table cell you want centered.

<td>
    <div class="centered">
        Anything: text, controls, etc... will be horizontally centered.
    </div>
</td>

Safely casting long to int in Java

here is a solution, in case you don't care about value in case it is bigger then needed ;)

public static int safeLongToInt(long l) {
    return (int) Math.max(Math.min(Integer.MAX_VALUE, l), Integer.MIN_VALUE);
}

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

Given a column of numbers:

lst = []
cols = ['A']
for a in range(100, 105):
    lst.append([a])
df = pd.DataFrame(lst, columns=cols, index=range(5))
df

    A
0   100
1   101
2   102
3   103
4   104

You can reference the previous row with shift:

df['Change'] = df.A - df.A.shift(1)
df

    A   Change
0   100 NaN
1   101 1.0
2   102 1.0
3   103 1.0
4   104 1.0

Razor Views not seeing System.Web.Mvc.HtmlHelper

I had run a project clean, and installed or reinstalled everything and was still getting lots of Intellisense errors, even though my site was compiling and running fine. Intellisense finally worked for me when I changed the version numbers in my web.config file in the Views folder. In my case I'm coding a module in Orchard, which runs in an MVC area, but I think this will help anyone using the latest release of MVC. Here is my web.config from the Views folder

    <?xml version="1.0"?>
    <configuration>
      <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
          <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
      </configSections>

      <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="Orchard.Mvc.ViewEngines.Razor.WebViewPage">
          <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="System.Linq" />
            <add namespace="System.Collections.Generic" />
          </namespaces>
        </pages>
      </system.web.webPages.razor>

      <system.web>

        <!--
            Enabling request validation in view pages would cause validation to occur
            after the input has already been processed by the controller. By default
            MVC performs request validation before a controller processes the input.
            To change this behavior apply the ValidateInputAttribute to a
            controller or action.
        -->
        <pages
            validateRequest="false"
            pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"
            pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"
            userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
          <controls>
            <add assembly="System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" namespace="System.Web.Mvc" tagPrefix="mvc" />
          </controls>
        </pages>
      </system.web>

      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />

        <handlers>
          <remove name="BlockViewHandler"/>
          <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
        </handlers>
      </system.webServer>
    </configuration>

Git: How to update/checkout a single file from remote origin master?

git archive --format=zip --remote=ssh://<user>@<host>/repos/<repo name> <tag or HEAD> <filename> > <output file name>.zip

How can I remove an element from a list, with lodash?

In Addition to @thefourtheye answer, using predicate instead of traditional anonymous functions:

  _.remove(obj.subTopics, (currentObject) => {
        return currentObject.subTopicId === stToDelete;
    });

OR

obj.subTopics = _.filter(obj.subTopics, (currentObject) => {
    return currentObject.subTopicId !== stToDelete;
});

What is the difference between window, screen, and document in Javascript?

The window is the actual global object.

The screen is the screen, it contains properties about the user's display.

The document is where the DOM is.

Git command to display HEAD commit id?

According to https://git-scm.com/docs/git-log, for more pretty output in console you can use --decorate argument of git-log command:

git log --pretty=oneline --decorate

will print:

2a5ccd714972552064746e0fb9a7aed747e483c7 (HEAD -> master) New commit
fe00287269b07e2e44f25095748b86c5fc50a3ef (tag: v1.1-01) Commit 3
08ed8cceb27f4f5e5a168831d20a9d2fa5c91d8b (tag: v1.1, tag: v1.0-0.1) commit 1
116340f24354497af488fd63f4f5ad6286e176fc (tag: v1.0) second
52c1cdcb1988d638ec9e05a291e137912b56b3af test

How to find a number in a string using JavaScript?

I thought I'd add my take on this since I'm only interested in the first integer I boiled it down to this:

let errorStringWithNumbers = "error: 404 (not found)";        
let errorNumber = parseInt(errorStringWithNumbers.toString().match(/\d+/g)[0]);

.toString() is added only if you get the "string" from an fetch error. If not, then you can remove it from the line.

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

Here's an alternative solution - since in most browsers the navigation controls (the nav bar, tabs, etc.) are located above the page content area, you can detect the mouse pointer leaving the page via the top and display a "before you leave" dialog. It's completely unobtrusive and it allows you to interact with the user before they actually perform the action to leave.

$(document).bind("mouseleave", function(e) {
    if (e.pageY - $(window).scrollTop() <= 1) {    
        $('#BeforeYouLeaveDiv').show();
    }
});

The downside is that of course it's a guess that the user actually intends to leave, but in the vast majority of cases it's correct.

What is the regex for "Any positive integer, excluding 0"

^\d*[1-9]\d*$

this can include all positive values, even if it is padded by Zero in the front

Allows

1

01

10

11 etc

do not allow

0

00

000 etc..

SMTP error 554

Can be caused by a miss configured SPF record on the senders end.

What does string::npos mean in this code?

we have to use string::size_type for the return type of the find function otherwise the comparison with string::npos might not work. size_type, which is defined by the allocator of the string, must be an unsigned integral type. The default allocator, allocator, uses type size_t as size_type. Because -1 is converted into an unsigned integral type, npos is the maximum unsigned value of its type. However, the exact value depends on the exact definition of type size_type. Unfortunately, these maximum values differ. In fact, (unsigned long)-1 differs from (unsigned short)-1 if the size of the types differs. Thus, the comparison

idx == std::string::npos

might yield false if idx has the value -1 and idx and string::npos have different types:

std::string s;
...
int idx = s.find("not found"); // assume it returns npos
if (idx == std::string::npos) { // ERROR: comparison might not work
...
}

One way to avoid this error is to check whether the search fails directly:

if (s.find("hi") == std::string::npos) {
...
}

However, often you need the index of the matching character position. Thus, another simple solution is to define your own signed value for npos:

const int NPOS = -1;

Now the comparison looks a bit different and even more convenient:

if (idx == NPOS) { // works almost always
...
}

Access VBA | How to replace parts of a string with another string

I was reading this thread and would like to add information even though it is surely no longer timely for the OP.

BiggerDon above points out the difficulty of rote replacing "North" with "N". A similar problem exists with "Avenue" to "Ave" (e.g. "Avenue of the Americas" becomes "Ave of the Americas": still understandable, but probably not what the OP wants.

The replace() function is entirely context-free, but addresses are not. A complete solution needs to have additional logic to interpret the context correctly, and then apply replace() as needed.

Databases commonly contain addresses, and so I wanted to point out that the generalized version of the OP's problem as applied to addresses within the United States has been addressed (humor!) by the Coding Accuracy Support System (CASS). CASS is a database tool that accepts a U.S. address and completes or corrects it to meet a standard set by the U.S. Postal Service. The Wikipedia entry https://en.wikipedia.org/wiki/Postal_address_verification has the basics, and more information is available at the Post Office: https://ribbs.usps.gov/index.cfm?page=address_info_systems

Creating all possible k combinations of n items in C++

Here is an algorithm i came up with for solving this problem. You should be able to modify it to work with your code.

void r_nCr(const unsigned int &startNum, const unsigned int &bitVal, const unsigned int &testNum) // Should be called with arguments (2^r)-1, 2^(r-1), 2^(n-1)
{
    unsigned int n = (startNum - bitVal) << 1;
    n += bitVal ? 1 : 0;

    for (unsigned int i = log2(testNum) + 1; i > 0; i--) // Prints combination as a series of 1s and 0s
        cout << (n >> (i - 1) & 1);
    cout << endl;

    if (!(n & testNum) && n != startNum)
        r_nCr(n, bitVal, testNum);

    if (bitVal && bitVal < testNum)
        r_nCr(startNum, bitVal >> 1, testNum);
}

You can see an explanation of how it works here.

How do you enable mod_rewrite on any OS?

No, you should not need to. mod_rewrite is an Apache module. It has nothing to do with php.ini.

css3 text-shadow in IE9

I was looking for a cross-browser text-stroke solution that works when overlaid on background images. think I have a solution for this that doesn't involve extra mark-up, js and works in IE7-9 (I haven't tested 6), and doesn't cause aliasing problems.

This is a combination of using CSS3 text-shadow, which has good support except IE (http://caniuse.com/#search=text-shadow), then using a combination of filters for IE. CSS3 text-stroke support is poor at the moment.

IE Filters

The glow filter (http://www.impressivewebs.com/css3-text-shadow-ie/) looks terrible, so I didn't use that.

David Hewitt's answer involved adding dropshadow filters in a combination of directions. ClearType is then removed unfortunately so we end up with badly aliased text.

I then combined some of the elements suggested on useragentman with the dropshadow filters.

Putting it together

This example would be black text with a white stroke. I'm using conditional html classes by the way to target IE (http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/).

#myelement {
    color: #000000;
    text-shadow:
    -1px -1px 0 #ffffff,  
    1px -1px 0 #ffffff,
    -1px 1px 0 #ffffff,
    1px 1px 0 #ffffff;
}

html.ie7 #myelement,
html.ie8 #myelement,
html.ie9 #myelement {
    background-color: white;
    filter: progid:DXImageTransform.Microsoft.Chroma(color='white') progid:DXImageTransform.Microsoft.Alpha(opacity=100) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=-1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=-1);
    zoom: 1;
}

adding classpath in linux

Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH% is used to represent value of existing path variable in Windows while ${PATH} is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:

export CLASSPATH=${CLASSPATH}:/new/path

but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:

  1. -cp options overrides CLASSPATH environment variable.
  2. Classpath defined in Manifest file overrides both -cp and CLASSPATH envorinment variable.

Reference: How Classpath works in Java.

How can I upload files asynchronously?

I've written this up in a Rails environment. It's only about five lines of JavaScript, if you use the lightweight jQuery-form plugin.

The challenge is in getting AJAX upload working as the standard remote_form_for doesn't understand multi-part form submission. It's not going to send the file data Rails seeks back with the AJAX request.

That's where the jQuery-form plugin comes into play.

Here’s the Rails code for it:

<% remote_form_for(:image_form, 
                   :url => { :controller => "blogs", :action => :create_asset }, 
                   :html => { :method => :post, 
                              :id => 'uploadForm', :multipart => true }) 
                                                                        do |f| %>
 Upload a file: <%= f.file_field :uploaded_data %>
<% end %>

Here’s the associated JavaScript:

$('#uploadForm input').change(function(){
 $(this).parent().ajaxSubmit({
  beforeSubmit: function(a,f,o) {
   o.dataType = 'json';
  },
  complete: function(XMLHttpRequest, textStatus) {
   // XMLHttpRequest.responseText will contain the URL of the uploaded image.
   // Put it in an image element you create, or do with it what you will.
   // For example, if you have an image elemtn with id "my_image", then
   //  $('#my_image').attr('src', XMLHttpRequest.responseText);
   // Will set that image tag to display the uploaded image.
  },
 });
});

And here’s the Rails controller action, pretty vanilla:

 @image = Image.new(params[:image_form])
 @image.save
 render :text => @image.public_filename

I’ve been using this for the past few weeks with Bloggity, and it’s worked like a champ.

Converting BigDecimal to Integer

Well, you could call BigDecimal.intValue():

Converts this BigDecimal to an int. This conversion is analogous to a narrowing primitive conversion from double to short as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this BigDecimal value as well as return a result with the opposite sign.

You can then either explicitly call Integer.valueOf(int) or let auto-boxing do it for you if you're using a sufficiently recent version of Java.

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

Javascript's logical OR operator is short-circuiting and can replace your "Elvis" operator:

var displayName = user.name || "Anonymous";

However, to my knowledge there's no equivalent to your ?. operator.

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    ORDER BY RAND()
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.

Cannot use object of type stdClass as array?

Here is the function signature:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

When param is false, which is default, it will return an appropriate php type. You fetch the value of that type using object.method paradigm.

When param is true, it will return associative arrays.

It will return NULL on error.

If you want to fetch value through array, set assoc to true.

Execute action when back bar button of UINavigationController is pressed

Try this .

self.navigationItem.leftBarButtonItem?.target = "methodname"
func methodname ( ) {            
  //    enter code here
}

Try on this too.

override func viewWillAppear(animated: Bool) {
  //empty your array
}

Converting from hex to string

For Unicode support:

public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}

Rails 3 migrations: Adding reference column?

You can add references to your model through command line in the following manner:

rails g migration add_column_to_tester user_id:integer

This will generate a migration file like :

class AddColumnToTesters < ActiveRecord::Migration
  def change
    add_column :testers, :user_id, :integer
  end
end

This works fine every time i use it..

CSS how to make an element fade in and then fade out?

I found this link to be useful: css-tricks fade-in fade-out css.

Here's a summary of the csstricks post:

CSS classes:

.m-fadeOut {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s linear 300ms, opacity 300ms;
}
.m-fadeIn {
  visibility: visible;
  opacity: 1;
  transition: visibility 0s linear 0s, opacity 300ms;
}

In React:

toggle(){
    if(true condition){
        this.setState({toggleClass: "m-fadeIn"});
    }else{
        this.setState({toggleClass: "m-fadeOut"});
    }
}

render(){
    return (<div className={this.state.toggleClass}>Element to be toggled</div>)
}

Build a simple HTTP server in C

Mongoose (Formerly Simple HTTP Daemon) is pretty good. In particular, it's embeddable and compiles under Windows, Windows CE, and UNIX.

How to prevent line-break in a column of a table cell (not a single cell)?

There are a few ways to do this; none of them are the easy, obvious way.

Applying white-space:nowrap to a <col> won't work; only four CSS properties work on <col> elements - background-color, width, border, and visibility. IE7 and earlier used to support all properties, but that's because they used a strange table model. IE8 now matches everyone else.

So, how do you solve this?

Well, if you can ignore IE (including IE8), you can use the :nth-child() pseudoclass to select particular <td>s from each row. You'd use td:nth-child(2) { white-space:nowrap; }. (This works for this example, but would break if you had any rowspans or colspans involved.)

If you have to support IE, then you've got to go the long way around and apply a class to every <td> that you want to affect. It sucks, but them's the breaks.

In the long run, there are proposals to fix this lack in CSS, so that you can more easily apply styles to all the cells in a column. You'll be able to do something like td:nth-col(2) { white-space:nowrap; } and it would do what you want.

Is there any native DLL export functions viewer?

you can use Dependency Walker to view the function name. you can see the function's parameters only if it's decorated. read the following from the FAQ:

How do I view the parameter and return types of a function? For most functions, this information is simply not present in the module. The Windows' module file format only provides a single text string to identify each function. There is no structured way to list the number of parameters, the parameter types, or the return type. However, some languages do something called function "decoration" or "mangling", which is the process of encoding information into the text string. For example, a function like int Foo(int, int) encoded with simple decoration might be exported as _Foo@8. The 8 refers to the number of bytes used by the parameters. If C++ decoration is used, the function would be exported as ?Foo@@YGHHH@Z, which can be directly decoded back to the function's original prototype: int Foo(int, int). Dependency Walker supports C++ undecoration by using the Undecorate C++ Functions Command.

oracle varchar to number

If you want formated number then use

SELECT TO_CHAR(number, 'fmt')
   FROM DUAL;

SELECT TO_CHAR('123', 999.99)
   FROM DUAL;

Result 123.00

Android Studio 3.0 Execution failed for task: unable to merge dex

When the version of Android Studio is 3.0.1, Gradle Version is 4.1 and Android PluginVersion is 3.0.0, it will encounter this problem. Then I downgrade Gradle Version is 3.3, Android Android is zero, there is no such problem.

Disable/enable an input with jQuery?

    // Disable #x
    $( "#x" ).prop( "disabled", true );
    // Enable #x
    $( "#x" ).prop( "disabled", false );

Sometimes you need to disable/enable the form element like input or textarea. Jquery helps you to easily make this with setting disabled attribute to "disabled". For e.g.:

  //To disable 
  $('.someElement').attr('disabled', 'disabled');

To enable disabled element you need to remove "disabled" attribute from this element or empty it's string. For e.g:

//To enable 
$('.someElement').removeAttr('disabled');

// OR you can set attr to "" 
$('.someElement').attr('disabled', '');

refer :http://garmoncheg.blogspot.fr/2011/07/how-to-disableenable-element-with.html

fetch in git doesn't get all branches

I had this issue today on a repo.

It wasn't the +refs/heads/*:refs/remotes/origin/* issue as per top solution.

Symptom was simply that git fetch origin or git fetch just didn't appear to do anything, although there were remote branches to fetch.

After trying lots of things, I removed the origin remote, and recreated it. That seems to have fixed it. Don't know why.

remove with: git remote rm origin

and recreate with: git remote add origin <git uri>

How to list all installed packages and their versions in Python?

If this is needed to run from within python you can just invoke subprocess

from subprocess import PIPE, Popen

pip_process = Popen(["pip freeze"], stdout=PIPE,
                   stderr=PIPE, shell=True)
stdout, stderr = pip_process.communicate()
print(stdout.decode("utf-8"))

Java - Access is denied java.io.FileNotFoundException

Make sure that the directory exists, you have permission to access it and add the file to the path to write the log:

File file = new File("D:/Data/" + item.getFileName());

Return value from nested function in Javascript

Right. The function you pass to getLocations() won't get called until the data is available, so returning "country" before it's been set isn't going to help you.

The way you need to do this is to have the function that you pass to geocoder.getLocations() actually do whatever it is you wanted done with the returned values.

Something like this:

function reverseGeocode(latitude,longitude){
  var geocoder = new GClientGeocoder();
  var latlng = new GLatLng(latitude, longitude);

  geocoder.getLocations(latlng, function(addresses) {
    var address = addresses.Placemark[0].address;
    var country = addresses.Placemark[0].AddressDetails.Country.CountryName;
    var countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
    var locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
    do_something_with_address(address, country, countrycode, locality);
  });   
}

function do_something_with_address(address, country, countrycode, locality) {
  if (country==="USA") {
     alert("USA A-OK!"); // or whatever
  }
}

If you might want to do something different every time you get the location, then pass the function as an additional parameter to reverseGeocode:

function reverseGeocode(latitude,longitude, callback){
  // Function contents the same as above, then
  callback(address, country, countrycode, locality);
}
reverseGeocode(latitude, longitude, do_something_with_address);

If this looks a little messy, then you could take a look at something like the Deferred feature in Dojo, which makes the chaining between functions a little clearer.

How to comment out a block of Python code in Vim

Frankly I use a tcomment plugin for that link. It can handle almost every syntax. It defines nice movements, using it with some text block matchers specific for python makes it a powerful tool.

Cannot stop or restart a docker container

I couldn't locate boot2docker in my machine. So, I came up with something that worked for me.

$ sudo systemctl restart docker.socket docker.service
$ docker rm -f <container id>

Check if it helps you as well.

How can I get terminal output in python?

You can use Popen in subprocess as they suggest.

with os, which is not recomment, it's like below:

import os
a  = os.popen('pwd').readlines()

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

INSERT INTO ... ON DUPLICATE KEY UPDATE will only work for MYSQL, not for SQL Server.

for SQL server, the way to work around this is to first declare a temp table, insert value to that temp table, and then use MERGE

Like this:

declare @Source table
(
name varchar(30),
age decimal(23,0)
)

insert into @Source VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29);


MERGE beautiful  AS Tg
using  @source as Sc
on tg.namet=sc.name 

when matched then update 
set tg.age=sc.age

when not matched then 
insert (name, age) VALUES
(SC.name, sc.age);

How to create a popup windows in javafx

You can either create a new Stage, add your controls into it or if you require the POPUP as Dialog box, then you may consider using DialogsFX or ControlsFX(Requires JavaFX8)

For creating a new Stage, you can use the following snippet

@Override
public void start(final Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Open Dialog");
    btn.setOnAction(
        new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                final Stage dialog = new Stage();
                dialog.initModality(Modality.APPLICATION_MODAL);
                dialog.initOwner(primaryStage);
                VBox dialogVbox = new VBox(20);
                dialogVbox.getChildren().add(new Text("This is a Dialog"));
                Scene dialogScene = new Scene(dialogVbox, 300, 200);
                dialog.setScene(dialogScene);
                dialog.show();
            }
         });
    }

If you don't want it to be modal (block other windows), use:

dialog.initModality(Modality.NONE);

How do I strip all spaces out of a string in PHP?

If you want to remove all whitespace:

$str = preg_replace('/\s+/', '', $str);

See the 5th example on the preg_replace documentation. (Note I originally copied that here.)

Edit: commenters pointed out, and are correct, that str_replace is better than preg_replace if you really just want to remove the space character. The reason to use preg_replace would be to remove all whitespace (including tabs, etc.).

How to read a file in reverse order?

How about something like this:

import os


def readlines_reverse(filename):
    with open(filename) as qfile:
        qfile.seek(0, os.SEEK_END)
        position = qfile.tell()
        line = ''
        while position >= 0:
            qfile.seek(position)
            next_char = qfile.read(1)
            if next_char == "\n":
                yield line[::-1]
                line = ''
            else:
                line += next_char
            position -= 1
        yield line[::-1]


if __name__ == '__main__':
    for qline in readlines_reverse(raw_input()):
        print qline

Since the file is read character by character in reverse order, it will work even on very large files, as long as individual lines fit into memory.

How to parse a JSON and turn its values into an Array?

You can prefer quick-json parser to meet your requirement...

quick-json parser is very straight forward, flexible, very fast and customizable. Try this out

[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -

  • Compliant with JSON specification (RFC4627)

  • High-Performance JSON parser

  • Supports Flexible/Configurable parsing approach

  • Configurable validation of key/value pairs of any JSON Heirarchy

  • Easy to use # Very Less foot print

  • Raises developer friendly and easy to trace exceptions

  • Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered

  • Validating and Non-Validating parser support

  • Support for two types of configuration (JSON/XML) for using quick-json validating parser

  • Require JDK 1.5 # No dependency on external libraries

  • Support for Json Generation through object serialization

  • Support for collection type selection during parsing process

For e.g.

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);

How is an HTTP POST request made in node.js?

Update 2020:

I've been really enjoying phin - The ultra-lightweight Node.js HTTP client

It can be used in two different ways. One with Promises (Async/Await) and the other with traditional callback styles.

Install via: npm i phin

Straight from it's README with await:

const p = require('phin')

await p({
    url: 'https://ethanent.me',
    method: 'POST',
    data: {
        hey: 'hi'
    }
})


Unpromisifed (callback) style:

const p = require('phin').unpromisified

p('https://ethanent.me', (err, res) => {
    if (!err) console.log(res.body)
})

As of 2015 there are now a wide variety of different libraries that can accomplish this with minimal coding. I much prefer elegant light weight libraries for HTTP requests unless you absolutely need control of the low level HTTP stuff.

One such library is Unirest

To install it, use npm.
$ npm install unirest

And onto the Hello, World! example that everyone is accustomed to.

var unirest = require('unirest');

unirest.post('http://example.com/helloworld')
.header('Accept', 'application/json')
.send({ "Hello": "World!" })
.end(function (response) {
  console.log(response.body);
});


Extra:
A lot of people are also suggesting the use of request [ 2 ]

It should be worth noting that behind the scenes Unirest uses the request library.

Unirest provides methods for accessing the request object directly.

Example:

var Request = unirest.get('http://mockbin.com/request');

How do I concatenate strings and variables in PowerShell?

As noted elsewhere, you can use join.

If you are using commands as inputs (as I was), use the following syntax:

-join($(Command1), "," , $(Command2))

This would result in the two outputs separated by a comma.

See https://stackoverflow.com/a/34720515/11012871 for related comment

Combine multiple JavaScript files into one JS file

Script grouping is counterproductive, you should load them in parallel using something like http://yepnopejs.com/ or http://headjs.com

Is there a function to split a string in PL/SQL?

Please find next an example you may find useful

--1st substring

select substr('alfa#bravo#charlie#delta', 1,  
  instr('alfa#bravo#charlie#delta', '#', 1, 1)-1) from dual;

--2nd substring

select substr('alfa#bravo#charlie#delta', instr('alfa#bravo#charlie#delta', '#', 1, 1)+1,  
  instr('alfa#bravo#charlie#delta', '#', 1, 2) - instr('alfa#bravo#charlie#delta', '#', 1, 1) -1) from dual;

--3rd substring

select substr('alfa#bravo#charlie#delta', instr('alfa#bravo#charlie#delta', '#', 1, 2)+1,  
  instr('alfa#bravo#charlie#delta', '#', 1, 3) - instr('alfa#bravo#charlie#delta', '#', 1, 2) -1) from dual;

--4th substring

select substr('alfa#bravo#charlie#delta', instr('alfa#bravo#charlie#delta', '#', 1, 3)+1) from dual;

Best regards

Emanuele

moving committed (but not pushed) changes to a new branch after pull

  1. Checkout fresh copy of you sources

    git clone ........

  2. Make branch from desired position

    git checkout {position} git checkout -b {branch-name}

  3. Add remote repository

    git remote add shared ../{original sources location}.git

  4. Get remote sources

    git fetch shared

  5. Checkout desired branch

    git checkout {branch-name}

  6. Merge sources

    git merge shared/{original branch from shared repository}

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

How do I delete an exported environment variable?

Walkthrough of creating and deleting an environment variable in bash:

Test if the DUALCASE variable exists:

el@apollo:~$ env | grep DUALCASE
el@apollo:~$ 

It does not, so create the variable and export it:

el@apollo:~$ DUALCASE=1
el@apollo:~$ export DUALCASE

Check if it is there:

el@apollo:~$ env | grep DUALCASE
DUALCASE=1

It is there. So get rid of it:

el@apollo:~$ unset DUALCASE

Check if it's still there:

el@apollo:~$ env | grep DUALCASE
el@apollo:~$ 

The DUALCASE exported environment variable is deleted.

Extra commands to help clear your local and environment variables:

Unset all local variables back to default on login:

el@apollo:~$ CAN="chuck norris"
el@apollo:~$ set | grep CAN
CAN='chuck norris'
el@apollo:~$ env | grep CAN
el@apollo:~$
el@apollo:~$ exec bash
el@apollo:~$ set | grep CAN
el@apollo:~$ env | grep CAN
el@apollo:~$

exec bash command cleared all the local variables but not environment variables.

Unset all environment variables back to default on login:

el@apollo:~$ export DOGE="so wow"
el@apollo:~$ env | grep DOGE
DOGE=so wow
el@apollo:~$ env -i bash
el@apollo:~$ env | grep DOGE
el@apollo:~$

env -i bash command cleared all the environment variables to default on login.

Catching errors in Angular HttpClient

Angular 8 HttpClient Error Handling Service Example

enter image description here

api.service.ts

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
    import { Student } from '../model/student';
    import { Observable, throwError } from 'rxjs';
    import { retry, catchError } from 'rxjs/operators';

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

      // API path
      base_path = 'http://localhost:3000/students';

      constructor(private http: HttpClient) { }

      // Http Options
      httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      }

      // Handle API errors
      handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', error.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(
            `Backend returned code ${error.status}, ` +
            `body was: ${error.error}`);
        }
        // return an observable with a user-facing error message
        return throwError(
          'Something bad happened; please try again later.');
      };


      // Create a new item
      createItem(item): Observable<Student> {
        return this.http
          .post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
          .pipe(
            retry(2),
            catchError(this.handleError)
          )
      }

     ........
     ........

    }

When use getOne and findOne methods Spring Data JPA

I had a similar problem understanding why JpaRespository.getOne(id) does not work and throw an error.

I went and change to JpaRespository.findById(id) which requires you to return an Optional.

This is probably my first comment on StackOverflow.

What is the mouse down selector in CSS?

Pro-tip Note: for some reason, CSS syntax needs the :active snippet after the :hover for the same element in order to be effective

http://www.w3schools.com/cssref/sel_active.asp

C++ Loop through Map

As @Vlad from Moscow says, Take into account that value_type for std::map is defined the following way:

typedef pair<const Key, T> value_type

This then means that if you wish to replace the keyword auto with a more explicit type specifier, then you could this;

for ( const pair<const string, int> &p : table ) {
   std::cout << p.first << '\t' << p.second << std::endl;
} 

Just for understanding what auto will translate to in this case.

Is it possible to use "return" in stored procedure?

It is possible.

When you use Return inside a procedure, the control is transferred to the calling program which calls the procedure. It is like an exit in loops.

It won't return any value.

How to validate an OAuth 2.0 access token for a resource server?

OAuth 2.0 spec doesn't define the part. But there could be couple of options:

  1. When resource server gets the token in the Authz Header then it calls the validate/introspect API on Authz server to validate the token. Here Authz server might validate it either from using DB Store or verifying the signature and certain attributes. As part of response, it decodes the token and sends the actual data of token along with remaining expiry time.

  2. Authz Server can encrpt/sign the token using private key and then publickey/cert can be given to Resource Server. When resource server gets the token, it either decrypts/verifies signature to verify the token. Takes the content out and processes the token. It then can either provide access or reject.

'module' object is not callable - calling method in another file

The problem is in the import line. You are importing a module, not a class. Assuming your file is named other_file.py (unlike java, again, there is no such rule as "one class, one file"):

from other_file import findTheRange

if your file is named findTheRange too, following java's convenions, then you should write

from findTheRange import findTheRange

you can also import it just like you did with random:

import findTheRange
operator = findTheRange.findTheRange()

Some other comments:

a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)

b) You can build the list directly:

  randomList = [random.randint(0, 100) for i in range(5)]

c) You can call methods in the same way you do in java:

largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)

d) You can use built in function, and the huge python library:

largestInList = max(randomList)
smallestInList = min(randomList)

e) If you still want to use a class, and you don't need self, you can use @staticmethod:

class findTheRange():
    @staticmethod
    def findLargest(_list):
        #stuff...

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

In my case I only wanted the image to behave responsively at mobile scale so I created a css style .myimgrsfix that only kicks in at mobile scale

.myimgrsfix {
    @media(max-width:767px){
        width:100%;
    }
}

and applied that to the image <img class='img-responsive myimgrsfix' src='whatever.gif'>

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

Take a look at the new Spatial data-types that were introduced in SQL Server 2008. They are designed for this kind of task and make indexing and querying much easier and more efficient.

More information:

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

PostgreSQL "DESCRIBE TABLE"

In MySQL , DESCRIBE table_name


In PostgreSQL , \d table_name


Or , you can use this long command:

SELECT
        a.attname AS Field,
        t.typname || '(' || a.atttypmod || ')' AS Type,
        CASE WHEN a.attnotnull = 't' THEN 'YES' ELSE 'NO' END AS Null,
        CASE WHEN r.contype = 'p' THEN 'PRI' ELSE '' END AS Key,
        (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid), '\'(.*)\'')
                FROM
                        pg_catalog.pg_attrdef d
                WHERE
                        d.adrelid = a.attrelid
                        AND d.adnum = a.attnum
                        AND a.atthasdef) AS Default,
        '' as Extras
FROM
        pg_class c 
        JOIN pg_attribute a ON a.attrelid = c.oid
        JOIN pg_type t ON a.atttypid = t.oid
        LEFT JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid 
                AND r.conname = a.attname
WHERE
        c.relname = 'tablename'
        AND a.attnum > 0

ORDER BY a.attnum

Interface extends another interface but implements its methods

An interface defines behavior. For example, a Vehicle interface might define the move() method.

A Car is a Vehicle, but has additional behavior. For example, the Car interface might define the startEngine() method. Since a Car is also a Vehicle, the Car interface extends the Vehicle interface, and thus defines two methods: move() (inherited) and startEngine().

The Car interface doesn't have any method implementation. If you create a class (Volkswagen) that implements Car, it will have to provide implementations for all the methods of its interface: move() and startEngine().

An interface may not implement any other interface. It can only extend it.

See line breaks and carriage returns in editor

VI shows newlines (LF character, code x0A) by showing the subsequent text on the next line.

Use the -b switch for binary mode. Eg vi -b filename or vim -b filename --.

It will then show CR characters (x0D), which are not normally used in Unix style files, as the characters ^M.

How to make a Qt Widget grow with the window size?

I found it was impossible to assign a layout to the centralwidget until I had added at least one child beneath it. Then I could highlight the tiny icon with the red 'disabled' mark and then click on a layout in the Designer toolbar at top.

java.text.ParseException: Unparseable date

I found simple solution to get current date without any parsing error.

Calendar calendar;
calendar = Calendar.getInstance();
String customDate = "" + calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH);

Are lists thread-safe?

I recently had this case where I needed to append to a list continuously in one thread, loop through the items and check if the item was ready, it was an AsyncResult in my case and remove it from the list only if it was ready. I could not find any examples that demonstrated my problem clearly Here is an example demonstrating adding to list in one thread continuously and removing from the same list in another thread continuously The flawed version runs easily on smaller numbers but keep the numbers big enough and run a few times and you will see the error

The FLAWED version

import threading
import time

# Change this number as you please, bigger numbers will get the error quickly
count = 1000
l = []

def add():
    for i in range(count):
        l.append(i)
        time.sleep(0.0001)

def remove():
    for i in range(count):
        l.remove(i)
        time.sleep(0.0001)


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()

print(l)

Output when ERROR

Exception in thread Thread-63:
Traceback (most recent call last):
  File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "<ipython-input-30-ecfbac1c776f>", line 13, in remove
    l.remove(i)
ValueError: list.remove(x): x not in list

Version that uses locks

import threading
import time
count = 1000
l = []
lock = threading.RLock()
def add():
    with lock:
        for i in range(count):
            l.append(i)
            time.sleep(0.0001)

def remove():
    with lock:
        for i in range(count):
            l.remove(i)
            time.sleep(0.0001)


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()

print(l)

Output

[] # Empty list

Conclusion

As mentioned in the earlier answers while the act of appending or popping elements from the list itself is thread safe, what is not thread safe is when you append in one thread and pop in another

How to check whether an array is empty using PHP?

is_array($detect) && empty($detect);

is_array

How do I apply CSS3 transition to all properties except background-position?

Here's a solution that also works on Firefox:

transition: all 0.3s ease, background-position 1ms;

I made a small demo: http://jsfiddle.net/aWzwh/

Python str vs unicode types

Unicode and encodings are completely different, unrelated things.

Unicode

Assigns a numeric ID to each character:

  • 0x41 ? A
  • 0xE1 ? á
  • 0x414 ? ?

So, Unicode assigns the number 0x41 to A, 0xE1 to á, and 0x414 to ?.

Even the little arrow ? I used has its Unicode number, it's 0x2192. And even emojis have their Unicode numbers, is 0x1F602.

You can look up the Unicode numbers of all characters in this table. In particular, you can find the first three characters above here, the arrow here, and the emoji here.

These numbers assigned to all characters by Unicode are called code points.

The purpose of all this is to provide a means to unambiguously refer to a each character. For example, if I'm talking about , instead of saying "you know, this laughing emoji with tears", I can just say, Unicode code point 0x1F602. Easier, right?

Note that Unicode code points are usually formatted with a leading U+, then the hexadecimal numeric value padded to at least 4 digits. So, the above examples would be U+0041, U+00E1, U+0414, U+2192, U+1F602.

Unicode code points range from U+0000 to U+10FFFF. That is 1,114,112 numbers. 2048 of these numbers are used for surrogates, thus, there remain 1,112,064. This means, Unicode can assign a unique ID (code point) to 1,112,064 distinct characters. Not all of these code points are assigned to a character yet, and Unicode is extended continuously (for example, when new emojis are introduced).

The important thing to remember is that all Unicode does is to assign a numerical ID, called code point, to each character for easy and unambiguous reference.

Encodings

Map characters to bit patterns.

These bit patterns are used to represent the characters in computer memory or on disk.

There are many different encodings that cover different subsets of characters. In the English-speaking world, the most common encodings are the following:

ASCII

Maps 128 characters (code points U+0000 to U+007F) to bit patterns of length 7.

Example:

  • a ? 1100001 (0x61)

You can see all the mappings in this table.

ISO 8859-1 (aka Latin-1)

Maps 191 characters (code points U+0020 to U+007E and U+00A0 to U+00FF) to bit patterns of length 8.

Example:

  • a ? 01100001 (0x61)
  • á ? 11100001 (0xE1)

You can see all the mappings in this table.

UTF-8

Maps 1,112,064 characters (all existing Unicode code points) to bit patterns of either length 8, 16, 24, or 32 bits (that is, 1, 2, 3, or 4 bytes).

Example:

  • a ? 01100001 (0x61)
  • á ? 11000011 10100001 (0xC3 0xA1)
  • ? ? 11100010 10001001 10100000 (0xE2 0x89 0xA0)
  • ? 11110000 10011111 10011000 10000010 (0xF0 0x9F 0x98 0x82)

The way UTF-8 encodes characters to bit strings is very well described here.

Unicode and Encodings

Looking at the above examples, it becomes clear how Unicode is useful.

For example, if I'm Latin-1 and I want to explain my encoding of á, I don't need to say:

"I encode that a with an aigu (or however you call that rising bar) as 11100001"

But I can just say:

"I encode U+00E1 as 11100001"

And if I'm UTF-8, I can say:

"Me, in turn, I encode U+00E1 as 11000011 10100001"

And it's unambiguously clear to everybody which character we mean.

Now to the often arising confusion

It's true that sometimes the bit pattern of an encoding, if you interpret it as a binary number, is the same as the Unicode code point of this character.

For example:

  • ASCII encodes a as 1100001, which you can interpret as the hexadecimal number 0x61, and the Unicode code point of a is U+0061.
  • Latin-1 encodes á as 11100001, which you can interpret as the hexadecimal number 0xE1, and the Unicode code point of á is U+00E1.

Of course, this has been arranged like this on purpose for convenience. But you should look at it as a pure coincidence. The bit pattern used to represent a character in memory is not tied in any way to the Unicode code point of this character.

Nobody even says that you have to interpret a bit string like 11100001 as a binary number. Just look at it as the sequence of bits that Latin-1 uses to encode the character á.

Back to your question

The encoding used by your Python interpreter is UTF-8.

Here's what's going on in your examples:

Example 1

The following encodes the character á in UTF-8. This results in the bit string 11000011 10100001, which is saved in the variable a.

>>> a = 'á'

When you look at the value of a, its content 11000011 10100001 is formatted as the hex number 0xC3 0xA1 and output as '\xc3\xa1':

>>> a
'\xc3\xa1'

Example 2

The following saves the Unicode code point of á, which is U+00E1, in the variable ua (we don't know which data format Python uses internally to represent the code point U+00E1 in memory, and it's unimportant to us):

>>> ua = u'á'

When you look at the value of ua, Python tells you that it contains the code point U+00E1:

>>> ua
u'\xe1'

Example 3

The following encodes Unicode code point U+00E1 (representing character á) with UTF-8, which results in the bit pattern 11000011 10100001. Again, for output this bit pattern is represented as the hex number 0xC3 0xA1:

>>> ua.encode('utf-8')
'\xc3\xa1'

Example 4

The following encodes Unicode code point U+00E1 (representing character á) with Latin-1, which results in the bit pattern 11100001. For output, this bit pattern is represented as the hex number 0xE1, which by coincidence is the same as the initial code point U+00E1:

>>> ua.encode('latin1')
'\xe1'

There's no relation between the Unicode object ua and the Latin-1 encoding. That the code point of á is U+00E1 and the Latin-1 encoding of á is 0xE1 (if you interpret the bit pattern of the encoding as a binary number) is a pure coincidence.

Getting the document object of an iframe

In my case, it was due to Same Origin policies. To explain it further, MDN states the following:

If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.

Why can't I duplicate a slice with `copy()`?

Another simple way to do this is by using append which will allocate the slice in the process.

arr := []int{1, 2, 3}
tmp := append([]int(nil), arr...)  // Notice the ... splat
fmt.Println(tmp)
fmt.Println(arr)

Output (as expected):

[1 2 3]
[1 2 3]

So a shorthand for copying array arr would be append([]int(nil), arr...)

https://play.golang.org/p/sr_4ofs5GW

Fastest way to check a string contain another substring in JavaScript?

I've found that using a simple for loop, iterating over all elements in the string and comparing using charAt performs faster than indexOf or Regex. The code and proof is available at JSPerf.

ETA: indexOf and charAt both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

For those who need to use the output in subsequent shell commands, rather than groovy, something like this example could be done:

    stage('Show Files') {
        environment {
          MY_FILES = sh(script: 'cd mydir && ls -l', returnStdout: true)
        }
        steps {
          sh '''
            echo "$MY_FILES"
          '''
        }
    }

I found the examples on code maven to be quite useful.

How to apply font anti-alias effects in CSS?

here you go Sir :-)

1

.myElement{
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-rendering: optimizeLegibility;
}

2

.myElement{
    text-shadow: rgba(0,0,0,.01) 0 0 1px;
}

Evenly space multiple views within a container view

I found a perfect and simple method. The auto layout does not allow you to resize the spaces equally, but it does allow you to resize views equally. Simply put some invisible views in between your fields and tell auto layout to keep them the same size. It works perfectly!

Initial XIB

Stretched XIB

One thing of note though; when I reduced the size in the interface designer, sometimes it got confused and left a label where it was, and it had a conflict if the size was changed by an odd amount. Otherwise it worked perfectly.

edit: I found that the conflict became a problem. Because of that, I took one of the spacing constraints, deleted it and replaced it with two constraints, a greater-than-or-equal and a less-than-or-equal. Both were the same size and had a much lower priority than the other constraints. The result was no further conflict.

How can I mimic the bottom sheet from the Maps app?

Try Pulley:

Pulley is an easy to use drawer library meant to imitate the drawer in iOS 10's Maps app. It exposes a simple API that allows you to use any UIViewController subclass as the drawer content or the primary content.

Pulley Preview

https://github.com/52inc/Pulley

How to JSON decode array elements in JavaScript?

Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -

echo json_encode($iniData);

In Javascript, use the following :

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: "ajaxCalls.php",
            data: "dataType=ini",
            success: function(msg)
            {
                var x = eval('(' + msg + ')');
                $('#allowed').html(x.allowed);              // these are the fields which you can now easily access..
                $('#completed').html(x.completed);
                $('#running').html(x.running);
                $('#expired').html(x.expired);
                $('#balance').html(x.balance);
            }
        });
    });
</script>

How to install Ruby 2.1.4 on Ubuntu 14.04

First of all, install the prerequisite libraries:

sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

Then install rbenv, which is used to install Ruby:

cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL

git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL

rbenv install 2.3.1
rbenv global 2.3.1
ruby -v

Then (optional) tell Rubygems to not install local documentation:

echo "gem: --no-ri --no-rdoc" > ~/.gemrc

Credits: https://gorails.com/setup/ubuntu/14.10

Warning!!! There are issues with Gnome-Shell. See comment below.

How to pass multiple parameters in json format to a web service using jquery?

i have same issue and resolved by

 data: "Id1=" + id1 + "&Id2=" + id2

Can't find AVD or SDK manager in Eclipse

I had similar problem after updating SDK from r20 to r21, but all I missed was the SDK/AVD Manager and running into this post while searching for the answer.

I managed to solve it by going to Window -> Customize Perspective, and under Command Groups Availability tab check the Android SDK and AVD Manager (not sure why it became unchecked because it was there before). I'm using Mac by the way, in case the menu option looks different.

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

In my case, i had deleted the original branch from which my current branch derived from. So in the .git/config file i had:

[branch "simil2.1.12"]
    remote = origin
    merge = refs/heads/simil2.0.5
    rebase = false

the simil2.0.5 was deleted. I replaced it with the same branch name:

[branch "simil2.1.12"]
    remote = origin
    merge = refs/heads/simil2.1.12
    rebase = false

and it worked

Show empty string when date field is 1/1/1900

Two nitpicks. (1) Best not to use string literals for column alias - that is deprecated. (2) Just use style 120 to get the same value.

    CASE 
      WHEN CreatedDate = '19000101' THEN '' 
      WHEN CreatedDate = '18000101' THEN '' 
      ELSE Convert(varchar(19), CreatedDate, 120)
    END AS [Created Date]

How to run a makefile in Windows?

Check out cygwin, a Unix alike environment for Windows

What is “2's Complement”?

Two complement is found out by adding one to 1'st complement of the given number. Lets say we have to find out twos complement of 10101 then find its ones complement, that is, 01010 add 1 to this result, that is, 01010+1=01011, which is the final answer.

Update my gradle dependencies in eclipse

I tried all above options but was still getting error, in my case issue was I have not setup gradle installation directory in eclipse, following worked:

eclipse -> Window -> Preferences -> Gradle -> "Select Local Installation Directory"

Click on Browse button and provide path.

Even though question is answered, thought to share in case somebody else is facing similar issue.

Cheers !

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

In my case, the problem was in the xml code somehow.

My web.xml file looked like this:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>index</servlet-name>
        <jsp-file>index.jsp</jsp-file>
    </servlet>

    <servlet-mapping>
        <servlet-name>index</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

but I changed it to look like

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

</web-app>

and now the server loads up properly. Strange.

Converting a Uniform Distribution to a Normal Distribution

Here is a javascript implementation using the polar form of the Box-Muller transformation.

/*
 * Returns member of set with a given mean and standard deviation
 * mean: mean
 * standard deviation: std_dev 
 */
function createMemberInNormalDistribution(mean,std_dev){
    return mean + (gaussRandom()*std_dev);
}

/*
 * Returns random number in normal distribution centering on 0.
 * ~95% of numbers returned should fall between -2 and 2
 * ie within two standard deviations
 */
function gaussRandom() {
    var u = 2*Math.random()-1;
    var v = 2*Math.random()-1;
    var r = u*u + v*v;
    /*if outside interval [0,1] start over*/
    if(r == 0 || r >= 1) return gaussRandom();

    var c = Math.sqrt(-2*Math.log(r)/r);
    return u*c;

    /* todo: optimize this algorithm by caching (v*c) 
     * and returning next time gaussRandom() is called.
     * left out for simplicity */
}

Where can I download an offline installer of Cygwin?

may this post can solve your problem

see Full Installation Answer on that: What is the current full install size of Cygwin?

How to insert a string which contains an "&"

In a program, always use a parameterized query. It avoids SQL Injection attacks as well as any other characters that are special to the SQL parser.

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

List of ANSI color escape sequences

For these who don't get proper results other than mentioned languages, if you're using C# to print a text into console(terminal) window you should replace "\033" with "\x1b". In Visual Basic it would be Chrw(27).

Compare object instances for equality by their attributes

Instance of a class when compared with == comes to non-equal. The best way is to ass the cmp function to your class which will do the stuff.

If you want to do comparison by the content you can simply use cmp(obj1,obj2)

In your case cmp(doc1,doc2) It will return -1 if the content wise they are same.

Configure cron job to run every 15 minutes on Jenkins

It should be,

*/15 * * * *  your_command_or_whatever

String replace method is not replacing characters

You should re-assign the result of the replacement, like this:

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

Be aware that the String class is immutable, meaning that all of its methods return a new string and never modify the original string in-place, so the result of invoking a method in an instance of String must be assigned to a variable or used immediately for the change to take effect.

Split page vertically using CSS

Here is the flex-box approach:

CSS

 .parent {
  display:flex;
  height:100vh;
  }
  .child{
    flex-grow:1;
  }
  .left{
    background:#ddd;
  }
  .center{
    background:#666;
  }

  .right{
    background:#999;
  }

HTML

<div class="parent">
    <div class="child left">Left</div>
    <div class="child center">Center</div>
    <div class="child right">Right</div>
</div>

You can try the same in js fiddle.

Chrome: Uncaught SyntaxError: Unexpected end of input

In my case, i had low internet speed, when i turn off the other user's internet connection then error has gone, strange

How do you create a read-only user in PostgreSQL?

Taken from a link posted in response to despesz' link.

Postgres 9.x appears to have the capability to do what is requested. See the Grant On Database Objects paragraph of:

http://www.postgresql.org/docs/current/interactive/sql-grant.html

Where it says: "There is also an option to grant privileges on all objects of the same type within one or more schemas. This functionality is currently supported only for tables, sequences, and functions (but note that ALL TABLES is considered to include views and foreign tables)."

This page also discusses use of ROLEs and a PRIVILEGE called "ALL PRIVILEGES".

Also present is information about how GRANT functionalities compare to SQL standards.

Plotting a 2D heatmap with Matplotlib

The imshow() function with parameters interpolation='nearest' and cmap='hot' should do what you want.

import matplotlib.pyplot as plt
import numpy as np

a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()

enter image description here

No Android SDK found - Android Studio

I got the same "No Android SDK Found" error message... plus no rendering for Design window, no little cellphone screen.

My SDK path was correct, pointing to where the (downloaded during setup) SDK lives.

During Setup of the SDK Mgr, I didn't download the latest "preview edition (version 20)"...(I thought it better to use the next most recent version (19)) Later I found, there was no dropdown choice in the AVD Manager to pick Version 19, only the default value of the preview, 20.

I thought "Maybe the rendering was based on a version that wasn't present yet." So, I downloaded all the "preview edition's (version 20)" SDK Platform (2) and system images (4)...

Once download/install completed, RESTARTED Android Studio and Viola! success... error message gone, rendering ok.

Add and remove multiple classes in jQuery

You can separate multiple classes with the space:

$("p").addClass("myClass yourClass");

http://api.jquery.com/addClass/

Neither BindingResult nor plain target object for bean name available as request attr

We faced the same issue and changed commandname="" to modelAttribute="" in jsp page to solve this issue.

Understanding typedefs for function pointers in C

Consider the signal() function from the C standard:

extern void (*signal(int, void(*)(int)))(int);

Perfectly obscurely obvious - it's a function that takes two arguments, an integer and a pointer to a function that takes an integer as an argument and returns nothing, and it (signal()) returns a pointer to a function that takes an integer as an argument and returns nothing.

If you write:

typedef void (*SignalHandler)(int signum);

then you can instead declare signal() as:

extern  SignalHandler signal(int signum, SignalHandler handler);

This means the same thing, but is usually regarded as somewhat easier to read. It is clearer that the function takes an int and a SignalHandler and returns a SignalHandler.

It takes a bit of getting used to, though. The one thing you can't do, though is write a signal handler function using the SignalHandler typedef in the function definition.

I'm still of the old-school that prefers to invoke a function pointer as:

(*functionpointer)(arg1, arg2, ...);

Modern syntax uses just:

functionpointer(arg1, arg2, ...);

I can see why that works - I just prefer to know that I need to look for where the variable is initialized rather than for a function called functionpointer.


Sam commented:

I have seen this explanation before. And then, as is the case now, I think what I didn't get was the connection between the two statements:

    extern void (*signal(int, void()(int)))(int);  /*and*/

    typedef void (*SignalHandler)(int signum);
    extern SignalHandler signal(int signum, SignalHandler handler);

Or, what I want to ask is, what is the underlying concept that one can use to come up with the second version you have? What is the fundamental that connects "SignalHandler" and the first typedef? I think what needs to be explained here is what is typedef is actually doing here.

Let's try again. The first of these is lifted straight from the C standard - I retyped it, and checked that I had the parentheses right (not until I corrected it - it is a tough cookie to remember).

First of all, remember that typedef introduces an alias for a type. So, the alias is SignalHandler, and its type is:

a pointer to a function that takes an integer as an argument and returns nothing.

The 'returns nothing' part is spelled void; the argument that is an integer is (I trust) self-explanatory. The following notation is simply (or not) how C spells pointer to function taking arguments as specified and returning the given type:

type (*function)(argtypes);

After creating the signal handler type, I can use it to declare variables and so on. For example:

static void alarm_catcher(int signum)
{
    fprintf(stderr, "%s() called (%d)\n", __func__, signum);
}

static void signal_catcher(int signum)
{
    fprintf(stderr, "%s() called (%d) - exiting\n", __func__, signum);
    exit(1);
}

static struct Handlers
{
    int              signum;
    SignalHandler    handler;
} handler[] =
{
    { SIGALRM,   alarm_catcher  },
    { SIGINT,    signal_catcher },
    { SIGQUIT,   signal_catcher },
};

int main(void)
{
    size_t num_handlers = sizeof(handler) / sizeof(handler[0]);
    size_t i;

    for (i = 0; i < num_handlers; i++)
    {
        SignalHandler old_handler = signal(handler[i].signum, SIG_IGN);
        if (old_handler != SIG_IGN)
            old_handler = signal(handler[i].signum, handler[i].handler);
        assert(old_handler == SIG_IGN);
    }

    ...continue with ordinary processing...

    return(EXIT_SUCCESS);
}

Please note How to avoid using printf() in a signal handler?

So, what have we done here - apart from omit 4 standard headers that would be needed to make the code compile cleanly?

The first two functions are functions that take a single integer and return nothing. One of them actually doesn't return at all thanks to the exit(1); but the other does return after printing a message. Be aware that the C standard does not permit you to do very much inside a signal handler; POSIX is a bit more generous in what is allowed, but officially does not sanction calling fprintf(). I also print out the signal number that was received. In the alarm_handler() function, the value will always be SIGALRM as that is the only signal that it is a handler for, but signal_handler() might get SIGINT or SIGQUIT as the signal number because the same function is used for both.

Then I create an array of structures, where each element identifies a signal number and the handler to be installed for that signal. I've chosen to worry about 3 signals; I'd often worry about SIGHUP, SIGPIPE and SIGTERM too and about whether they are defined (#ifdef conditional compilation), but that just complicates things. I'd also probably use POSIX sigaction() instead of signal(), but that is another issue; let's stick with what we started with.

The main() function iterates over the list of handlers to be installed. For each handler, it first calls signal() to find out whether the process is currently ignoring the signal, and while doing so, installs SIG_IGN as the handler, which ensures that the signal stays ignored. If the signal was not previously being ignored, it then calls signal() again, this time to install the preferred signal handler. (The other value is presumably SIG_DFL, the default signal handler for the signal.) Because the first call to 'signal()' set the handler to SIG_IGN and signal() returns the previous error handler, the value of old after the if statement must be SIG_IGN - hence the assertion. (Well, it could be SIG_ERR if something went dramatically wrong - but then I'd learn about that from the assert firing.)

The program then does its stuff and exits normally.

Note that the name of a function can be regarded as a pointer to a function of the appropriate type. When you do not apply the function-call parentheses - as in the initializers, for example - the function name becomes a function pointer. This is also why it is reasonable to invoke functions via the pointertofunction(arg1, arg2) notation; when you see alarm_handler(1), you can consider that alarm_handler is a pointer to the function and therefore alarm_handler(1) is an invocation of a function via a function pointer.

So, thus far, I've shown that a SignalHandler variable is relatively straight-forward to use, as long as you have some of the right type of value to assign to it - which is what the two signal handler functions provide.

Now we get back to the question - how do the two declarations for signal() relate to each other.

Let's review the second declaration:

 extern SignalHandler signal(int signum, SignalHandler handler);

If we changed the function name and the type like this:

 extern double function(int num1, double num2);

you would have no problem interpreting this as a function that takes an int and a double as arguments and returns a double value (would you? maybe you'd better not 'fess up if that is problematic - but maybe you should be cautious about asking questions as hard as this one if it is a problem).

Now, instead of being a double, the signal() function takes a SignalHandler as its second argument, and it returns one as its result.

The mechanics by which that can also be treated as:

extern void (*signal(int signum, void(*handler)(int signum)))(int signum);

are tricky to explain - so I'll probably screw it up. This time I've given the parameters names - though the names aren't critical.

In general, in C, the declaration mechanism is such that if you write:

type var;

then when you write var it represents a value of the given type. For example:

int     i;            // i is an int
int    *ip;           // *ip is an int, so ip is a pointer to an integer
int     abs(int val); // abs(-1) is an int, so abs is a (pointer to a)
                      // function returning an int and taking an int argument

In the standard, typedef is treated as a storage class in the grammar, rather like static and extern are storage classes.

typedef void (*SignalHandler)(int signum);

means that when you see a variable of type SignalHandler (say alarm_handler) invoked as:

(*alarm_handler)(-1);

the result has type void - there is no result. And (*alarm_handler)(-1); is an invocation of alarm_handler() with argument -1.

So, if we declared:

extern SignalHandler alt_signal(void);

it means that:

(*alt_signal)();

represents a void value. And therefore:

extern void (*alt_signal(void))(int signum);

is equivalent. Now, signal() is more complex because it not only returns a SignalHandler, it also accepts both an int and a SignalHandler as arguments:

extern void (*signal(int signum, SignalHandler handler))(int signum);

extern void (*signal(int signum, void (*handler)(int signum)))(int signum);

If that still confuses you, I'm not sure how to help - it is still at some levels mysterious to me, but I've grown used to how it works and can therefore tell you that if you stick with it for another 25 years or so, it will become second nature to you (and maybe even a bit quicker if you are clever).

Set icon for Android application

It's better to do this through Android Studio rather than the file browser as it updates all icon files with the correct resolution for each.

To do so go to menu File ? New ? Image Asset. This will open a new dialogue and then make sure Launcher Icons is selected (Which it is by default) and then browse to the directory of your icon (it doesn't have to be in the project resources) and then once selected make sure other settings are to your liking and hit done.

Now all resolutions are saved into their respective folders, and you don't have to worry about copying it yourself or using tools, etc.

Enter image description here

Don't forget "Shape - none" for a transparent background.

Please don't edit my answer without asking.

Android set height and width of Custom view programmatically

spin12.setLayoutParams(new LinearLayout.LayoutParams(200, 120));

spin12 is your spinner and 200,120 is width and height for your spinner.

What is the difference between JAX-RS and JAX-WS?

i have been working on Apachi Axis1.1 and Axis2.0 and JAX-WS but i would suggest you must JAX-WS because it allow you make wsdl in any format , i was making operation as GetInquiry() in Apache Axis2 it did not allow me to Start Operation name in Upper Case , so i find it not good , so i would suggest you must use JAX-WS

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

In my case this problem was occuring because i was accessing the file from shared folder by using computerName. OPENROWSET(''Microsoft.Jet.OLEDB.4.0'',''Excel 8.0;Database='\ntpc0100\MysharedFolder\KPI_tempData\VariablePayoutDetails.xls';IMEX=1;'','.....) Insted of using computerName ntpc0100(whatever your machine name) you should specify IPaddress of your machine. for example:- OPENROWSET(''Microsoft.Jet.OLEDB.4.0'',''Excel 8.0; Database='\193.34.23.200\MysharedFolder\KPI_tempData\KPIVariablePayoutDetails.xls'....);

Setting default value in select drop-down using Angularjs

$scope.item = {
    "id": "3",
    "name": "ALL",
};

$scope.CategoryLst = [
    { id: '1', name: 'MD' },
    { id: '2', name: 'CRNA' },
    { id: '3', name: 'ALL' }];

<select ng-model="item.id" ng-selected="3" ng-options="i.id as i.name for i in CategoryLst"></select>

What is the boundary in multipart/form-data?

Is the ??? free to be defined by the user?

Yes.

or is it supplied by the HTML?

No. HTML has nothing to do with that. Read below.

Is it possible for me to define the ??? as abcdefg?

Yes.

If you want to send the following data to the web server:

name = John
age = 12

using application/x-www-form-urlencoded would be like this:

name=John&age=12

As you can see, the server knows that parameters are separated by an ampersand &. If & is required for a parameter value then it must be encoded.

So how does the server know where a parameter value starts and ends when it receives an HTTP request using multipart/form-data?

Using the boundary, similar to &.

For example:

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

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

In that case, the boundary value is XXX. You specify it in the Content-Type header so that the server knows how to split the data it receives.

So you need to:

  • Use a value that won't appear in the HTTP data sent to the server.

  • Be consistent and use the same value everywhere in the request message.

Is it possible to remove inline styles with jQuery?

In case the display is the only parameter from your style, you can run this command in order to remove all style:

$('#element').attr('style','');

Means that if your element looked like this before:

<input id="element" style="display: block;">

Now your element will look like this:

<input id="element" style="">

Find an object in array?

SWIFT 5

Check if the element exists

if array.contains(where: {$0.name == "foo"}) {
   // it exists, do something
} else {
   //item could not be found
}

Get the element

if let foo = array.first(where: {$0.name == "foo"}) {
   // do something with foo
} else {
   // item could not be found
}

Get the element and its offset

if let foo = array.enumerated().first(where: {$0.element.name == "foo"}) {
   // do something with foo.offset and foo.element
} else {
   // item could not be found
}

Get the offset

if let fooOffset = array.firstIndex(where: {$0.name == "foo"}) {
    // do something with fooOffset
} else {
    // item could not be found
}

bash shell nested for loop

The question does not contain a nested loop, just a single loop. But THIS nested version works, too:

# for i in c d; do for j in a b; do echo $i $j; done; done
c a
c b
d a
d b

How to disable Google asking permission to regularly check installed apps on my phone?

In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".

Python: access class property from string

A picture's worth a thousand words:

>>> class c:
        pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'

How can I change the version of npm using nvm?

I had same issue after installing nvm-windows on top of existing Node installation. Solution was just to follow the instructions:

You should also delete the existing npm install location (e.g. "C:\Users\AppData\Roaming\npm") so that the nvm install location will be correctly used instead.

Installation & Upgrades

Extracting hours from a DateTime (SQL Server 2005)

DATEPART(HOUR, [date]) returns the hour in military time ( 00 to 23 ) If you want 1AM, 3PM etc, you need to case it out:

SELECT Run_Time_Hour =
CASE DATEPART(HOUR, R.date_schedule)
    WHEN 0 THEN  '12AM'
    WHEN 1 THEN   '1AM'
    WHEN 2 THEN   '2AM'
    WHEN 3 THEN   '3AM'
    WHEN 4 THEN   '4AM'
    WHEN 5 THEN   '5AM'
    WHEN 6 THEN   '6AM'
    WHEN 7 THEN   '7AM'
    WHEN 8 THEN   '8AM'
    WHEN 9 THEN   '9AM'
    WHEN 10 THEN '10AM'
    WHEN 11 THEN '11AM'
    WHEN 12 THEN '12PM'
    ELSE CONVERT(varchar, DATEPART(HOUR, R.date_schedule)-12) + 'PM'
END
FROM
    dbo.ARCHIVE_RUN_SCHEDULE R

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

You can do this by displaying a div (if you want to do it in a modal manner you could use blockUI - or one of the many other modal dialog plugins out there) prior to the request then just waiting until the call back succeeds as a quick example you can you $.getJSON as follows (you might want to use .ajax if you want to add proper error handling)

$("#ajaxLoader").show(); //Or whatever you want to do
$.getJSON("/AJson/Call/ThatTakes/Ages", function(result) {
    //Process your response
    $("#ajaxLoader").hide();
});

If you do this several times in your app and want to centralise the behaviour for all ajax calls you can make use of the global AJAX events:-

$("#ajaxLoader").ajaxStart(function() { $(this).show(); })
               .ajaxStop(function() { $(this).hide(); });

Using blockUI is similar for example with mark up like:-

<a href="/Path/ToYourJson/Action" id="jsonLink">Get JSON</a>
<div id="resultContainer" style="display:none">
And the answer is:-
    <p id="result"></p>
</div>

<div id="ajaxLoader" style="display:none">
    <h2>Please wait</h2>
    <p>I'm getting my AJAX on!</p>
</div>

And using jQuery:-

$(function() {
    $("#jsonLink").click(function(e) {
        $.post(this.href, function(result) {
            $("#resultContainer").fadeIn();
            $("#result").text(result.Answer);
        }, "json");
        return false;
    });
    $("#ajaxLoader").ajaxStart(function() {
                          $.blockUI({ message: $("#ajaxLoader") });
                     })
                    .ajaxStop(function() { 
                          $.unblockUI();
                     });
});

How to activate an Anaconda environment

I've tried to activate env from Jenkins job (in bash) with conda activate base and it failed, so after many tries, this one worked for me (CentOS 7) :

source /opt/anaconda2/bin/activate base

Cannot overwrite model once compiled Mongoose

You are using mongoose.model with the same variable name "user" in check.js and insert.js.

Command CompileSwift failed with a nonzero exit code in Xcode 10

Just adding to this question. My issue didn't have anything to do with CommonCrypto. It created a new Single App application and tested to run. Compiler was complaining about using Swift 4.2

Changing the Swift language to version 4.0 in Build settings fixed the issue. Not sure if this is a bug.

Is there any way to wait for AJAX response and halt execution?

Try this code. it worked for me.

 function getInvoiceID(url, invoiceId) {
    return $.ajax({
        type: 'POST',
        url: url,
        data: { invoiceId: invoiceId },
        async: false,
    });
}
function isInvoiceIdExists(url, invoiceId) {
    $.when(getInvoiceID(url, invoiceId)).done(function (data) {
        if (!data) {

        }
    });
}

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

How to format a duration in java? (e.g format H:MM:SS)

This is a working option.

public static String showDuration(LocalTime otherTime){          
    DateTimeFormatter df = DateTimeFormatter.ISO_LOCAL_TIME;
    LocalTime now = LocalTime.now();
    System.out.println("now: " + now);
    System.out.println("otherTime: " + otherTime);
    System.out.println("otherTime: " + otherTime.format(df));

    Duration span = Duration.between(otherTime, now);
    LocalTime fTime = LocalTime.ofNanoOfDay(span.toNanos());
    String output = fTime.format(df);

    System.out.println(output);
    return output;
}

Call the method with

System.out.println(showDuration(LocalTime.of(9, 30, 0, 0)));

Produces something like:

otherTime: 09:30
otherTime: 09:30:00
11:31:27.463
11:31:27.463

Neatest way to remove linebreaks in Perl

After digging a bit through the perlre docs a bit, I'll present my best suggestion so far that seems to work pretty good. Perl 5.10 added the \R character class as a generalized linebreak:

$line =~ s/\R//g;

It's the same as:

(?>\x0D\x0A?|[\x0A-\x0C\x85\x{2028}\x{2029}])

I'll keep this question open a while yet, just to see if there's more nifty ways waiting to be suggested.

link_to method and click event in Rails

another solution is catching onClick event and for aggregate data to js function you can

.hmtl.erb

<%= link_to "Action", 'javascript:;', class: 'my-class', data: { 'array' => %w(foo bar) } %>

.js

// handle my-class click
$('a.my-class').on('click', function () {
  var link = $(this);
  var array = link.data('array');
});

Modifying Objects within stream in Java8 while iterating

You can make use of the removeIf to remove data from a list conditionally.

Eg:- If you want to remove all even numbers from a list, you can do it as follows.

    final List<Integer> list = IntStream.range(1,100).boxed().collect(Collectors.toList());

    list.removeIf(number -> number % 2 == 0);

Facebook share button and custom text

This is a simple dialog feed that Facebook offer's. Read here for more detail link

How to Run Terminal as Administrator on Mac Pro

You can run a command as admin using

sudo <command>

You can also switch to root and every command will be run as root

sudo su

When should we implement Serializable interface?

  1. From What's this "serialization" thing all about?:

    It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).

    Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."

    So, implement the Serializable interface when you need to store a copy of the object, send them to another process which runs on the same system or over the network.

  2. Because you want to store or send an object.

  3. It makes storing and sending objects easy. It has nothing to do with security.

Error: package or namespace load failed for ggplot2 and for data.table

After a wild goose chase with tons of Google searches and burteforce attempts, I think I found how to solve this problem.

Steps undertaken to solve the problem:

  1. Uninstall R
  2. Reinstall R
  3. Install ggplot with the dependencies argument to install.packages set to TRUE

    install.packages("ggplot2",dependencies = TRUE)

  4. The above step still does NOT include the Rcpp dependency so that has to be manually installed using the following command

    install.packages("Rcpp")

However, while the above command successfully downloads Rcpp, for some reason, it fails to explode the ZIP file and install it in my R's library folder citing the following error:

package ‘Rcpp’ successfully unpacked and MD5 sums checked Warning in install.packages : unable to move temporary installation ‘C:\Root_Prgs\Data_Science_SW\R\R-3.2.3\library\file27b8ef47b6d\Rcpp’ to ‘C:\Root_Prgs\Data_Science_SW\R\R-3.2.3\library\Rcpp’

The downloaded binary packages are in C:\Users\MY_USER_ID\AppData\Local\Temp\Rtmp25XQ0S\downloaded_packages

  1. Note that the above output says "Warning" but actually, it is an indication of failure to install the Rcpp package successfully within the repository. I then used the Tools-->Install packages--> From ZIP file and pointed to the location of the "downloaded binary packages" in the message above -

C:\Users\MY_USER_ID\AppData\Local\Temp\Rtmp25XQ0S\downloaded_packages\Rcpp_0.12.3.zip

  1. This led to successful installation of Rcpp in my R\R-3.2.3\library folder, thereby ensuring that Rcpp is now available when I attempt to load the library for ggplot2. I could not do this step in the past because my previous installation of R would throw error stating that Rcpp cannot be imported. However, the same command worked after I uninstalled and reinstalled R, which is ODD.

    install.packages("C:/Users/MY_USER_ID/AppData/Local/Temp/Rtmp25XQ0S/downloaded_packages/Rcpp_0.12.3.zip", repos = NULL, type = "win.binary") package ‘Rcpp’ successfully unpacked and MD5 sums checked`

  2. I was finally able to load the ggplot2 library successfully.

    library(ggplot2)

How to get relative path of a file in visual studio?

I'm a little late, and I'm not sure if this is what you're looking for, but I thought I'd add it just in case someone else finds it useful.

Suppose this is your file structure:

/BulutDepoProject
    /bin
        Main.exe
    /FolderIcon
        Folder.ico
        Main.cs

You need to write your path relative to the Main.exe file. So, you want to access Folder.ico, in your Main.cs you can use:

String path = "..\\FolderIcon\\Folder.ico"

That seemed to work for me!

Create table variable in MySQL

Perhaps a temporary table will do what you want.

CREATE TEMPORARY TABLE SalesSummary (
product_name VARCHAR(50) NOT NULL
, total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
, avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
, total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
) ENGINE=MEMORY;

INSERT INTO SalesSummary
(product_name, total_sales, avg_unit_price, total_units_sold)
SELECT 
  p.name
  , SUM(oi.sales_amount)
  , AVG(oi.unit_price)
  , SUM(oi.quantity_sold)
FROM OrderItems oi
INNER JOIN Products p
    ON oi.product_id = p.product_id
GROUP BY p.name;

/* Just output the table */
SELECT * FROM SalesSummary;

/* OK, get the highest selling product from the table */
SELECT product_name AS "Top Seller"
FROM SalesSummary
ORDER BY total_sales DESC
LIMIT 1;

/* Explicitly destroy the table */
DROP TABLE SalesSummary; 

From forge.mysql.com. See also the temporary tables piece of this article.

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

Regular Expression to get a string between parentheses in Javascript

Alternative:

var str = "I expect five hundred dollars ($500) ($1).";
str.match(/\(.*?\)/g).map(x => x.replace(/[()]/g, ""));
? (2) ["$500", "$1"]

It is possible to replace brackets with square or curly brackets if you need

compression and decompression of string data in java

Another example of correct compression and decompression:

@Slf4j
public class GZIPCompression {
    public static byte[] compress(final String stringToCompress) {
        if (isNull(stringToCompress) || stringToCompress.length() == 0) {
            return null;
        }

        try (final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOutput = new GZIPOutputStream(baos)) {
            gzipOutput.write(stringToCompress.getBytes(UTF_8));
            gzipOutput.finish();
            return baos.toByteArray();
        } catch (IOException e) {
            throw new UncheckedIOException("Error while compression!", e);
        }
    }

    public static String decompress(final byte[] compressed) {
        if (isNull(compressed) || compressed.length == 0) {
            return null;
        }

        try (final GZIPInputStream gzipInput = new GZIPInputStream(new ByteArrayInputStream(compressed));
             final StringWriter stringWriter = new StringWriter()) {
            IOUtils.copy(gzipInput, stringWriter, UTF_8);
            return stringWriter.toString();
        } catch (IOException e) {
            throw new UncheckedIOException("Error while decompression!", e);
        }
    }
}

INNER JOIN in UPDATE sql for DB2

for you ask

update file1 f1
set file1.firstfield=
(
select 'BIT OF TEXT' || f2.something
from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
where exists
(
select * from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
and f1.firstfield like 'BLAH%'

if join give multiple result you can force update like this

update file1 f1
set file1.firstfield=
(
select 'BIT OF TEXT' || f2.something
from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
fetch first rows only
)
where exists
(
select * from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
and f1.firstfield like 'BLAH%' 

template methode

update table1 f1
set (f1.field1, f1.field2, f1.field3, f1.field4)=
(
select f2.field1, f2.field2, f2.field3, 'CONSTVALUE'
from table2 f2
where (f1.key1, f1.key2)=(f2.key1, f2.key2) 
)
where exists 
(
select * from table2 f2
where (f1.key1, f1.key2)=(f2.key1, f2.key2)
) 

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

invalid use of incomplete type

Not exactly what you were asking, but you can make action a template member function:

template<typename Subclass>
class A {
    public:
        //Why doesn't it like this?
        template<class V> void action(V var) {
                (static_cast<Subclass*>(this))->do_action();
        }
};

class B : public A<B> {
    public:
        typedef int mytype;

        B() {}

        void do_action(mytype var) {
                // Do stuff
        }
};

int main(int argc, char** argv) {
    B myInstance;
    return 0;
}

how to change color of TextinputLayout's label and edittext underline android

This Blog Post describes various styling aspects of EditText and AutoCompleteTextView wrapped by TextInputLayout.

For EditText and AppCompat lib 22.1.0+ you can set theme attribute with some theme related settings:

<style name="StyledTilEditTextTheme">
   <item name="android:imeOptions">actionNext</item>
   <item name="android:singleLine">true</item>
   <item name="colorControlNormal">@color/greyLight</item>
   <item name="colorControlActivated">@color/blue</item>
   <item name="android:textColorPrimary">@color/blue</item>
   <item name="android:textSize">@dimen/styledtil_edit_text_size</item>
</style>

<style name="StyledTilEditText">
    <item name="android:theme">@style/StyledTilEditTextTheme</item>
    <item name="android:paddingTop">4dp</item>
</style>

and apply them on EditText:

<EditText
    android:id="@+id/etEditText"
    style="@style/StyledTilEditText"

For AutoCompleteTextView things are more complicated because wrapping it in TextInputLayout and applying this theme breaks floating label behaviour. You need to fix this in code:

private void setStyleForTextForAutoComplete(int color) {
    Drawable wrappedDrawable =     DrawableCompat.wrap(autoCompleteTextView.getBackground());
    DrawableCompat.setTint(wrappedDrawable, color);
    autoCompleteTextView.setBackgroundDrawable(wrappedDrawable);
}

and in Activity.onCreate:

setStyleForTextForAutoComplete(getResources().getColor(R.color.greyLight));
autoCompleteTextView.setOnFocusChangeListener((v, hasFocus) -> {
    if(hasFocus) {
        setStyleForTextForAutoComplete(getResources().getColor(R.color.blue));
    } else {
        if(autoCompleteTextView.getText().length() == 0) {  
              setStyleForTextForAutoComplete(getResources().getColor(R.color.greyLight));
        }
    }
});

Printing out all the objects in array list

You have to define public String toString() method in your Student class. For example:

public String toString() {
  return "Student: " + studentName + ", " + studentNo;
}

html select scroll bar

One options will be to show the selected option above (or below) the select list like following:

HTML

<div id="selText"><span>&nbsp;</span></div><br/>
<select size="4" id="mySelect" style="width:65px;color:#f98ad3;">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"   
  type="text/javascript"></script> 
<script type="text/javascript">
$(document).ready(function(){        
    $("select#mySelect").change(function(){
      //$("#selText").html($($(this).children("option:selected")[0]).text());
       var txt = $($(this).children("option:selected")[0]).text();
       $("<span>" + txt + "<br/></span>").appendTo($("#selText span:last"));
    });
});
</script>

PS:- Set height of div#selText otherwise it will keep shifting select list downward.

How can I convert ticks to a date format?

Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.

public class Time
{
    public static void Timestamps()
    {
        OutputTimestamp();
        Thread.Sleep(1000);
        OutputTimestamp();
    }

    private static void OutputTimestamp()
    {
        var timestamp = DateTime.UtcNow.Ticks;
        var localTicks = DateTime.Now.Ticks;
        var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
        Console.Out.WriteLine("Timestamp = {0}.  Local ticks = {1}.  Local time = {2}.", timestamp, localTicks, localTime);
    }
}

Output:

Timestamp = 636988286338754530.  Local ticks = 636988034338754530.  Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736.  Local ticks = 636988034348878736.  Local time = 2019-07-15 4:03:54 PM.

Form Google Maps URL that searches for a specific places near specific coordinates

What do you want to search near that known place?

For example if you want to search a restaurant near a known place you can use the parameters "q=" and "near=" and construct this URL: maps.google.com/?q=restaurant&near=47.154719,27.60551

For a list of complete parameters you can see this: https://web.archive.org/web/20070708030513/http://mapki.com/wiki/Google_Map_Parameters

Depending on what is the format you want your information in you can add at the end of the url the parameter output like this: maps.google.com/?q=restaurant&near=47.154719,27.60551&output=kml

For more types of output format you can read chapter 2 of this: http://csie-tw.blogspot.de/2009/06/android-driving-direction-route-path.html

Difference between a class and a module

Module in Ruby, to a degree, corresponds to Java abstract class -- has instance methods, classes can inherit from it (via include, Ruby guys call it a "mixin"), but has no instances. There are other minor differences, but this much information is enough to get you started.

How to install Android SDK Build Tools on the command line?

The "android" command is deprecated.

For command-line tools, use tools/bin/sdkmanager and tools/bin/avdmanager

If you do not need Android Studio, you can download the basic Android command line tools from developer.android.com in section Command line tools only.

from CLI it should be somfing like:

curl --output sdk-tools-linux.zip https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip

or

wget --output-document sdk-tools-linux.zip https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip

After that just unpack the archive to the target folder

unzip sdk-tools-linux.zip

And now we can install everything you need...

./tools/bin/sdkmanager --install 'build-tools;29.0.2' 'platform-tools' 'platforms;android-29' 'tools'

You can get a complete list of packages using the command ./tools/bin/sdkmanager --list

Some packages require acceptance of the license agreement. you can accept it interactively or just pass "y" to the input stream, like this(two agreements in case):

echo -ne "y\ny" | ./tools/bin/sdkmanager --install 'system-images;android-29;default;x86_64'

And of course, for your convenience, you can export variables such as ANDROID_HOME or ANDROID_SDK_ROOT (including doing it in ~/.profile or ~/.bash_profile) or patch the PATH variable - all this is at your discretion.

Script example:

mkdir /opt/android-sdk
cd /opt/android-sdk
curl --output sdk-tools-linux.zip https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip
unzip sdk-tools-linux.zip
echo -ne "y" | ./tools/bin/sdkmanager --install 'build-tools;29.0.2' 'platform-tools' 'platforms;android-29' 'tools'

Requirements: curl(or wget) and unzip

Troubleshooting:

if you see Warning: Could not create settings, you need to have the tools directory inside the cmdline-tools directory inside the ANDROID_HOME (create it if needed with this exact name) see Android Command line tools sdkmanager always shows: Warning: Could not create settings

Getting a list of associative array keys

Simple jQuery way:

This is what I use:

DictionaryObj being the JavaScript dictionary object you want to go through. And value, key of course being the names of them in the dictionary.

$.each(DictionaryObj, function (key, value) {
    $("#storeDuplicationList")
        .append($("<li></li>")
        .attr("value", key)
        .text(value));
});

jQuery on window resize

Move your javascript into a function and then bind that function to window resize.

$(document).ready(function () {
    updateContainer();
    $(window).resize(function() {
        updateContainer();
    });
});
function updateContainer() {
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    if ($containerHeight > 819) {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    }
}

Regex allow digits and a single dot

My try is combined solution.

string = string.replace(',', '.').replace(/[^\d\.]/g, "").replace(/\./, "x").replace(/\./g, "").replace(/x/, ".");
string = Math.round( parseFloat(string) * 100) / 100;

First line solution from here: regex replacing multiple periods in floating number . It replaces comma "," with dot "." ; Replaces first comma with x; Removes all dots and replaces x back to dot.

Second line cleans numbers after dot.

How to check if an array value exists?

Using: in_array()

$search_array = array('user_from','lucky_draw_id','prize_id');

if (in_array('prize_id', $search_array)) {
    echo "The 'prize_id' element is in the array";
}

Here is output: The 'prize_id' element is in the array


Using: array_key_exists()

$search_array = array('user_from','lucky_draw_id','prize_id');

if (array_key_exists('prize_id', $search_array)) {
    echo "The 'prize_id' element is in the array";
}

No output


In conclusion, array_key_exists() does not work with a simple array. Its only to find whether an array key exist or not. Use in_array() instead.

Here is more example:

<?php
/**++++++++++++++++++++++++++++++++++++++++++++++
 * 1. example with assoc array using in_array
 *
 * IMPORTANT NOTE: in_array is case-sensitive
 * in_array — Checks if a value exists in an array
 *
 * DOES NOT WORK FOR MULTI-DIMENSIONAL ARRAY
 *++++++++++++++++++++++++++++++++++++++++++++++
 */
$something = array('a' => 'bla', 'b' => 'omg');
if (in_array('omg', $something)) {
    echo "|1| The 'omg' value found in the assoc array ||";
}

/**++++++++++++++++++++++++++++++++++++++++++++++
 * 2. example with index array using in_array
 *
 * IMPORTANT NOTE: in_array is case-sensitive
 * in_array — Checks if a value exists in an array
 *
 * DOES NOT WORK FOR MULTI-DIMENSIONAL ARRAY
 *++++++++++++++++++++++++++++++++++++++++++++++
 */
$something = array('bla', 'omg');
if (in_array('omg', $something)) {
    echo "|2| The 'omg' value found in the index array ||";
}

/**++++++++++++++++++++++++++++++++++++++++++++++
 * 3. trying with array_search
 *
 * array_search — Searches the array for a given value 
 * and returns the corresponding key if successful
 *
 * DOES NOT WORK FOR MULTI-DIMENSIONAL ARRAY
 *++++++++++++++++++++++++++++++++++++++++++++++
 */
$something = array('a' => 'bla', 'b' => 'omg');
if (array_search('bla', $something)) {
    echo "|3| The 'bla' value found in the assoc array ||";
}

/**++++++++++++++++++++++++++++++++++++++++++++++
 * 4. trying with isset (fastest ever)
 *
 * isset — Determine if a variable is set and 
 * is not NULL
 *++++++++++++++++++++++++++++++++++++++++++++++
 */
$something = array('a' => 'bla', 'b' => 'omg');
if($something['a']=='bla'){
    echo "|4| Yeah!! 'bla' found in array ||";
}

/**
 * OUTPUT:
 * |1| The 'omg' element value found in the assoc array ||
 * |2| The 'omg' element value found in the index array ||
 * |3| The 'bla' element value found in the assoc array ||
 * |4| Yeah!! 'bla' found in array ||
 */
?>

Here is PHP DEMO

Python concatenate text files

That's exactly what fileinput is for:

import fileinput
with open(outfilename, 'w') as fout, fileinput.input(filenames) as fin:
    for line in fin:
        fout.write(line)

For this use case, it's really not much simpler than just iterating over the files manually, but in other cases, having a single iterator that iterates over all of the files as if they were a single file is very handy. (Also, the fact that fileinput closes each file as soon as it's done means there's no need to with or close each one, but that's just a one-line savings, not that big of a deal.)

There are some other nifty features in fileinput, like the ability to do in-place modifications of files just by filtering each line.


As noted in the comments, and discussed in another post, fileinput for Python 2.7 will not work as indicated. Here slight modification to make the code Python 2.7 compliant

with open('outfilename', 'w') as fout:
    fin = fileinput.input(filenames)
    for line in fin:
        fout.write(line)
    fin.close()

Check if a string within a list contains a specific string with Linq

I think you want Any:

if (myList.Any(str => str.Contains("Mdd LH")))

It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

PHP - Get array value with a numeric index

Yes, for scalar values, a combination of implode and array_slice will do:

$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));

Or mix it up with array_values and list (thanks @nikic) so that it works with all types of values:

list($bar) = array_values(array_slice($array, 0, 1));

Convert timestamp to readable date/time PHP

echo date("l M j, Y",$res1['timep']);
This is really good for converting a unix timestamp to a readable date along with day. Example: Thursday Jul 7, 2016

The declared package does not match the expected package ""

You need to have the class inside a folder Devices.

gradle build fails on lint task

As for me, it's a bad and quick solution for your problem :

android { 
  lintOptions { 
    abortOnError false 
  }
}

Better solution is solving problem in your code, because lint tool checks your Android project source files for potential bugs and optimization improvements for correctness, security, performance, usability, accessibility, and internationalization.

This problem most frequently occurring when:

  • Layout include unresolved symbols or missing some attribute
  • Other structural issues, such as use of deprecated elements or API calls that are not supported by the target API versions, might lead to code failing to run correctly.

Find your bugs by Inspect Code in Android Studio: Improve Your Code with Lint

TypeError: tuple indices must be integers, not str

Like the error says, row is a tuple, so you can't do row["pool_number"]. You need to use the index: row[0].

How to measure time taken by a function to execute

Stopwatch with cumulative cycles

Works with server and client (Node or DOM), uses the Performance API. Good when you have many small cycles e.g. in a function called 1000 times that processes 1000 data objects but you want to see how each operation in this function adds up to the total.

So this one uses a module global (singleton) timer. Same as a class singleton pattern, just a bit simpler to use, but you need to put this in a separate e.g. stopwatch.js file.

const perf = typeof performance !== "undefined" ? performance : require('perf_hooks').performance;
const DIGITS = 2;

let _timers = {};

const _log = (label, delta?) => {
    if (_timers[label]) {
        console.log(`${label}: ` + (delta ? `${delta.toFixed(DIGITS)} ms last, ` : '') +
            `${_timers[label].total.toFixed(DIGITS)} ms total, ${_timers[label].cycles} cycles`);
    }
};

export const Stopwatch = {
    start(label) {
        const now = perf.now();
        if (_timers[label]) {
            if (!_timers[label].started) {
                _timers[label].started = now;
            }
        } else {
            _timers[label] = {
                started: now,
                total: 0,
                cycles: 0
            };
        }
    },
    /** Returns total elapsed milliseconds, or null if stopwatch doesn't exist. */
    stop(label, log = false) {
        const now = perf.now();
        if (_timers[label]) {
            let delta;
            if(_timers[label].started) {
                delta = now - _timers[label].started;
                _timers[label].started = null;
                _timers[label].total += delta;
                _timers[label].cycles++;
            }
            log && _log(label, delta);
            return _timers[label].total;
        } else {
            return null;
        }
    },
    /** Logs total time */
    log: _log,
    delete(label) {
        delete _timers[label];
    }
};

Python, print all floats to 2 decimal places in output

Format String Syntax.

https://docs.python.org/3/library/string.html#formatstrings

from math import pi
var1, var2, var3, var4 = pi, pi*2, pi*3, pi*4
'{:0.2f}, kg={:0.2f}, lb={:0.2f}, gal={:0.2f}'.format(var1, var2, var3, var4)

The output would be:

'3.14, kg=6.28, lb=9.42, gal=12.57'

Calling a user defined function in jQuery

jQuery.fn.make_me_red = function() {
    return this.each(function() {
        this.style.color = 'red';
    });
};

$('a').make_me_red() // - instead of this you can use $(this).make_me_red() instead for better readability.

Disable Enable Trigger SQL server for a table

I wanted to share something that helped me out. Idea credit goes to @Siavash and @Shahab Naseer.

I needed something where I could script disable and re enable of triggers for a particular table. I normally try and stay away from tiggers, but sometimes they could be good to use.

I took the script above and added a join to the sysobjects so I could filter by table name. This script will disable a trigger or triggers for a table.

select 'alter table '+ (select Schema_name(schema_id) from sys.objects o 
where o.object_id = parent_id) + '.'+object_name(parent_id) + ' ENABLE TRIGGER '+ t.Name as EnableScript,*
from sys.triggers t 
INNER JOIN dbo.sysobjects DS ON DS.id = t.parent_id 
where is_disabled = 0 AND DS.name = 'tblSubContact'

How to add shortcut keys for java code in eclipse

Type syso and ctrl + space for System.out.println()

Is there a keyboard shortcut (hotkey) to open Terminal in macOS?

I tested the following procedure under macOS Mojave 10.14.6 (18G3020).

Launch Automator. Create a document of type “Quick Action”:

quick action template

(In older versions of macOS, use the “Service” template.)

In the new Automator document, add a “Run AppleScript” action. (You can type “run applescript” into the search field at the top of the action list to find it.) Here's the AppleScript to paste into the action:

on run {input, parameters}
    tell application "Terminal"
        if it is running then
            do script ""
        end if
        activate
    end tell
end run

Set the “Workflow receives” popup to “no input”. It should look like this overall:

workflow with applescript

Save the document with the name “New Terminal”. Then go to the Automator menu (or the app menu in any running application) and open the Services submenu. You should now see the “New Terminal” quick action:

New Terminal service menu item

If you click the “New Terminal” menu item, you'll get a dialog box:

permission dialog

Click OK to allow the action to run. You'll see this dialog once in each application that's frontmost when you use the action. In other words, the first time you use the action while Finder is frontmost, you'll see the dialog. And the first time you use the action while Safari is frontmost, you'll see the dialog. And so on.

After you click OK in the dialog, Terminal should open a new window.

To assign a keyboard shortcut to the quick action, choose the “Services Preferences…” item from the Services menu. (Or launch System Preferences, choose the Keyboard pane, then choose the Shortcuts tab, then choose Services from the left-hand list.) Scroll to the bottom of the right-hand list and find the New Terminal service. Click it and you should see an “Add Shortcut” button:

add shortcut button

Click the button and press your preferred keyboard shortcut. Then, scratch your head, because (when I tried it) the Add Shortcut button reappears. But click the button again and you should see your shortcut:

keyboard shortcut set

Now you should be able to press your keyboard shortcut in most circumstances to get a new terminal window.

What regular expression will match valid international phone numbers?

Modified @Eric's regular expression - added a list of all country codes (got them from xxxdepy @ Github. I hope you will find it helpful:

/(\+|00)(297|93|244|1264|358|355|376|971|54|374|1684|1268|61|43|994|257|32|229|226|880|359|973|1242|387|590|375|501|1441|591|55|1246|673|975|267|236|1|61|41|56|86|225|237|243|242|682|57|269|238|506|53|5999|61|1345|357|420|49|253|1767|45|1809|1829|1849|213|593|20|291|212|34|372|251|358|679|500|33|298|691|241|44|995|44|233|350|224|590|220|245|240|30|1473|299|502|594|1671|592|852|504|385|509|36|62|44|91|246|353|98|964|354|972|39|1876|44|962|81|76|77|254|996|855|686|1869|82|383|965|856|961|231|218|1758|423|94|266|370|352|371|853|590|212|377|373|261|960|52|692|389|223|356|95|382|976|1670|258|222|1664|596|230|265|60|262|264|687|227|672|234|505|683|31|47|977|674|64|968|92|507|64|51|63|680|675|48|1787|1939|850|351|595|970|689|974|262|40|7|250|966|249|221|65|500|4779|677|232|503|378|252|508|381|211|239|597|421|386|46|268|1721|248|963|1649|235|228|66|992|690|993|670|676|1868|216|90|688|886|255|256|380|598|1|998|3906698|379|1784|58|1284|1340|84|678|681|685|967|27|260|263)(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{4,20}$/

Finding a branch point with Git?

The following implements git equivalent of svn log --stop-on-copy and can also be used to find branch origin.

Approach

  1. Get head for all branches
  2. collect mergeBase for target branch each other branch
  3. git.log and iterate
  4. Stop at first commit that appears in the mergeBase list

Like all rivers run to the sea, all branches run to master and therefore we find merge-base between seemingly unrelated branches. As we walk back from branch head through ancestors, we can stop at the first potential merge base since in theory it should be origin point of this branch.

Notes

  • I haven't tried this approach where sibling and cousin branches merged between each other.
  • I know there must be a better solution.

details: https://stackoverflow.com/a/35353202/9950

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

How to show all of columns name on pandas dataframe?

Not a conventional answer, but I guess you could transpose the dataframe to look at the rows instead of the columns. I use this because I find looking at rows more 'intuitional' than looking at columns:

data_all2.T

This should let you view all the rows. This action is not permanent, it just lets you view the transposed version of the dataframe.

If the rows are still truncated, just use print(data_all2.T) to view everything.

How to install an apk on the emulator in Android Studio?

Just drag APK file to android emulator it will install automatically.

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

WordPress - Check if user is logged in

Try following code that worked fine for me

global $current_user;
get_currentuserinfo();

Then, use following code to check whether user has logged in or not.

if ($current_user->ID == '') { 
    //show nothing to user
}
else { 
    //write code to show menu here
}

Can I redirect the stdout in python into some sort of string buffer?

Just to add to Ned's answer above: you can use this to redirect output to any object that implements a write(str) method.

This can be used to good effect to "catch" stdout output in a GUI application.

Here's a silly example in PyQt:

import sys
from PyQt4 import QtGui

class OutputWindow(QtGui.QPlainTextEdit):
    def write(self, txt):
        self.appendPlainText(str(txt))

app = QtGui.QApplication(sys.argv)
out = OutputWindow()
sys.stdout=out
out.show()
print "hello world !"

Declaring variables inside loops, good practice or bad practice?

Generally, it's a very good practice to keep it very close.

In some cases, there will be a consideration such as performance which justifies pulling the variable out of the loop.

In your example, the program creates and destroys the string each time. Some libraries use a small string optimization (SSO), so the dynamic allocation could be avoided in some cases.

Suppose you wanted to avoid those redundant creations/allocations, you would write it as:

for (int counter = 0; counter <= 10; counter++) {
   // compiler can pull this out
   const char testing[] = "testing";
   cout << testing;
}

or you can pull the constant out:

const std::string testing = "testing";
for (int counter = 0; counter <= 10; counter++) {
   cout << testing;
}

Do most compilers realize that the variable has already been declared and just skip that portion, or does it actually create a spot for it in memory each time?

It can reuse the space the variable consumes, and it can pull invariants out of your loop. In the case of the const char array (above) - that array could be pulled out. However, the constructor and destructor must be executed at each iteration in the case of an object (such as std::string). In the case of the std::string, that 'space' includes a pointer which contains the dynamic allocation representing the characters. So this:

for (int counter = 0; counter <= 10; counter++) {
   string testing = "testing";
   cout << testing;
}

would require redundant copying in each case, and dynamic allocation and free if the variable sits above the threshold for SSO character count (and SSO is implemented by your std library).

Doing this:

string testing;
for (int counter = 0; counter <= 10; counter++) {
   testing = "testing";
   cout << testing;
}

would still require a physical copy of the characters at each iteration, but the form could result in one dynamic allocation because you assign the string and the implementation should see there is no need to resize the string's backing allocation. Of course, you wouldn't do that in this example (because multiple superior alternatives have already been demonstrated), but you might consider it when the string or vector's content varies.

So what do you do with all those options (and more)? Keep it very close as a default -- until you understand the costs well and know when you should deviate.