Programs & Examples On #Oracle type

LINQ: combining join and group by

I met the same problem as you.

I push two tables result into t1 object and group t1.

 from p in Products                         
  join bp in BaseProducts on p.BaseProductId equals bp.Id
  select new {
   p,
   bp
  } into t1
 group t1 by t1.p.SomeId into g
 select new ProductPriceMinMax { 
  SomeId = g.FirstOrDefault().p.SomeId, 
  CountryCode = g.FirstOrDefault().p.CountryCode, 
  MinPrice = g.Min(m => m.bp.Price), 
  MaxPrice = g.Max(m => m.bp.Price),
  BaseProductName = g.FirstOrDefault().bp.Name
};

What's the difference between Invoke() and BeginInvoke()

Building on Jon Skeet's reply, there are times when you want to invoke a delegate and wait for its execution to complete before the current thread continues. In those cases the Invoke call is what you want.

In multi-threading applications, you may not want a thread to wait on a delegate to finish execution, especially if that delegate performs I/O (which could make the delegate and your thread block).

In those cases the BeginInvoke would be useful. By calling it, you're telling the delegate to start but then your thread is free to do other things in parallel with the delegate.

Using BeginInvoke increases the complexity of your code but there are times when the improved performance is worth the complexity.

python modify item in list, save back in list

You could do this:

for idx, item in enumerate(list):
   if 'foo' in item:
       item = replace_all(...)
       list[idx] = item

H2 database error: Database may be already in use: "Locked by another process"

If you are running same app into multiple ports where app uses single database (h2), then add AUTO_SERVER=TRUE in the url as follows:

jdbc:h2:file:C:/simple-commerce/price;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE;AUTO_SERVER=TRUE

Why does git say "Pull is not possible because you have unmerged files"?

What is currently happening is, that you have a certain set of files, which you have tried merging earlier, but they threw up merge conflicts. Ideally, if one gets a merge conflict, he should resolve them manually, and commit the changes using git add file.name && git commit -m "removed merge conflicts". Now, another user has updated the files in question on his repository, and has pushed his changes to the common upstream repo.

It so happens, that your merge conflicts from (probably) the last commit were not not resolved, so your files are not merged all right, and hence the U(unmerged) flag for the files. So now, when you do a git pull, git is throwing up the error, because you have some version of the file, which is not correctly resolved.

To resolve this, you will have to resolve the merge conflicts in question, and add and commit the changes, before you can do a git pull.

Sample reproduction and resolution of the issue:

# Note: commands below in format `CUURENT_WORKING_DIRECTORY $ command params`
Desktop $ cd test

First, let us create the repository structure

test $ mkdir repo && cd repo && git init && touch file && git add file && git commit -m "msg"
repo $ cd .. && git clone repo repo_clone && cd repo_clone
repo_clone $ echo "text2" >> file && git add file && git commit -m "msg" && cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone

Now we are in repo_clone, and if you do a git pull, it will throw up conflicts

repo_clone $ git pull origin master
remote: Counting objects: 5, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From /home/anshulgoyal/Desktop/test/test/repo
 * branch            master     -> FETCH_HEAD
   24d5b2e..1a1aa70  master     -> origin/master
Auto-merging file
CONFLICT (content): Merge conflict in file
Automatic merge failed; fix conflicts and then commit the result.

If we ignore the conflicts in the clone, and make more commits in the original repo now,

repo_clone $ cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone

And then we do a git pull, we get

repo_clone $ git pull
U   file
Pull is not possible because you have unmerged files.
Please, fix them up in the work tree, and then use 'git add/rm <file>'
as appropriate to mark resolution, or use 'git commit -a'.

Note that the file now is in an unmerged state and if we do a git status, we can clearly see the same:

repo_clone $ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
  (use "git pull" to merge the remote branch into yours)

You have unmerged paths.
  (fix conflicts and run "git commit")

Unmerged paths:
  (use "git add <file>..." to mark resolution)

        both modified:      file

So, to resolve this, we first need to resolve the merge conflict we ignored earlier

repo_clone $ vi file

and set its contents to

text2
text1
text1

and then add it and commit the changes

repo_clone $ git add file && git commit -m "resolved merge conflicts"
[master 39c3ba1] resolved merge conflicts

Call static methods from regular ES6 class methods

I stumbled over this thread searching for answer to similar case. Basically all answers are found, but it's still hard to extract the essentials from them.

Kinds of Access

Assume a class Foo probably derived from some other class(es) with probably more classes derived from it.

Then accessing

  • from static method/getter of Foo
    • some probably overridden static method/getter:
      • this.method()
      • this.property
    • some probably overridden instance method/getter:
      • impossible by design
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • impossible by design
  • from instance method/getter of Foo
    • some probably overridden static method/getter:
      • this.constructor.method()
      • this.constructor.property
    • some probably overridden instance method/getter:
      • this.method()
      • this.property
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • not possible by intention unless using some workaround:
        • Foo.prototype.method.call( this )
        • Object.getOwnPropertyDescriptor( Foo.prototype,"property" ).get.call(this);

Keep in mind that using this isn't working this way when using arrow functions or invoking methods/getters explicitly bound to custom value.

Background

  • When in context of an instance's method or getter
    • this is referring to current instance.
    • super is basically referring to same instance, but somewhat addressing methods and getters written in context of some class current one is extending (by using the prototype of Foo's prototype).
    • definition of instance's class used on creating it is available per this.constructor.
  • When in context of a static method or getter there is no "current instance" by intention and so
    • this is available to refer to the definition of current class directly.
    • super is not referring to some instance either, but to static methods and getters written in context of some class current one is extending.

Conclusion

Try this code:

_x000D_
_x000D_
class A {_x000D_
  constructor( input ) {_x000D_
    this.loose = this.constructor.getResult( input );_x000D_
    this.tight = A.getResult( input );_x000D_
    console.log( this.scaledProperty, Object.getOwnPropertyDescriptor( A.prototype, "scaledProperty" ).get.call( this ) );_x000D_
  }_x000D_
_x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 100;_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return input * this.scale;_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 2;_x000D_
  }_x000D_
}_x000D_
_x000D_
class B extends A {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
    this.tight = B.getResult( input ) + " (of B)";_x000D_
  }_x000D_
  _x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 10000;_x000D_
  }_x000D_
_x000D_
  static get scale() {_x000D_
    return 4;_x000D_
  }_x000D_
}_x000D_
_x000D_
class C extends B {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 5;_x000D_
  }_x000D_
}_x000D_
_x000D_
class D extends C {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return super.getResult( input ) + " (overridden)";_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 10;_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
let instanceA = new A( 4 );_x000D_
console.log( "A.loose", instanceA.loose );_x000D_
console.log( "A.tight", instanceA.tight );_x000D_
_x000D_
let instanceB = new B( 4 );_x000D_
console.log( "B.loose", instanceB.loose );_x000D_
console.log( "B.tight", instanceB.tight );_x000D_
_x000D_
let instanceC = new C( 4 );_x000D_
console.log( "C.loose", instanceC.loose );_x000D_
console.log( "C.tight", instanceC.tight );_x000D_
_x000D_
let instanceD = new D( 4 );_x000D_
console.log( "D.loose", instanceD.loose );_x000D_
console.log( "D.tight", instanceD.tight );
_x000D_
_x000D_
_x000D_

How to declare std::unique_ptr and what is the use of it?

The constructor of unique_ptr<T> accepts a raw pointer to an object of type T (so, it accepts a T*).

In the first example:

unique_ptr<int> uptr (new int(3));

The pointer is the result of a new expression, while in the second example:

unique_ptr<double> uptr2 (pd);

The pointer is stored in the pd variable.

Conceptually, nothing changes (you are constructing a unique_ptr from a raw pointer), but the second approach is potentially more dangerous, since it would allow you, for instance, to do:

unique_ptr<double> uptr2 (pd);
// ...
unique_ptr<double> uptr3 (pd);

Thus having two unique pointers that effectively encapsulate the same object (thus violating the semantics of a unique pointer).

This is why the first form for creating a unique pointer is better, when possible. Notice, that in C++14 we will be able to do:

unique_ptr<int> p = make_unique<int>(42);

Which is both clearer and safer. Now concerning this doubt of yours:

What is also not clear to me, is how pointers, declared in this way will be different from the pointers declared in a "normal" way.

Smart pointers are supposed to model object ownership, and automatically take care of destroying the pointed object when the last (smart, owning) pointer to that object falls out of scope.

This way you do not have to remember doing delete on objects allocated dynamically - the destructor of the smart pointer will do that for you - nor to worry about whether you won't dereference a (dangling) pointer to an object that has been destroyed already:

{
    unique_ptr<int> p = make_unique<int>(42);
    // Going out of scope...
}
// I did not leak my integer here! The destructor of unique_ptr called delete

Now unique_ptr is a smart pointer that models unique ownership, meaning that at any time in your program there shall be only one (owning) pointer to the pointed object - that's why unique_ptr is non-copyable.

As long as you use smart pointers in a way that does not break the implicit contract they require you to comply with, you will have the guarantee that no memory will be leaked, and the proper ownership policy for your object will be enforced. Raw pointers do not give you this guarantee.

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

If you want to hover the popover itself as well you have to use a manual trigger.

This is what i came up with:

function enableThumbPopover() {
    var counter;

    $('.thumbcontainer').popover({
        trigger: 'manual',
        animation: false,
        html: true,
        title: function () {
            return $(this).parent().find('.thumbPopover > .title').html();
        },
        content: function () {
            return $(this).parent().find('.thumbPopover > .body').html();
        },
        container: 'body',
        placement: 'auto'
    }).on("mouseenter",function () {
        var _this = this; // thumbcontainer

        console.log('thumbcontainer mouseenter')
        // clear the counter
        clearTimeout(counter);
        // Close all other Popovers
        $('.thumbcontainer').not(_this).popover('hide');

        // start new timeout to show popover
        counter = setTimeout(function(){
            if($(_this).is(':hover'))
            {
                $(_this).popover("show");
            }
            $(".popover").on("mouseleave", function () {
                $('.thumbcontainer').popover('hide');
            });
        }, 400);

    }).on("mouseleave", function () {
        var _this = this;

        setTimeout(function () {
            if (!$(".popover:hover").length) {
                if(!$(_this).is(':hover')) // change $(this) to $(_this) 
                {
                    $(_this).popover('hide');
                }
            }
        }, 200);
    });
}

Converting HTML to Excel?

So long as Excel can open the file, the functionality to change the format of the opened file is built in.

To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).

To do it using VBA, the code would look like this:

Sub Open_HTML_Save_XLSX()

    Workbooks.Open Filename:="C:\Temp\Example.html"
    ActiveWorkbook.SaveAs Filename:= _
        "C:\Temp\Example.xlsx", FileFormat:= _
        xlOpenXMLWorkbook

End Sub

converting numbers in to words C#

When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:

{1, "one"}
{2, "two"}
{30, "thirty"}

You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.

After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.

What is InputStream & Output Stream? Why and when do we use them?

The goal of InputStream and OutputStream is to abstract different ways to input and output: whether the stream is a file, a web page, or the screen shouldn't matter. All that matters is that you receive information from the stream (or send information into that stream.)

InputStream is used for many things that you read from.

OutputStream is used for many things that you write to.

Here's some sample code. It assumes the InputStream instr and OutputStream osstr have already been created:

int i;

while ((i = instr.read()) != -1) {
    osstr.write(i);
}

instr.close();
osstr.close();

Accessing bash command line args $@ vs $*

The difference appears when the special parameters are quoted. Let me illustrate the differences:

$ set -- "arg  1" "arg  2" "arg  3"

$ for word in $*; do echo "$word"; done
arg
1
arg
2
arg
3

$ for word in $@; do echo "$word"; done
arg
1
arg
2
arg
3

$ for word in "$*"; do echo "$word"; done
arg  1 arg  2 arg  3

$ for word in "$@"; do echo "$word"; done
arg  1
arg  2
arg  3

one further example on the importance of quoting: note there are 2 spaces between "arg" and the number, but if I fail to quote $word:

$ for word in "$@"; do echo $word; done
arg 1
arg 2
arg 3

and in bash, "$@" is the "default" list to iterate over:

$ for word; do echo "$word"; done
arg  1
arg  2
arg  3

CSS3 transitions inside jQuery .css()

Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.

Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.

JS Fiddle Live Demo

Javascript:

$("#startTransition").on("click", function()
{

    if( $(".boxOne").is(":visible")) 
    {
        $(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
        $(".boxTwo").css({ x: '100%' });
        $(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
        return;        
    }

    $(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
    $(".boxOne").css({ x: '100%' });
    $(".boxOne").show().transition({ x: '0%', opacity: 1.0 });

});

Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.

ExecutorService that interrupts tasks after a timeout

It seems problem is not in JDK bug 6602600 ( it was solved at 2010-05-22), but in incorrect call of sleep(10) in circle. Addition note, that the main Thread must give directly CHANCE to other threads to realize thier tasks by invoke SLEEP(0) in EVERY branch of outer circle. It is better, I think, to use Thread.yield() instead of Thread.sleep(0)

The result corrected part of previous problem code is such like this:

.......................
........................
Thread.yield();         

if (i % 1000== 0) {
System.out.println(i + "/" + counter.get()+ "/"+service.toString());
}

//                
//                while (i > counter.get()) {
//                    Thread.sleep(10);
//                } 

It works correctly with amount of outer counter up to 150 000 000 tested circles.

Authenticating against Active Directory with Java on Linux

Here's the code I put together based on example from this blog: LINK and this source: LINK.

import com.sun.jndi.ldap.LdapCtxFactory;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.AuthenticationException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;

class App2 {

    public static void main(String[] args) {

        if (args.length != 4 && args.length != 2) {
            System.out.println("Purpose: authenticate user against Active Directory and list group membership.");
            System.out.println("Usage: App2 <username> <password> <domain> <server>");
            System.out.println("Short usage: App2 <username> <password>");
            System.out.println("(short usage assumes 'xyz.tld' as domain and 'abc' as server)");
            System.exit(1);
        }

        String domainName;
        String serverName;

        if (args.length == 4) {
            domainName = args[2];
            serverName = args[3];
        } else {
            domainName = "xyz.tld";
            serverName = "abc";
        }

        String username = args[0];
        String password = args[1];

        System.out
                .println("Authenticating " + username + "@" + domainName + " through " + serverName + "." + domainName);

        // bind by using the specified username/password
        Hashtable props = new Hashtable();
        String principalName = username + "@" + domainName;
        props.put(Context.SECURITY_PRINCIPAL, principalName);
        props.put(Context.SECURITY_CREDENTIALS, password);
        DirContext context;

        try {
            context = LdapCtxFactory.getLdapCtxInstance("ldap://" + serverName + "." + domainName + '/', props);
            System.out.println("Authentication succeeded!");

            // locate this user's record
            SearchControls controls = new SearchControls();
            controls.setSearchScope(SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),
                    "(& (userPrincipalName=" + principalName + ")(objectClass=user))", controls);
            if (!renum.hasMore()) {
                System.out.println("Cannot locate user information for " + username);
                System.exit(1);
            }
            SearchResult result = renum.next();

            List<String> groups = new ArrayList<String>();
            Attribute memberOf = result.getAttributes().get("memberOf");
            if (memberOf != null) {// null if this user belongs to no group at all
                for (int i = 0; i < memberOf.size(); i++) {
                    Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" });
                    Attribute att = atts.get("CN");
                    groups.add(att.get().toString());
                }
            }

            context.close();

            System.out.println();
            System.out.println("User belongs to: ");
            Iterator ig = groups.iterator();
            while (ig.hasNext()) {
                System.out.println("   " + ig.next());
            }

        } catch (AuthenticationException a) {
            System.out.println("Authentication failed: " + a);
            System.exit(1);
        } catch (NamingException e) {
            System.out.println("Failed to bind to LDAP / get account information: " + e);
            System.exit(1);
        }
    }

    private static String toDC(String domainName) {
        StringBuilder buf = new StringBuilder();
        for (String token : domainName.split("\\.")) {
            if (token.length() == 0)
                continue; // defensive check
            if (buf.length() > 0)
                buf.append(",");
            buf.append("DC=").append(token);
        }
        return buf.toString();
    }

}

Android Studio Gradle Configuration with name 'default' not found

I had similar issue and found very simple way to add a library to the project.

  1. Create folder "libs" in the root of your project.
  2. Copy JAR file into that folder.
  3. Go back to Android Studio, locate your JAR file and right click it, choose "Add As Library...", it will ask you only to which module you want to add it, well choose "app".

Now in your "app" module you can use classes from that JAR, it will be able to locate and add "import" declarations automatically and compile just okay. The only issue might be is that it adds dependency with absolute path like:

compile files('/home/user/proj/theproj/libs/thelib-1.2.3.jar')

in your "app/build.gradle".

Hope that helps!

Replace \n with actual new line in Sublime Text

On Mac, Shift+CMD+F for search and replace. Search for '\n' and replace with Shift+Enter.

Why does AngularJS include an empty option in select?

This works perfectly fine

<select ng-model="contact.Title" ng-options="co for co in['Mr.','Ms.','Mrs.','Dr.','Prof.']">
    <option style="display:none" value=""></option>
</select>

the way it works is, that this gives the first option to be displayed before selecting something and the display:none removes it form the dropdown so if you want you can do

<select ng-model="contact.Title" ng-options="co for co in['Mr.','Ms.','Mrs.','Dr.','Prof.']">
    <option style="display:none" value="">select an option...</option>
</select>

and this will give you the select and option before selecting but once selected it will disappear, and it will not show up in the dropdown.

How to get a URL parameter in Express?

If you want to grab the query parameter value in the URL, follow below code pieces

//url.localhost:8888/p?tagid=1234
req.query.tagid
OR
req.param.tagid

If you want to grab the URL parameter using Express param function

Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

This can be used for validations or grabbing important information about item.

An example for this would be:

// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {

// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';

// save name to the request
req.tagid= modified;

next();
});

// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');
});

What version of javac built my jar?

You can't tell from the JAR file itself, necessarily.

Download a hex editor and open one of the class files inside the JAR and look at byte offsets 4 through 7. The version information is built in.

http://en.wikipedia.org/wiki/Java_class_file

Note: As mentioned in the comment below,

those bytes tell you what version the class has been compiled FOR, not what version compiled it.

Disabling contextual LOB creation as createClob() method threw error

As mentioned in other comments using

hibernate.temp.use_jdbc_metadata_defaults = false

...will fix the annoying message, but can lead to many other surprising problems. Better solution is just to disable contextual LOB creation with this:

hibernate.jdbc.lob.non_contextual_creation = true

This will cause Hibernate (in my case, its 5.3.10.Final) to skip probing the JDBC driver and just output following message:

HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true

So far it looks like this setting doesn't cause any problems.

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

You should never use the unidirectional @OneToMany annotation because:

  1. It generates inefficient SQL statements
  2. It creates an extra table which increases the memory footprint of your DB indexes

Now, in your first example, both sides are owning the association, and this is bad.

While the @JoinColumn would let the @OneToMany side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy attribute on the @OneToMany side.

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<APost> aPosts;

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<BPost> bPosts;
}

public class BPost extends Post {

    @ManyToOne(fetch=FetchType.LAZY)    
    public User user;
}

public class APost extends Post {

     @ManyToOne(fetch=FetchType.LAZY) 
     public User user;
}

Get the directory from a file path in java (android)

I have got solution on this after 4 days, Please note following points while giving path to File class in Android(Java):

  1. Use path for internal storage String path="/storage/sdcard0/myfile.txt";
  2. path="/storage/sdcard1/myfile.txt";
  3. mention permissions in Manifest file.

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

  4. First check file length for confirmation.
  5. Check paths in ES File Explorer regarding sdcard0 & sdcard1 is this same or else......

e.g.

File file=new File(path);
long=file.length();//in Bytes

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

If yoou use Contains, you could get false positives. Suppose you have a string that contains such text: "My text data Mdd LH" Using Contains method, this method will return true for call. The approach is use equals operator:

bool exists = myStringList.Any(c=>c == "Mdd LH")

Kill python interpeter in linux from the terminal

You can try the killall command:

killall python

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

It doesn't look like DD-MMM-YYYY is supported by default (at least, with dash as separator). However, using the AS clause, you should be able to do something like:

SELECT CONVERT(VARCHAR(11), SYSDATETIME(), 106) AS [DD-MON-YYYY]

See here: http://www.sql-server-helper.com/sql-server-2008/sql-server-2008-date-format.aspx

PUT vs. POST in REST

If you are familiar with database operations, there are

  1. Select
  2. Insert
  3. Update
  4. Delete
  5. Merge (Update if already existing, else insert)

I use PUT for Merge and update like operations and use POST for Insertions.

How to show current user name in a cell?

if you don't want to create a UDF in VBA or you can't, this could be an alternative.

=Cell("Filename",A1) this will give you the full file name, and from this you could get the user name with something like this:

=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)


This Formula runs only from a workbook saved earlier.

You must start from 4th position because of the first slash from the drive.

How to fetch data from local JSON file on react native?

For ES6/ES2015 you can import directly like:

// example.json
{
    "name": "testing"
}


// ES6/ES2015
// app.js
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'

If you use typescript, you may declare json module like:

// tying.d.ts
declare module "*.json" {
    const value: any;
    export default value;
}

How to get a list of installed android applications and pick one to run

To filter on sytem based apps :

private boolean isSystemPackage(ResolveInfo ri) {
    return (ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
}

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

Is there way to use two PHP versions in XAMPP?

Use this php switcher

You can control php version to any your project you want via vhost config.

Check if PHP session has already started

On PHP 5.3 this works for me:

if(!strlen(session_id())){
    session_name('someSpecialName');
    session_start();
} 

then you have. If you do not put the not at if statement beginning the session will start any way I do not why.

Ajax using https on an http page

Check out the opensource Forge project. It provides a JavaScript TLS implementation, along with some Flash to handle the actual cross-domain requests:

http://github.com/digitalbazaar/forge/blob/master/README

In short, Forge will enable you to make XmlHttpRequests from a web page loaded over http to an https site. You will need to provide a Flash cross-domain policy file via your server to enable the cross-domain requests. Check out the blog posts at the end of the README to get a more in-depth explanation for how it works.

However, I should mention that Forge is better suited for requests between two different https-domains. The reason is that there's a potential MiTM attack. If you load the JavaScript and Flash from a non-secure site it could be compromised. The most secure use is to load it from a secure site and then use it to access other sites (secure or otherwise).

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

There are different ways we can pass the Access-Control-Expose-Headers.

  • As jgauffin has explained we can create a new attribute.
  • As LaundroMatt has explained we can add in the web.config file.
  • Another way is we can add code as below in the webApiconfig.cs file.

    config.EnableCors(new EnableCorsAttribute("", headers: "", methods: "*",exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });

Or we can add below code in the Global.Asax file.

protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
                HttpContext.Current.Response.End();
            }
        }

I have written it for the options. Please modify the same as per your need.

Happy Coding !!

Infinity symbol with HTML

You can use the following:

  • literal: 8 (if the encoding you use can encode it — UTF-8 can, for example)
  • character reference: &#8734; (decimal), &#x221E; (hexadecimal)
  • entity reference: &infin;

But whether it is displayed correctly does also depend on the font the text is displayed with.

push object into array

I'm not really sure, but you can try some like this:

var pack = function( arr ) {
    var length = arr.length,
        result = {},
        i;

    for ( i = 0; i < length; i++ ) {
        result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
    }

    return result;
};

pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}

How do I size a UITextView to its content?

I found out a way to resize the height of a text field according to the text inside it and also arrange a label below it based on the height of the text field! Here is the code.

UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 10)];
NSString *str = @"This is a test text view to check the auto increment of height of a text view. This is only a test. The real data is something different.";
_textView.text = str;

[self.view addSubview:_textView];
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 5 + frame.origin.y + frame.size.height, 300, 20)];
lbl.text = @"Hello!";
[self.view addSubview:lbl];

Registry key Error: Java version has value '1.8', but '1.7' is required

You have to define your jdk folder in variable JAVA_HOME, add %JAVA_HOME% to your variable path

Delete or change name of your java.exe, javaw.exe and javaws in your folder system32

execute cmd.exe, java -version now take the new version that you define in JAVA_HOME.

Is this a good way to clone an object in ES6?

If the methods you used isn't working well with objects involving data types like Date, try this

Import _

import * as _ from 'lodash';

Deep clone object

myObjCopy = _.cloneDeep(myObj);

Getting the first index of an object

There is no way to get the first element, seeing as "hashes" (objects) in JavaScript have unordered properties. Your best bet is to store the keys in an array:

var keys = ["foo", "bar", "baz"];

Then use that to get the proper value:

object[keys[0]]

What do the python file extensions, .pyc .pyd .pyo stand for?

  • .py - Regular script
  • .py3 - (rarely used) Python3 script. Python3 scripts usually end with ".py" not ".py3", but I have seen that a few times
  • .pyc - compiled script (Bytecode)
  • .pyo - optimized pyc file (As of Python3.5, Python will only use pyc rather than pyo and pyc)
  • .pyw - Python script to run in Windowed mode, without a console; executed with pythonw.exe
  • .pyx - Cython src to be converted to C/C++
  • .pyd - Python script made as a Windows DLL
  • .pxd - Cython script which is equivalent to a C/C++ header
  • .pxi - MyPy stub
  • .pyi - Stub file (PEP 484)
  • .pyz - Python script archive (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .pywz - Python script archive for MS-Windows (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .py[cod] - wildcard notation in ".gitignore" that means the file may be ".pyc", ".pyo", or ".pyd".
  • .pth - a path configuration file; its contents are additional items (one per line) to be added to sys.path. See site module.

A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/

Java Try Catch Finally blocks without Catch

Regardless of exception thrown or not in try block - finally block will be executed. Exception would not be caught.

Detect IF hovering over element with jQuery

Expanding on @Mohamed's answer. You could use a little encapsulation

Like this:

jQuery.fn.mouseIsOver = function () {
    if($(this[0]).is(":hover"))
    {
        return true;
    }
    return false;
}; 

Use it like:

$("#elem").mouseIsOver();//returns true or false

Forked the fiddle: http://jsfiddle.net/cgWdF/1/

Trying to get property of non-object - CodeIgniter

To get the value:

$query = $this->db->query("YOUR QUERY");

Then, for single row from(in controller):

$query1 = $query->row();
$data['product'] = $query1;

In view, you can use your own code (above code)

Convert a list to a dictionary in Python

{x: a[a.index(x)+1] for x in a if a.index(x) % 2 ==0}

result : {'hello': 'world', '1': '2'}

How to convert a negative number to positive?

If "keep a positive one" means you want a positive number to stay positive, but also convert a negative number to positive, use abs():

>>> abs(-1)
1
>>> abs(1)
1

How to create a dynamic array of integers

int main()
{
  int size;

  std::cin >> size;

  int *array = new int[size];

  delete [] array;

  return 0;
}

Don't forget to delete every array you allocate with new.

Multiple axis line chart in excel

The picture you showd in the question is actually a chart made using JavaScript. It is actually very easy to plot multi-axis chart using JavaScript with the help of 3rd party libraries like HighChart.js or D3.js. Here I propose to use the Funfun Excel add-in which allows you to use JavaScript directly in Excel so you could plot chart like you've showed easily in Excel. Here I made an example using Funfun in Excel.

enter image description here

You could see in this chart you have one axis of Rainfall at the left side while two axis of Temperature and Sea-pressure level at the right side. This is also a combination of line chart and bar chart for different datasets. In this example, with the help of the Funfun add-in, I used HighChart.js to plot this chart.

Funfun also has an online editor in which you could test your JavaScript code with you data. You could check the detailed code of this example on the link below.

https://www.funfun.io/1/#/edit/5a43b416b848f771fbcdee2c

Edit: The content on the previous link has been changed so I posted a new link here. The link below is the original link https://www.funfun.io/1/#/edit/5a55dc978dfd67466879eb24

If you are satisfied with the result you achieved in the online editor, you could easily load the result into you Excel using the URL above. Of couse first you need to insert the Funfun add-in from Insert - My add-ins. Here are some screenshots showing how you could do this.

enter image description here

enter image description here

enter image description here

Disclosure: I'm a developer of Funfun

Redis command to get all available keys?

SCAN doesn't require the client to load all the keys into memory like KEYS does. SCAN gives you an iterator you can use. I had a 1B records in my redis and I could never get enough memory to return all the keys at once.

Here is a python snippet to get all keys from the store matching a pattern and delete them:

import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
for key in r.scan_iter("key_pattern*"):
    print key

Tomcat - maxThreads vs maxConnections

From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections is the value of maxThreads unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads.

A method to reverse effect of java String.split()?

Since JDK8 I love Streams and Lambdas a lot, so I would suggest:

public static String join( String delimiter, String[] array )
{
    return Arrays.asList( array ).stream().collect( Collectors.joining( delimiter ) );
}

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Try this it worked for me.

sudo /usr/local/mysql/support-files/mysql.server start

Create a directory if it does not exist and then create the files in that directory as well

code:

// Create Directory if not exist then Copy a file.


public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {

    Path FROM = Paths.get(origin);
    Path TO = Paths.get(destination);
    File directory = new File(String.valueOf(destDir));

    if (!directory.exists()) {
        directory.mkdir();
    }
        //overwrite the destination file if it exists, and copy
        // the file attributes, including the rwx permissions
     CopyOption[] options = new CopyOption[]{
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES

        };
        Files.copy(FROM, TO, options);


}

How to customize a Spinner in Android

I have build a small demo project on this you could have a look to it Link to project

Generating 8-character only UUIDs

It is not possible since a UUID is a 16-byte number per definition. But of course, you can generate 8-character long unique strings (see the other answers).

Also be careful with generating longer UUIDs and substring-ing them, since some parts of the ID may contain fixed bytes (e.g. this is the case with MAC, DCE and MD5 UUIDs).

open read and close a file in 1 line of code

Python Standard Library Pathlib module does what you looking for:

Path('pagehead.section.htm').read_text()

Don't forget to import Path:

jsk@dev1:~$ python3
Python 3.5.2 (default, Sep 10 2016, 08:21:44)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pathlib import Path
>>> (Path("/etc") / "hostname").read_text()
'dev1.example\n'

On Python 27 install backported pathlib or pathlib2

Redirect from asp.net web api post action

Here is another way you can get to the root of your website without hard coding the url:

var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);

Note: Will only work if both your MVC website and WebApi are on the same URL

Node.js Write a line into a .txt file

I did a log file which prints data into text file using "Winston" log. The source code is here below,

const { createLogger, format, transports } = require('winston');
var fs = require('fs')
var logger = fs.createWriteStream('Data Log.txt', {`
flags: 'a' 
})
const os = require('os');
var sleep = require('system-sleep');
var endOfLine = require('os').EOL;
var t = '             ';var s = '         ';var q = '               ';
var array1=[];
var array2=[];
var array3=[];
var array4=[];

array1[0]  =  78;`
array1[1]  =  56;
array1[2]  =  24;
array1[3]  =  34;

for (var n=0;n<4;n++)
{
array2[n]=array1[n].toString();
}

for (var k=0;k<4;k++)
{
array3[k]=Buffer.from('                    ');
}

for (var a=0;a<4;a++)  
{
array4[a]=Buffer.from(array2[a]);
}

for (m=0;m<4;m++)
{
array4[m].copy(array3[m],0);
}

logger.write('Date'+q);
logger.write('Time'+(q+'  '))
logger.write('Data 01'+t);
logger.write('Data 02'+t); 
logger.write('Data 03'+t);
logger.write('Data 04'+t)

logger.write(endOfLine);
logger.write(endOfLine);
enter code here`enter code here`
}

function mydata()      //user defined function
{
logger.write(datechar+s);
logger.write(timechar+s);
for ( n = 0; n < 4; n++) 
{
logger.write(array3[n]);
}
logger.write(endOfLine); 
}

for (;;)
}
var now = new Date();
var dateFormat = require('dateformat');
var date = dateFormat(now,"isoDate");
var time = dateFormat(now, "h:MM:ss TT ");
var datechar = date.toString();
var timechar = time.toString();
mydata();
sleep(5*1000);
}

Get hostname of current request in node.js Express

Here's an alternate

req.hostname

Read about it in the Express Docs.

How do you Change a Package's Log Level using Log4j?

I just encountered the issue and couldn't figure out what was going wrong even after reading all the above and everything out there. What I did was

  1. Set root logger level to WARN
  2. Set package log level to DEBUG

Each logging implementation has it's own way of setting it via properties or via code(lot of help available on this)

Irrespective of all the above I would not get the logs in my console or my log file. What I had overlooked was the below...


enter image description here


All I was doing with the above jugglery was controlling only the production of the logs(at root/package/class etc), left of the red line in above image. But I was not changing the way displaying/consumption of the logs of the same, right of the red line in above image. Handler(Consumption) is usually defaulted at INFO, therefore your precious debug statements wouldn't come through. Consumption/displaying is controlled by setting the log levels for the Handlers(ConsoleHandler/FileHandler etc..) So I went ahead and set the log levels of all my handlers to finest and everything worked.

This point was not made clear in a precise manner in any place.

I hope someone scratching their head, thinking why the properties are not working will find this bit helpful.

How to calculate combination and permutation in R?

If you don't want your code to depend on other packages, you can always just write these functions:

perm = function(n, x) {
  factorial(n) / factorial(n-x)
}

comb = function(n, x) {
  factorial(n) / factorial(n-x) / factorial(x)
}

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

use func call @objc

func call(){

foo()

}

@objc func foo() {

}

Tomcat 7: How to set initial heap size correctly?

If it's not work in your centos 7 machine "export CATALINA_OPTS="-Xms512M -Xmx1024M"" then you can change heap memory from vi /etc/systemd/system/tomcat.service file then this value shown in your tomcat by help of ps -ef|grep tomcat.

Can a variable number of arguments be passed to a function?

Adding to the other excellent posts.

Sometimes you don't want to specify the number of arguments and want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method).

def manyArgs1(args):
  print args.a, args.b #note args.c is not used here

def manyArgs2(args):
  print args.c #note args.b and .c are not used here

class Args: pass

args = Args()
args.a = 1
args.b = 2
args.c = 3

manyArgs1(args) #outputs 1 2
manyArgs2(args) #outputs 3

Then you can do things like

myfuns = [manyArgs1, manyArgs2]
for fun in myfuns:
  fun(args)

How can I check if a key exists in a dictionary?

If you want to retrieve the key's value if it exists, you can also use

try:
    value = a[key]
except KeyError:
    # Key is not present
    pass

If you want to retrieve a default value when the key does not exist, use value = a.get(key, default_value). If you want to set the default value at the same time in case the key does not exist, use value = a.setdefault(key, default_value).

Get generic type of class at runtime

One simple solution for this cab be like below

public class GenericDemo<T>{
    private T type;

    GenericDemo(T t)
    {
        this.type = t;
    }

    public String getType()
    {
        return this.type.getClass().getName();
    }

    public static void main(String[] args)
    {
        GenericDemo<Integer> obj = new  GenericDemo<Integer>(5);
        System.out.println("Type: "+ obj.getType());
    }
}

Error in model.frame.default: variable lengths differ

Joran suggested to first remove the NAs before running the model. Thus, I removed the NAs, run the model and obtained the residuals. When I updated model2 by inclusion of the lagged residuals, the error message did not appear again.

Remove NAs

df2<-df1[complete.cases(df1),]

Run the main model

model2<-gam(death ~ pm10 + s(trend,k=14*7)+ s(temp,k=5), data=df2, family=poisson)

Obtain residuals

resid2 <- residuals(model2,type="deviance")

Update model2 by including the lag 1 residuals

model2_1 <- update(model2,.~.+ Lag(resid2,1),  na.action=na.omit)

How to wait 5 seconds with jQuery?

Based on Joey's answer, I came up with an intended (by jQuery, read about 'queue') solution.

It somewhat follows the jQuery.animate() syntax - allows to be chained with other fx functions, supports 'slow' and other jQuery.fx.speeds as well as being fully jQuery. And will be handled the same way as animations, if you stop those.

jsFiddle test ground with more usages (like showing off .stop()), can be found here.

the core of the solution is:

_x000D_
_x000D_
$('<queue/>')_x000D_
.delay(100 /*ms*/)_x000D_
.queue( (next) => { $('#result').text('done.'); next(); } );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

the whole as a plugin, supporting usage of $.wait() and $(..).wait() :

_x000D_
_x000D_
// add wait as $.wait() standalone and $(elem).wait() for animation chaining_x000D_
(function($) {_x000D_
_x000D_
  $.wait = function(duration, completeCallback, target) {_x000D_
    $target = $(target || '<queue />');_x000D_
    return $target.delay(duration).queue(function(next){completeCallback && completeCallback.call($target); next();});_x000D_
  }_x000D_
_x000D_
  $.fn.wait = function(duration, completeCallback) {_x000D_
    return $.wait.call(this, duration, completeCallback, this);_x000D_
  };_x000D_
_x000D_
})(jQuery);_x000D_
_x000D_
//TEST_x000D_
$(function() {_x000D_
_x000D_
  // stand alone_x000D_
  $.wait(1000, function() {_x000D_
    $('#result')_x000D_
    .append('...done');_x000D_
  });_x000D_
_x000D_
  // chained_x000D_
  $('#result')_x000D_
  .append('go...')_x000D_
  .wait('slow', function() {_x000D_
    $(this).append('after slow');_x000D_
  })_x000D_
  .css({color: 'green'});_x000D_
  _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

Note: since wait adds to the animation stack, $.css() is executed immediately - as it is supposed: expected jQuery behaviour.

How to upload file using Selenium WebDriver in Java

I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(

//open upload window upload.click();

//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);

What are XAND and XOR

Have a look

x   y      A    B   C   D   E   F   G   H   I   J   K   L   M   N

·   ·      T    ·   T   ·   T   ·   T   ·   T   ·   T   ·   T   ·
·   T      ·    T   T   ·   ·   T   T   ·   ·   T   T   ·   ·   T
T   ·      ·    ·   ·   T   T   T   T   ·   ·   ·   ·   T   T   T
T   T      ·    ·   ·   ·   ·   ·   ·   T   T   T   T   T   T   T

A) !(x OR y)    
B) !(x) AND y   
C) !(x) 
D) x AND !(y)   
E) !(y) 
F) x XOR y  
G) !(x AND y)   
H) x AND y  
I) !(x XOR y)   
J) y    
K) !(x) OR y    
L) x    
M) x OR !(y)    
N) x OR y

Get device token for push notification

Swift 4 This works for me:

Step 1 into TARGETS Click on add capability and select Push Notifications

Step 2 in AppDelegate.swift add the following code:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound]) { (didAllow, error) in
            
        }
        UIApplication.shared.registerForRemoteNotifications()
        
        return true
    }
    
    //Get device token
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
    {
        let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        
        print("The token: \(tokenString)")
    }

Eloquent - where not equal to

Fetching data with either null and value on where conditions are very tricky. Even if you are using straight Where and OrWhereNotNull condition then for every rows you will fetch both items ignoring other where conditions if applied. For example if you have more where conditions it will mask out those and still return with either null or value items because you used orWhere condition

The best way so far I found is as follows. This works as where (whereIn Or WhereNotNull)

Code::where(function ($query) {
            $query->where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id');                  
        })->get();

using OR and NOT in solr query

I don't know why that doesn't work, but this one is logically equivalent and it does work:

-(myField:superneat AND -myOtherField:somethingElse)

Maybe it has something to do with defining the same field twice in the query...

Try asking in the solr-user group, then post back here the final answer!

How do you use subprocess.check_output() in Python?

The right answer (using Python 2.7 and later, since check_output() was introduced then) is:

py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])

To demonstrate, here are my two programs:

py2.py:

import sys
print sys.argv

py3.py:

import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)

Running it:

$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"

Here's what's wrong with each of your versions:

py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])

First, str('python py2.py') is exactly the same thing as 'python py2.py'—you're taking a str, and calling str to convert it to an str. This makes the code harder to read, longer, and even slower, without adding any benefit.

More seriously, python py2.py can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py. Which you're not; you're trying to run, say, /usr/bin/python with first argument py2.py. So, you need to make them separate elements in the list.

Your second version fixes that, but you're missing the ' before test.txt'. This should give you a SyntaxError, probably saying EOL while scanning string literal.

Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:

>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'

That calls the "echo" command with an additional argument, "Hello World!".

Also:

-i is a positional argument for argparse, test.txt is what the -i is

I'm pretty sure -i is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.

Elegant solution for line-breaks (PHP)

I ended up writing a function that has worked for me well so far:

// pretty print data
function out($data, $label = NULL) {

  $CLI = (php_sapi_name() === 'cli') ? 'cli' : '';

  $gettype = gettype($data);

  if (isset($label)) {
    if ($CLI) { $label = $label . ': '; }
    else { $label = '<b>'.$label.'</b>: '; }
  }

  if ($gettype == 'string' || $gettype == 'integer' || $gettype == 'double' || $gettype == 'boolean') {
    if ($CLI) { echo $label . $data . "\n"; }
    else { echo $label . $data . "<br/>"; }
  }
  else {
    if ($CLI) { echo $label . print_r($data,1) . "\n"; } 
    else { echo $label . "<pre>".print_r($data,1)."</pre>"; }
  }
}


// Usage

out('Hello world!');

$var = 'Hello Stackoverflow!';
out($var, 'Label');

Where to place $PATH variable assertions in zsh?

tl;dr version: use ~/.zshrc

And read the man page to understand the differences between:

~/.zshrc, ~/.zshenv and ~/.zprofile.


Regarding my comment

In my comment attached to the answer kev gave, I said:

This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh. However, this only occurs if zsh is "invoked as sh or ksh"; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].

The ArchWiki ZSH link says:

At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).



To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from ~/.zshrc, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc is read for interactive shells, which may or may not suit your needs - if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then ~/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There's a bunch of files read on startup (check the linked man pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv not existing - if you need it, make it, and it will be read.

.bashrc and .bash_profile are not read by zsh, unless you explicitly source them from ~/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

How to split strings into text and number?

This is a little longer, but more versatile for cases where there are multiple, randomly placed, numbers in the string. Also, it requires no imports.

def getNumbers( input ):
    # Collect Info
    compile = ""
    complete = []

    for letter in input:
        # If compiled string
        if compile:
            # If compiled and letter are same type, append letter
            if compile.isdigit() == letter.isdigit():
                compile += letter
            
            # If compiled and letter are different types, append compiled string, and begin with letter
            else:
                complete.append( compile )
                compile = letter
            
        # If no compiled string, begin with letter
        else:
            compile = letter
        
    # Append leftover compiled string
    if compile:
        complete.append( compile )
    
    # Return numbers only
    numbers = [ word for word in complete if word.isdigit() ]
        
    return numbers

How can I use mySQL replace() to replace strings in multiple records?

This will help you.

UPDATE play_school_data SET title= REPLACE(title, "&#39;", "'") WHERE title = "Elmer&#39;s Parade";

Result:

title = Elmer's Parade

Phone mask with jQuery and Masked Input Plugin

If you don't want to show your mask as placeholder you should use jQuery Mask Plugin.

The cleanest way:

var options =  {
    onKeyPress: function(phone, e, field, options) {
        var masks = ['(00) 0000-00000', '(00) 00000-0000'];
        var mask = (phone.length>14) ? masks[1] : masks[0];
        $('.phone-input').mask(mask, options);
    }
};

$('.phone-input').mask('(00) 0000-00000', options);

How do I log a Python error with debug information?

If "debugging information" means the values present when exception was raised, then logging.exception(...) won't help. So you'll need a tool that logs all variable values along with the traceback lines automatically.

Out of the box you'll get log like

2020-03-30 18:24:31 main ERROR   File "./temp.py", line 13, in get_ratio
2020-03-30 18:24:31 main ERROR     return height / width
2020-03-30 18:24:31 main ERROR       height = 300
2020-03-30 18:24:31 main ERROR       width = 0
2020-03-30 18:24:31 main ERROR builtins.ZeroDivisionError: division by zero

Have a look at some pypi tools, I'd name:

Some of them give you pretty crash messages: enter image description here

But you might find some more on pypi

Duplicate symbols for architecture x86_64 under Xcode

Remove -all_load from Other Linker Flags. It works on my project

How do I pull my project from github?

Run these commands:

cd /pathToYourLocalProjectFolder

git pull origin master

Efficiency of Java "Double Brace Initialization"?

I was researching this and decided to do a more in depth test than the one provided by the valid answer.

Here is the code: https://gist.github.com/4368924

and this is my conclusion

I was surprised to find that in most of the run tests the internal initiation was actually faster (almost double in some cases). When working with large numbers the benefit seems to fade away.

Interestingly, the case that creates 3 objects on the loop loses it's benefit rans out sooner than on the other cases. I am not sure why this is happening and more testing should be done to reach any conclusions. Creating concrete implementations may help to avoid the class definition to be reloaded (if that's what's happening)

However, it is clear that not much overhead it observed in most cases for the single item building, even with large numbers.

One set back would be the fact that each of the double brace initiations creates a new class file that adds a whole disk block to the size of our application (or about 1k when compressed). A small footprint, but if it's used in many places it could potentially have an impact. Use this 1000 times and you are potentially adding a whole MiB to you applicaiton, which may be concerning on an embedded environment.

My conclusion? It can be ok to use as long as it is not abused.

Let me know what you think :)

How do I finish the merge after resolving my merge conflicts?

When there is a conflict during a merge, you have to finish the merge commit manually. It sounds like you've done the first two steps, to edit the files that conflicted and then run git add on them to mark them as resolved. Finally, you need to actually commit the merge with git commit. At that point you will be able to switch branches again.

Differences between .NET 4.0 and .NET 4.5 in High level in .NET

This answer may be late reply but it will be useful for seeing this topic in future.

The features of .NET framework 4.5 can be seen in the following link.

To summarize:

  • Installation

    .NET Framework 4.5 does not support Windows XP or Windows Server 2003, and therefore, if you have to create applications that target these operating systems, you will need to stay with .NET Framework 4.0. In contrast, Windows 8 and Windows Server 2012 in all of their editions include .NET Framework 4.5.

  • Support for Arrays Larger than 2 GB on 64-bit Platforms
  • Enhanced Background Server Garbage Collection
  • Support for Timeouts in Regular Expression Evaluations
  • Support for Unicode 6.0.0 in Culture-Sensitive Sorting and Casing Rules on Windows 8
  • Simple Default Culture Definition for an Application Domain
  • Internationalized Domain Names in Windows 8 Apps

How to send email from SQL Server?

To send mail through SQL Server we need to set up DB mail profile we can either use T-SQl or SQL Database mail option in sql server to create profile. After below code is used to send mail through query or stored procedure.

Use below link to create DB mail profile

http://www.freshcodehub.com/Article/42/configure-database-mail-in-sql-server-database

http://www.freshcodehub.com/Article/43/create-a-database-mail-configuration-using-t-sql-script

_x000D_
_x000D_
--Sending Test Mail_x000D_
EXEC msdb.dbo.sp_send_dbmail_x000D_
@profile_name = 'TestProfile', _x000D_
@recipients = 'To Email Here', _x000D_
@copy_recipients ='CC Email Here',             --For CC Email if exists_x000D_
@blind_copy_recipients= 'BCC Email Here',      --For BCC Email if exists_x000D_
@subject = 'Mail Subject Here', _x000D_
@body = 'Mail Body Here',_x000D_
@body_format='HTML',_x000D_
@importance ='HIGH',_x000D_
@file_attachments='C:\Test.pdf';               --For Attachments if exists
_x000D_
_x000D_
_x000D_

Property '...' has no initializer and is not definitely assigned in the constructor

change the

fieldname?: any[]; 

to this:

fieldname?: any; 

Listview Scroll to the end of the list after updating the list

Using : Set the head of the list to it bottom lv.setStackFromBottom(true);

Worked for me and the list is scrolled to the bottom automatically when it is first brought into visibility. The list then scrolls as it should with TRANSCRIPT_MODE_ALWAYS_SCROLL.

Removing duplicate rows from table in Oracle

For best performance, here is what I wrote :
(see execution plan)

DELETE FROM your_table
WHERE rowid IN 
  (select t1.rowid from your_table  t1
      LEFT OUTER JOIN (
      SELECT MIN(rowid) as rowid, column1,column2, column3
      FROM your_table 
      GROUP BY column1, column2, column3
  )  co1 ON (t1.rowid = co1.rowid)
  WHERE co1.rowid IS NULL
);

Maven Run Project

The above mentioned answers are correct but I am simplifying it for noobs like me.Go to your project's pom file. Add a new property exec.mainClass and give its value as the class which contains your main method. For me it was DriverClass in mainpkg. Change it as per your project. enter image description here

Having done this navigate to the folder that contains your project's pom.xml and run this on the command prompt mvn exec:java. This should call the main method.

Concat a string to SELECT * MySql

You cannot do this on multiple fields. You can also look for this.

Detect click outside element

I have updated MadisonTrash's answer to support Mobile Safari (which does not have click event, touchend must be used instead). This also incorporates a check so that the event isn't triggered by dragging on mobile devices.

Vue.directive('click-outside', {
    bind: function (el, binding, vnode) {
        el.eventSetDrag = function () {
            el.setAttribute('data-dragging', 'yes');
        }
        el.eventClearDrag = function () {
            el.removeAttribute('data-dragging');
        }
        el.eventOnClick = function (event) {
            var dragging = el.getAttribute('data-dragging');
            // Check that the click was outside the el and its children, and wasn't a drag
            if (!(el == event.target || el.contains(event.target)) && !dragging) {
                // call method provided in attribute value
                vnode.context[binding.expression](event);
            }
        };
        document.addEventListener('touchstart', el.eventClearDrag);
        document.addEventListener('touchmove', el.eventSetDrag);
        document.addEventListener('click', el.eventOnClick);
        document.addEventListener('touchend', el.eventOnClick);
    }, unbind: function (el) {
        document.removeEventListener('touchstart', el.eventClearDrag);
        document.removeEventListener('touchmove', el.eventSetDrag);
        document.removeEventListener('click', el.eventOnClick);
        document.removeEventListener('touchend', el.eventOnClick);
        el.removeAttribute('data-dragging');
    },
});

How to add a new column to a CSV file?

Append new column in existing csv file using python without header name

  default_text = 'Some Text'
# Open the input_file in read mode and output_file in write mode
    with open('problem-one-answer.csv', 'r') as read_obj, \
    open('output_1.csv', 'w', newline='') as write_obj:
# Create a csv.reader object from the input file object
    csv_reader = reader(read_obj)
# Create a csv.writer object from the output file object
    csv_writer = csv.writer(write_obj)
# Read each row of the input csv file as list
    for row in csv_reader:
# Append the default text in the row / list
        row.append(default_text)
# Add the updated row / list to the output file
        csv_writer.writerow(row)

Thankyou

How to center a View inside of an Android Layout?

I use android:layout_centerInParent="true" and it worked

Confirm postback OnClientClick button ASP.NET

Try this:

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
                       OnClick="BtnUserDelete_Click"
                       OnClientClick="if ( ! UserDeleteConfirmation()) return false;" 
 meta:resourcekey="BtnUserDeleteResource1" />

This way the "return" is only executed when the user clicks "cancel" and not when he clicks "ok".

By the way, you can shorten the UserDeleteConfirmation function to:

function UserDeleteConfirmation() {
    return confirm("Are you sure you want to delete this user?");
}

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Unfortunately, you need to manually construct the query parameters, because as far as I know, there is no built-in bind method for binding a list to an IN clause, similar to Hibernate's setParameterList(). However, you can accomplish the same with the following:

Python 3:

args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)' 
in_p=', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
cursor.execute(sql, args)

Python 2:

args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)' 
in_p=', '.join(map(lambda x: '%s', args))
sql = sql % in_p
cursor.execute(sql, args)

HTML 5: Is it <br>, <br/>, or <br />?

<br> and <br /> render differently in some browsers, so choosing either over the other isn't going to hurt your project, but do expect a bulk find..replace to affect the page render in some browsers, which may result in extra work for yourself or even embarrassment should the change affect nothing in your test browser, but break it in the preferred browser of your clients'.

I prefer <br> since it is what I have used since Erwise and Netscape Navigator (early web browsers), but there's no reason not to choose <br /> instead. It may be useful for some preprocessing, comparability, etc.

Even if your choice boils down to preferring the look of one over the other, or you (or your favourite HTML editor e.g. Dreamweaver) might like your code to be xml compliant. It's up to you.

A quick side note:

Not to be confused with br, but in addition you may also consider using wbr tags in your HTML: A word break opportunity tag, which specifies where in a text it would be ok to add a line-break.

For further reading, please have a read of the HTML5 spec.

Laravel 5 PDOException Could Not Find Driver

I'm using Ubuntu 16.04 and PHP 5.6.20

After too many problems, the below steps solved this for me:

  1. find php.ini path via phpinfo()

  2. uncomment

    extension=php_pdo_mysql.dll
    
  3. add this line

    extension=pdo_mysql.so
    
  4. then run

    sudo apt-get install php-mysql
    

How to avoid the "Circular view path" exception with Spring MVC test

Another simple approach:

package org.yourpackagename;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

      @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(PreferenceController.class);
        }


    public static void main(String[] args) {
        SpringApplication.run(PreferenceController.class, args);
    }
}

How to add new column to MYSQL table?

 $table  = 'your table name';
 $column = 'q6'
 $add = mysql_query("ALTER TABLE $table ADD $column VARCHAR( 255 ) NOT NULL");

you can change VARCHAR( 255 ) NOT NULL into what ever datatype you want.

Are the shift operators (<<, >>) arithmetic or logical in C?

Here are functions to guarantee logical right shift and arithmetic right shift of an int in C:

int logicalRightShift(int x, int n) {
    return (unsigned)x >> n;
}
int arithmeticRightShift(int x, int n) {
    if (x < 0 && n > 0)
        return x >> n | ~(~0U >> n);
    else
        return x >> n;
}

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

Allowed characters in filename

To be more precise about Mac OS X (now called MacOS) / in the Finder is interpreted to : in the Unix file system.

This was done for backward compatibility when Apple moved from Classic Mac OS.

It is legitimate to use a / in a file name in the Finder, looking at the same file in the terminal it will show up with a :.

And it works the other way around too: you can't use a / in a file name with the terminal, but a : is OK and will show up as a / in the Finder.

Some applications may be more restrictive and prohibit both characters to avoid confusion or because they kept logic from previous Classic Mac OS or for name compatibility between platforms.

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

HTML: how to make 2 tables with different CSS

Of course, just assign seperate css classes to both tables.

<table class="style1"></table>
<table class="style2"></table>

.css

table.style1 { //your css here}
table.style2 { //your css here}

Unexpected 'else' in "else" error

You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)       
} 

To put it more simply, if you have:

if(condition == TRUE) x <- TRUE
else x <- FALSE

Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:

if(condition == TRUE) {x <- TRUE
 } else {x <- FALSE}

Python in Xcode 4+?

You should try PyDev plug in for Eclipse. I tried alot of editors/IDE's to use with python, but the only one i liked the most is the PyDev plugin for Eclipse. It has code completion, debugger and many other nice features. Plus both are free.

How can I iterate over files in a given directory?

I really like using the scandir directive that is built into the os library. Here is a working example:

import os

i = 0
with os.scandir('/usr/local/bin') as root_dir:
    for path in root_dir:
        if path.is_file():
            i += 1
            print(f"Full path is: {path} and just the name is: {path.name}")
print(f"{i} files scanned successfully.")

Checkout subdirectories in Git?

You can revert uncommitted changes only to particular file or directory:

git checkout [some_dir|file.txt]

Make button width fit to the text

Try to add display:inline; to the CSS property of a button.

How do you specify table padding in CSS? ( table, not cell padding )

You can try the border-spacing property. That should do what you want. But you may want to see this answer.

What is Gradle in Android Studio?

You can find everything you need to know about Gradle here: Gradle Plugin User Guide

Goals of the new Build System

The goals of the new build system are:

  • Make it easy to reuse code and resources
  • Make it easy to create several variants of an application, either for multi-apk distribution or for different flavors of an application
  • Make it easy to configure, extend and customize the build process
  • Good IDE integration

Why Gradle?

Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins.

Here are some of its features that made us choose Gradle:

  • Domain Specific Language (DSL) to describe and manipulate the build logic
  • Build files are Groovy based and allow mixing of declarative elements through the DSL and using code to manipulate the DSL elements to provide custom logic.
  • Built-in dependency management through Maven and/or Ivy.
  • Very flexible. Allows using best practices but doesn’t force its own way of doing things.
  • Plugins can expose their own DSL and their own API for build files to use.
  • Good Tooling API allowing IDE integration

How do I spool to a CSV formatted file using SQLPLUS?

prefer to use "set colsep" in sqlplus prompt instead of editing col name one by one. Use sed to edit the output file.

set colsep '","'     -- separate columns with a comma
sed 's/^/"/;s/$/"/;s/\s *"/"/g;s/"\s */"/g' $outfile > $outfile.csv

Best way to copy a database (SQL Server 2008)

If you want to take a copy of a live database, do the Backup/Restore method.

[In SQLS2000, not sure about 2008:] Just keep in mind that if you are using SQL Server accounts in this database, as opposed to Windows accounts, if the master DB is different or out of sync on the development server, the user accounts will not translate when you do the restore. I've heard about an SP to remap them, but I can't remember which one it was.

What is sys.maxint in Python 3?

Python 3 ints do not have a maximum.

If your purpose is to determine the maximum size of an int in C when compiled the same way Python was, you can use the struct module to find out:

>>> import struct
>>> platform_c_maxint = 2 ** (struct.Struct('i').size * 8 - 1) - 1

If you are curious about the internal implementation details of Python 3 int objects, Look at sys.int_info for bits per digit and digit size details. No normal program should care about these.

Confused about stdin, stdout and stderr?

It would be more correct to say that stdin, stdout, and stderr are "I/O streams" rather than files. As you've noticed, these entities do not live in the filesystem. But the Unix philosophy, as far as I/O is concerned, is "everything is a file". In practice, that really means that you can use the same library functions and interfaces (printf, scanf, read, write, select, etc.) without worrying about whether the I/O stream is connected to a keyboard, a disk file, a socket, a pipe, or some other I/O abstraction.

Most programs need to read input, write output, and log errors, so stdin, stdout, and stderr are predefined for you, as a programming convenience. This is only a convention, and is not enforced by the operating system.

How to insert an object in an ArrayList at a specific position

Here is the simple arraylist example for insertion at specific index

ArrayList<Integer> str=new ArrayList<Integer>();
    str.add(0);
    str.add(1);
    str.add(2);
    str.add(3); 
    //Result = [0, 1, 2, 3]
    str.add(1, 11);
    str.add(2, 12);
    //Result = [0, 11, 12, 1, 2, 3]

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

Does this answer your question?

I have never used reinterpret_cast, and wonder whether running into a case that needs it isn't a smell of bad design. In the code base I work on dynamic_cast is used a lot. The difference with static_cast is that a dynamic_cast does runtime checking which may (safer) or may not (more overhead) be what you want (see msdn).

Detect Route Change with react-router

Update for React Router 5.1+.

import React from 'react';
import { useLocation, Switch } from 'react-router-dom'; 

const App = () => {
  const location = useLocation();

  React.useEffect(() => {
    console.log('Location changed');
  }, [location]);

  return (
    <Switch>
      {/* Routes go here */}
    </Switch>
  );
};

How to specify the actual x axis values to plot as x axis ticks in R

Take a closer look at the ?axis documentation. If you look at the description of the labels argument, you'll see that it is:

"a logical value specifying whether (numerical) annotations are 
to be made at the tickmarks,"

So, just change it to true, and you'll get your tick labels.

x <- seq(10,200,10)
y <- runif(x)
plot(x,y,xaxt='n')
axis(side = 1, at = x,labels = T)
# Since TRUE is the default for labels, you can just use axis(side=1,at=x)

Be careful that if you don't stretch your window width, then R might not be able to write all your labels in. Play with the window width and you'll see what I mean.


It's too bad that you had such trouble finding documentation! What were your search terms? Try typing r axis into Google, and the first link you will get is that Quick R page that I mentioned earlier. Scroll down to "Axes", and you'll get a very nice little guide on how to do it. You should probably check there first for any plotting questions, it will be faster than waiting for a SO reply.

How to POST request using RestSharp

This way works fine for me:

var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
                .AddBody(BODY);

var response = Client.Execute(request);

// Handle response errors
HandleResponseErrors(response);

if (Errors.Length == 0)
{ }
else
{ }

Hope this helps! (Although it is a bit late)

Style disabled button with CSS

Need to apply css as belows:

button:disabled,button[disabled]{
    background-color: #cccccc;
    cursor:not-allowed !important;
  }

What is the "realm" in basic authentication

According to the RFC 7235, the realm parameter is reserved for defining protection spaces (set of pages or resources where credentials are required) and it's used by the authentication schemes to indicate a scope of protection.

For more details, see the quote below (the highlights are not present in the RFC):

2.2. Protection Space (Realm)

The "realm" authentication parameter is reserved for use by authentication schemes that wish to indicate a scope of protection.

A protection space is defined by the canonical root URI (the scheme and authority components of the effective request URI) of the server being accessed, in combination with the realm value if present. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, that can have additional semantics specific to the authentication scheme. Note that a response can have multiple challenges with the same auth-scheme but with different realms. [...]


Note 1: The framework for HTTP authentication is currently defined by the RFC 7235, which updates the RFC 2617 and makes the RFC 2616 obsolete.

Note 2: The realm parameter is no longer always required on challenges.

Difference between javacore, thread dump and heap dump in Websphere

Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores

Show only two digit after decimal

Use DecimalFormat.

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

Code snippet -

double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));

Output -

5.81

Setting onSubmit in React.js

In your doSomething() function, pass in the event e and use e.preventDefault().

doSomething = function (e) {
    alert('it works!');
    e.preventDefault();
}

How can I find a file/directory that could be anywhere on linux command line?

I hope this comment will help you to find out your local & server file path using terminal

 find "$(cd ..; pwd)" -name "filename"

Or just you want to see your Current location then run

 pwd "filename"

Xcode 10 Error: Multiple commands produce

In my case, I've got my GoogleService-info.plist file multiple copied, as it's included in both my main app and a share extension project.

The solution is to exclude this file from the extension project (by unchecking it from the Target in its File Inspector side window view); as I don't like the option to switch to Legacy Build System (which is also working for me).

Can I catch multiple Java exceptions in the same catch clause?

Catch the exception that happens to be a parent class in the exception hierarchy. This is of course, bad practice. In your case, the common parent exception happens to be the Exception class, and catching any exception that is an instance of Exception, is indeed bad practice - exceptions like NullPointerException are usually programming errors and should usually be resolved by checking for null values.

Google Maps v3 - limit viewable area and zoom level

As of middle 2016, there is no official way to restrict viewable area. Most of ad-hoc solutions to restrict the bounds have a flaw though, because they don't restrict the bounds exactly to fit the map view, they only restrict it if the center of the map is out of the specified bounds. If you want to restrict the bounds to overlaying image like me, this can result in a behavior like illustrated below, where the underlaying map is visible under our image overlay:

enter image description here

To tackle this issue, I have created a library, which successfully restrict the bounds so you cannot pan out of the overlay.

However, as other existing solutions, it has a "vibrating" issue. When the user pans the map aggressively enough, after they release the left mouse button, the map still continues panning by itself, gradually slowing. I always return the map back to the bounds, but that results in kind of vibrating. This panning effect cannot be stopped with any means provided by the Js API at the moment. It seems that until google adds support for something like map.stopPanningAnimation() we won't be able to create a smooth experience.

Example using the mentioned library, the smoothest strict bounds experience I was able to get:

_x000D_
_x000D_
function initialise(){_x000D_
  _x000D_
  var myOptions = {_x000D_
     zoom: 5,_x000D_
     center: new google.maps.LatLng(0,0),_x000D_
     mapTypeId: google.maps.MapTypeId.ROADMAP,_x000D_
  };_x000D_
  var map = new google.maps.Map(document.getElementById('map'), myOptions);_x000D_
  _x000D_
  addStrictBoundsImage(map);_x000D_
}_x000D_
_x000D_
function addStrictBoundsImage(map){_x000D_
 var bounds = new google.maps.LatLngBounds(_x000D_
  new google.maps.LatLng(62.281819, -150.287132),_x000D_
  new google.maps.LatLng(62.400471, -150.005608));_x000D_
_x000D_
 var image_src = 'https://developers.google.com/maps/documentation/' +_x000D_
  'javascript/examples/full/images/talkeetna.png';_x000D_
_x000D_
 var strict_bounds_image = new StrictBoundsImage(bounds, image_src, map);_x000D_
}
_x000D_
<script type="text/javascript" src="http://www.google.com/jsapi"></script>_x000D_
      <script type="text/javascript">_x000D_
        google.load("maps", "3",{other_params:"sensor=false"});_x000D_
      </script>_x000D_
<body style="margin:0px; padding:0px;" onload="initialise()">_x000D_
  <div id="map" style="height:400px; width:500px;"></div>_x000D_
     <script  type="text/javascript"src="https://raw.githubusercontent.com/matej-pavla/StrictBoundsImage/master/StrictBoundsImage.js"></script>_x000D_
</body>
_x000D_
_x000D_
_x000D_

The library is also able to calculate the minimum zoom restriction automatically. It then restricts the zoom level using minZoom map's attribute.

Hopefully this helps someone who wants a solution which fully respect the given boundaries and doesn't want to allow panning out of them.

How to markdown nested list items in Bitbucket?

Even a single space works

...Just open this answer for edit to see it.

Nested lists, deeper levels: ---- leave here an empty row * first level A item - no space in front the bullet character * second level Aa item - 1 space is enough * third level Aaa item - 5 spaces min * second level Ab item - 4 spaces possible too * first level B item

Nested lists, deeper levels:

  • first level A item - no space in front the bullet character
    • second level Aa item - 1 space is enough
      • third level Aaa item - 5 spaces min
    • second level Ab item - 4 spaces possible too
  • first level B item

    Nested lists, deeper levels:
     ...Skip a line and indent eight spaces. (as said in the editor-help, just on this page)
    * first level A item - no space in front the bullet character
     * second level Aa item - 1 space is enough
         * third level Aaa item - 5 spaces min
        * second level Ab item - 4 spaces possible too
    * first level B item
    

Why do we use __init__ in Python classes?

To contribute my 5 cents to the thorough explanation from Amadan.

Where classes are a description "of a type" in an abstract way. Objects are their realizations: the living breathing thing. In the object-orientated world there are principal ideas you can almost call the essence of everything. They are:

  1. encapsulation (won't elaborate on this)
  2. inheritance
  3. polymorphism

Objects have one, or more characteristics (= Attributes) and behaviors (= Methods). The behavior mostly depends on the characteristics. Classes define what the behavior should accomplish in a general way, but as long as the class is not realized (instantiated) as an object it remains an abstract concept of a possibility. Let me illustrate with the help of "inheritance" and "polymorphism".

    class Human:
        gender
        nationality
        favorite_drink
        core_characteristic
        favorite_beverage
        name
        age

        def love    
        def drink
        def laugh
        def do_your_special_thing                

    class Americans(Humans)
        def drink(beverage):
            if beverage != favorite_drink: print "You call that a drink?"
            else: print "Great!" 

    class French(Humans)
        def drink(beverage, cheese):
            if beverage == favourite_drink and cheese == None: print "No cheese?" 
            elif beverage != favourite_drink and cheese == None: print "Révolution!"

    class Brazilian(Humans)
        def do_your_special_thing
            win_every_football_world_cup()

    class Germans(Humans)
        def drink(beverage):
            if favorite_drink != beverage: print "I need more beer"
            else: print "Lecker!" 

    class HighSchoolStudent(Americans):
        def __init__(self, name, age):
             self.name = name
             self.age = age

jeff = HighSchoolStudent(name, age):
hans = Germans()
ronaldo = Brazilian()
amelie = French()

for friends in [jeff, hans, ronaldo]:
    friends.laugh()
    friends.drink("cola")
    friends.do_your_special_thing()

print amelie.love(jeff)
>>> True
print ronaldo.love(hans)
>>> False

Some characteristics define human beings. But every nationality differs somewhat. So "national-types" are kinda Humans with extras. "Americans" are a type of "Humans " and inherit some abstract characteristics and behavior from the human type (base-class) : that's inheritance. So all Humans can laugh and drink, therefore all child-classes can also! Inheritance (2).

But because they are all of the same kind (Type/base-class : Humans) you can exchange them sometimes: see the for-loop at the end. But they will expose an individual characteristic, and thats Polymorphism (3).

So each human has a favorite_drink, but every nationality tend towards a special kind of drink. If you subclass a nationality from the type of Humans you can overwrite the inherited behavior as I have demonstrated above with the drink() Method. But that's still at the class-level and because of this it's still a generalization.

hans = German(favorite_drink = "Cola")

instantiates the class German and I "changed" a default characteristic at the beginning. (But if you call hans.drink('Milk') he would still print "I need more beer" - an obvious bug ... or maybe that's what i would call a feature if i would be a Employee of a bigger Company. ;-)! )

The characteristic of a type e.g. Germans (hans) are usually defined through the constructor (in python : __init__) at the moment of the instantiation. This is the point where you define a class to become an object. You could say breath life into an abstract concept (class) by filling it with individual characteristics and becoming an object.

But because every object is an instance of a class they share all some basic characteristic-types and some behavior. This is a major advantage of the object-orientated concept.

To protect the characteristics of each object you encapsulate them - means you try to couple behavior and characteristic and make it hard to manipulate it from outside the object. That's Encapsulation (1)

Asp.net Validation of viewstate MAC failed

I had this same issue and it was due to a Gridview (generated from a vb code) on the page which had sorting enabled. Disabling Sort fixed my issue. I do not have this problem with the gridviews created using a SQLdatasource.

Building a fat jar using maven

Maybe you want maven-shade-plugin, bundle dependencies, minimize unused code and hide external dependencies to avoid conflicts.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.1.1</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <minimizeJar>true</minimizeJar>
                        <createDependencyReducedPom>true</createDependencyReducedPom>
                        <dependencyReducedPomLocation>
                            ${java.io.tmpdir}/dependency-reduced-pom.xml
                        </dependencyReducedPomLocation>
                        <relocations>
                            <relocation>
                                <pattern>com.acme.coyote</pattern>
                                <shadedPattern>hidden.coyote</shadedPattern>
                            </relocation>
                        </relocations>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

References:

How to pretty print XML from Java?

Just to note that top rated answer requires the use of xerces.

If you don't want to add this external dependency then you can simply use the standard jdk libraries (which actually are built using xerces internally).

N.B. There was a bug with jdk version 1.5 see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446 but it is resolved now.,

(Note if an error occurs this will return the original text)

package com.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

public class XmlTest {
    public static void main(String[] args) {
        XmlTest t = new XmlTest();
        System.out.println(t.formatXml("<a><b><c/><d>text D</d><e value='0'/></b></a>"));
    }

    public String formatXml(String xml){
        try{
            Transformer serializer= SAXTransformerFactory.newInstance().newTransformer();
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            //serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            //serializer.setOutputProperty("{http://xml.customer.org/xslt}indent-amount", "2");
            Source xmlSource=new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
            StreamResult res =  new StreamResult(new ByteArrayOutputStream());            
            serializer.transform(xmlSource, res);
            return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
        }catch(Exception e){
            //TODO log error
            return xml;
        }
    }

}

What is the Record type in typescript?

  1. Can someone give a simple definition of what Record is?

A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

and it would treat them as excess properties which are sometimes rejected:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

and sometimes accepted:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

    type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
    

    Is it exactly the same as this?:

    type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
    

Yes!

Hope that helps. Good luck!

How to get client's IP address using JavaScript?

Include this code in your page : <script type="text/javascript" src="http://l2.io/ip.js"></script>

more doc here

Using OpenSSL what does "unable to write 'random state'" mean?

You should set the $RANDFILE environment variable and/or create $HOME/.rnd file. (OpenSSL FAQ). (Of course, you should have rights to that file. Others answers here are about that. But first you should have the file and a reference to it.)

Up to version 0.9.6 OpenSSL wrote the seeding file in the current directory in the file ".rnd". At version 0.9.6a you have no default seeding file. OpenSSL 0.9.6b and later will behave similarly to 0.9.6a, but will use a default of "C:\" for HOME on Windows systems if the environment variable has not been set.

If the default seeding file does not exist or is too short, the "PRNG not seeded" error message may occur.

The $RANDFILE environment variable and $HOME/.rnd are only used by the OpenSSL command line tools. Applications using the OpenSSL library provide their own configuration options to specify the entropy source, please check out the documentation coming the with application.

How to find out the location of currently used MySQL configuration file in linux

You should find them by default in a folder like /etc/my.cnf, maybe also depends on versions. From MySQL Configuration File:

Interestingly, the scope of this file can be set according to its location. The settings will be considered global to all MySQL servers if stored in /etc/my.cnf. It will be global to a specific server if located in the directory where the MySQL databases are stored (/usr/local/mysql/data for a binary installation, or /usr/local/var for a source installation). Finally, its scope could be limited to a specific user if located in the home directory of the MySQL user (~/.my.cnf). Keep in mind that even if MySQL does locate a my.cnf file in /etc/my.cnf (global to all MySQL servers on that machine), it will continue its search for a server-specific file, and then a user-specific file. You can think of the final configuration settings as being the result of the /etc/my.cnf, mysql-data-dir/my.cnf, and ~/.my.cnf files.

There are a few switches to package managers to list specific files.

RPM Sytems:

There are switches to rpm command, -q for query, and -c or --configfiles to list config files. There is also -l or --list

The --configfiles one didn't quiet work for me, but --list did list a few .cnf files held by mysql-server

rpm -q --list mysql-server

DEB Systems:

Also with limited success: dpkg --listfiles mysql-server

How does Google calculate my location on a desktop?

It is possible get your approximate locate based on your IP address (wireless or fixed).

See for example hostip.info or maxmind which basically provide a mapping from IP address to geographical coordinates. The probably use many kinds of heuristics and datasources. This kind of system has probably enough accuracy to put you in right major city, in most cases.

Google probably uses somewhat similar approach in addition to WiFi tricks.

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

I had this issue but it was fixed easily by going to the Internet Information Services (IIS) Manager, double clicking Directory Browsing and clicking Enable.

In my case, I could access files directly but could not access folders.

ReactJS: setTimeout() not working?

setTimeout(() => {
  this.setState({ position: 1 });
}, 3000);

The above would also work because the ES6 arrow function does not change the context of this.

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

System images are pre-installed Android operating systems, and are only used by emulators. If you use your real Android device for debugging, you no longer need them, so you can remove them all.

The cleanest way to remove them is using SDK Manager. Open up SDK Manager and uncheck those system images and then apply.

Also feel free to remove other components (e.g. old SDK levels) that are of no use.

How to evaluate a boolean variable in an if block in bash?

Note that the if $myVar; then ... ;fi construct has a security problem you might want to avoid with

case $myvar in
  (true)    echo "is true";;
  (false)   echo "is false";;
  (rm -rf*) echo "I just dodged a bullet";;
esac

You might also want to rethink why if [ "$myvar" = "true" ] appears awkward to you. It's a shell string comparison that beats possibly forking a process just to obtain an exit status. A fork is a heavy and expensive operation, while a string comparison is dead cheap. Think a few CPU cycles versus several thousand. My case solution is also handled without forks.

Remove quotes from String in Python

You can replace "quote" characters with an empty string, like this:

>>> a = '"sajdkasjdsak" "asdasdasds"' 
>>> a
'"sajdkasjdsak" "asdasdasds"'
>>> a = a.replace('"', '')
>>> a
'sajdkasjdsak asdasdasds'

In your case, you can do the same for out variable.

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

You're trying to access a JSON, not JSONP.

Notice the difference between your source:

https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59&callback=?

And actual JSONP (a wrapping function):

http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=processJSON&tags=monkey&tagmode=any&format=json

Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.

How can I color Python logging output?

I already knew about the color escapes, I used them in my bash prompt a while ago. Thanks anyway.
What I wanted was to integrate it with the logging module, which I eventually did after a couple of tries and errors.
Here is what I end up with:

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)

#The background is set with 40 plus the number of the color, and the foreground with 30

#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"

def formatter_message(message, use_color = True):
    if use_color:
        message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
    else:
        message = message.replace("$RESET", "").replace("$BOLD", "")
    return message

COLORS = {
    'WARNING': YELLOW,
    'INFO': WHITE,
    'DEBUG': BLUE,
    'CRITICAL': YELLOW,
    'ERROR': RED
}

class ColoredFormatter(logging.Formatter):
    def __init__(self, msg, use_color = True):
        logging.Formatter.__init__(self, msg)
        self.use_color = use_color

    def format(self, record):
        levelname = record.levelname
        if self.use_color and levelname in COLORS:
            levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ
            record.levelname = levelname_color
        return logging.Formatter.format(self, record)

And to use it, create your own Logger:

# Custom logger class with multiple destinations
class ColoredLogger(logging.Logger):
    FORMAT = "[$BOLD%(name)-20s$RESET][%(levelname)-18s]  %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)"
    COLOR_FORMAT = formatter_message(FORMAT, True)
    def __init__(self, name):
        logging.Logger.__init__(self, name, logging.DEBUG)                

        color_formatter = ColoredFormatter(self.COLOR_FORMAT)

        console = logging.StreamHandler()
        console.setFormatter(color_formatter)

        self.addHandler(console)
        return


logging.setLoggerClass(ColoredLogger)

Just in case anyone else needs it.

Be careful if you're using more than one logger or handler: ColoredFormatter is changing the record object, which is passed further to other handlers or propagated to other loggers. If you have configured file loggers etc. you probably don't want to have the colors in the log files. To avoid that, it's probably best to simply create a copy of record with copy.copy() before manipulating the levelname attribute, or to reset the levelname to the previous value, before returning the formatted string (credit to Michael in the comments).

Hexadecimal string to byte array in C

Here is a solution to deal with files, which may be used more frequently...

int convert(char *infile, char *outfile) {

char *source = NULL;
FILE *fp = fopen(infile, "r");
long bufsize;
if (fp != NULL) {
    /* Go to the end of the file. */
    if (fseek(fp, 0L, SEEK_END) == 0) {
        /* Get the size of the file. */
        bufsize = ftell(fp);
        if (bufsize == -1) { /* Error */ }

        /* Allocate our buffer to that size. */
        source = malloc(sizeof(char) * (bufsize + 1));

        /* Go back to the start of the file. */
        if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ }

        /* Read the entire file into memory. */
        size_t newLen = fread(source, sizeof(char), bufsize, fp);
        if ( ferror( fp ) != 0 ) {
            fputs("Error reading file", stderr);
        } else {
            source[newLen++] = '\0'; /* Just to be safe. */
        }
    }
    fclose(fp);
}
     
int sourceLen = bufsize - 1;
int destLen = sourceLen/2;
unsigned char* dest = malloc(destLen);
short i;  
unsigned char highByte, lowByte;  
      
for (i = 0; i < sourceLen; i += 2)  
{  
        highByte = toupper(source[i]);  
        lowByte  = toupper(source[i + 1]);  
  
        if (highByte > 0x39)  
            highByte -= 0x37;  
        else  
            highByte -= 0x30;  
  
        if (lowByte > 0x39)  
            lowByte -= 0x37;  
        else  
            lowByte -= 0x30;  
  
        dest[i / 2] = (highByte << 4) | lowByte;  
}  
        

FILE *fop = fopen(outfile, "w");
if (fop == NULL) return 1;
fwrite(dest, 1, destLen, fop);
fclose(fop);
free(source);
free(dest);
return 0;
}  

Calculate number of hours between 2 dates in PHP

Unfortunately the solution provided by FaileN doesn't work as stated by Walter Tross.. days may not be 24 hours!

I like to use the PHP Objects where possible and for a bit more flexibility I have come up with the following function:

/**
 * @param DateTimeInterface $a
 * @param DateTimeInterface $b
 * @param bool              $absolute Should the interval be forced to be positive?
 * @param string            $cap The greatest time unit to allow
 *
 * @return DateInterval The difference as a time only interval
 */
function time_diff(DateTimeInterface $a, DateTimeInterface $b, $absolute=false, $cap='H'){

  // Get unix timestamps, note getTimeStamp() is limited
  $b_raw = intval($b->format("U"));
  $a_raw = intval($a->format("U"));

  // Initial Interval properties
  $h = 0;
  $m = 0;
  $invert = 0;

  // Is interval negative?
  if(!$absolute && $b_raw<$a_raw){
    $invert = 1;
  }

  // Working diff, reduced as larger time units are calculated
  $working = abs($b_raw-$a_raw);

  // If capped at hours, calc and remove hours, cap at minutes
  if($cap == 'H') {
    $h = intval($working/3600);
    $working -= $h * 3600;
    $cap = 'M';
  }

  // If capped at minutes, calc and remove minutes
  if($cap == 'M') {
    $m = intval($working/60);
    $working -= $m * 60;
  }

  // Seconds remain
  $s = $working;

  // Build interval and invert if necessary
  $interval = new DateInterval('PT'.$h.'H'.$m.'M'.$s.'S');
  $interval->invert=$invert;

  return $interval;
}

This like date_diff() creates a DateTimeInterval, but with the highest unit as hours rather than years.. it can be formatted as usual.

$interval = time_diff($date_a, $date_b);
echo $interval->format('%r%H'); // For hours (with sign)

N.B. I have used format('U') instead of getTimestamp() because of the comment in the manual. Also note that 64-bit is required for post-epoch and pre-negative-epoch dates!

Opening PDF String in new window with javascript

Based off other old answers:

escape() function is now deprecated,

Use encodeURI() or encodeURIComponent() instead.

Example that worked in my situation:

window.open("data:application/pdf," + encodeURI(pdfString)); 

Happy Coding!

Finding the Eclipse Version Number

There is a system property eclipse.buildId (for example, for Eclipse Luna, I have 4.4.1.M20140925-0400 as a value there).

I'm not sure in which version of Eclipse did this property become available.

Also, dive right in and explore all the available system properties -- there is quite a bit of information available under eclipse.*, os.* osgi.* and org.osgi.* namespaces.


UPDATE! After experimenting with different Eclipse versions, it seems that eclipse.buildId system property is not the way to go. For example, on Eclipse Luna 4.4.0, it gives the result of 4.4.2.M20150204-1700 which is obviously incorrect.

I suspect eclipse.buildId system property is set to the version of org.eclipse.platform plugin. Unfortunately, this does not (always) give the correct result. However, good news is that I have a solution with working code sample which I will outline in a separate answer.

What is the difference between SAX and DOM?

Here in simpler words:

DOM

  • Tree model parser (Object based) (Tree of nodes).

  • DOM loads the file into the memory and then parse- the file.

  • Has memory constraints since it loads the whole XML file before parsing.

  • DOM is read and write (can insert or delete nodes).

  • If the XML content is small, then prefer DOM parser.

  • Backward and forward search is possible for searching the tags and evaluation of the information inside the tags. So this gives the ease of navigation.

  • Slower at run time.

SAX

  • Event based parser (Sequence of events).

  • SAX parses the file as it reads it, i.e. parses node by node.

  • No memory constraints as it does not store the XML content in the memory.

  • SAX is read only i.e. can’t insert or delete the node.

  • Use SAX parser when memory content is large.

  • SAX reads the XML file from top to bottom and backward navigation is not possible.

  • Faster at run time.

Intellij JAVA_HOME variable

The problem is your "Project SDK" is none! Add a "Project SDK" by clicking "New ..." and choose the path of JDK. And then it should be OK.

Transpose a range in VBA

Something like this should do it for you.

Sub CombineColumns1()
    Dim xRng As Range
    Dim i As Long, j As Integer
    Dim xNextRow As Long
    Dim xTxt As String
    On Error Resume Next
    With ActiveSheet
        xTxt = .RangeSelection.Address
        Set xRng = Application.InputBox("please select the data range", "Kutools for Excel", xTxt, , , , , 8)
        If xRng Is Nothing Then Exit Sub
        j = xRng.Columns(1).Column
        For i = 4 To xRng.Columns.Count Step 3
            'Need to recalculate the last row, as some of the final columns may not have data in all rows
            xNextRow = .Cells(.Rows.Count, j).End(xlUp).Row + 1

            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Copy .Cells(xNextRow, j)
            .Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Clear
        Next
    End With
End Sub

You could do this too.

Sub TransposeFormulas()
    Dim vFormulas As Variant
    Dim oSel As Range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Please select a range of cells first.", _
                vbOKOnly + vbInformation, "Transpose formulas"
        Exit Sub
    End If
    Set oSel = Selection
    vFormulas = oSel.Formula
    vFormulas = Application.WorksheetFunction.Transpose(vFormulas)
    oSel.Offset(oSel.Rows.Count + 2).Resize(oSel.Columns.Count, oSel.Rows.Count).Formula = vFormulas
End Sub

See this for more info.

http://bettersolutions.com/vba/arrays/transposing.htm

.includes() not working in Internet Explorer

It works for me:

function stringIncludes(a, b) {
      return a.indexOf(b) !== -1;
}

How do I set/unset a cookie with jQuery?

I think Fresher gave us nice way, but there is a mistake:

    <script type="text/javascript">
        function setCookie(key, value) {
            var expires = new Date();
            expires.setTime(expires.getTime() + (value * 24 * 60 * 60 * 1000));
            document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }
   </script>

You should add "value" near getTime(); otherwise the cookie will expire immediately :)

How can I store the result of a system command in a Perl variable?

From Perlfaq8:

You're confusing the purpose of system() and backticks (``). system() runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT.

$exit_status   = system("mail-users");
$output_string = `ls`;

There are many ways to execute external commands from Perl. The most commons with their meanings are:

  • system() : you want to execute a command and don't want to capture its output
  • exec: you don't want to return to the calling perl script
  • backticks : you want to capture the output of the command
  • open: you want to pipe the command (as input or output) to your script

Also see How can I capture STDERR from an external command?

Finding blocking/locking queries in MS SQL (mssql)

Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.

How to pass multiple parameters from ajax to mvc controller?

  var data = JSON.stringify
            ({
            'StrContactDetails': Details,
            'IsPrimary': true
            })

How do I disable the resizable property of a textarea?

I have created a small demo to show how resize properties work. I hope it will help you and others as well.

_x000D_
_x000D_
.resizeable {_x000D_
  resize: both;_x000D_
}_x000D_
_x000D_
.noResizeable {_x000D_
  resize: none;_x000D_
}_x000D_
_x000D_
.resizeable_V {_x000D_
  resize: vertical;_x000D_
}_x000D_
_x000D_
.resizeable_H {_x000D_
  resize: horizontal;_x000D_
}
_x000D_
<textarea class="resizeable" rows="5" cols="20" name="resizeable" title="This is Resizable.">_x000D_
This is Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>_x000D_
_x000D_
<textarea class="noResizeable" rows="5" title="This will not Resizable. " cols="20" name="resizeable">_x000D_
This will not Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>_x000D_
_x000D_
<textarea class="resizeable_V" title="This is Vertically Resizable." rows="5" cols="20" name="resizeable">_x000D_
This is Vertically Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>_x000D_
_x000D_
<textarea class="resizeable_H" title="This is Horizontally Resizable." rows="5" cols="20" name="resizeable">_x000D_
This is Horizontally Resizable. Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book._x000D_
</textarea>
_x000D_
_x000D_
_x000D_

What generates the "text file busy" message in Unix?

If you are running the .sh from a ssh connection with a tool like MobaXTerm, and if said tool has an autosave utility to edit remote file from local machine, that will lock the file.

Closing and reopening the SSH session solves it.

How to use the DropDownList's SelectedIndexChanged event

You should add AutoPostBack="true" to DropDownList1

                <asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
                    DataSourceID="Sql_fur_model_manu"    
                    DataTextField="manufacturer" DataValueField="manufacturer" 
                    onselectedindexchanged="ddmanu_SelectedIndexChanged">
                </asp:DropDownList>

How to add files/folders to .gitignore in IntelliJ IDEA?

Intellij had .ignore plugin to support this. https://plugins.jetbrains.com/plugin/7495?pr=idea

After you install the plugin, you right click on the project and select new -> .ignore file -> .gitignore file (Git) enter image description here

Then, select the type of project you have to generate a template and click Generate. enter image description here

C++ String Declaring

In C++ you can declare a string like this:

#include <string>

using namespace std;

int main()
{
    string str1("argue2000"); //define a string and Initialize str1 with "argue2000"    
    string str2 = "argue2000"; // define a string and assign str2 with "argue2000"
    string str3;  //just declare a string, it has no value
    return 1;
}

JavaScript: filter() for Objects

In these cases I use the jquery $.map, which can handle objects. As mentioned on other answers, it's not a good practice to change native prototypes (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#Bad_practice_Extension_of_native_prototypes)

Below is an example of filtering just by checking some property of your object. It returns the own object if your condition is true or returns undefined if not. The undefined property will make that record disappear from your object list;

$.map(yourObject, (el, index)=>{
    return el.yourProperty ? el : undefined;
});

How to fix IndexError: invalid index to scalar variable

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

How can I run MongoDB as a Windows service?

This is what worked for me:

sc.exe create MongoDB binPath= "d:\MongoDB\bin\mongod.exe --service --config=d:\MongoDB\bin\mongod.config" displayname= "MongoDB 2.6 Standard" start= "auto"

escaping the binPath was failing for me as described in the Mongo documentation

Failed:

sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB 2.6 Standard\bin\mongod.exe\" --service --config=\"C:\Program Files\MongoDB 2.6 Standard\mongod.cfg\"" DisplayName= "MongoDB 2.6 Standard" start= "auto"

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

Function of Project > Clean in Eclipse

I also faced the same issue with Eclipse when I ran the clean build with Maven, but there is a simple solution for this issue. We just need to run Maven update and then build or direct run the application. I hope it will solve the problem.

How to fix 'Notice: Undefined index:' in PHP form action

Please try this

error_reporting = E_ALL & ~E_NOTICE

in php.ini

How do you find out the caller function in JavaScript?

I wanted to add my fiddle here for this:

http://jsfiddle.net/bladnman/EhUm3/

I tested this is chrome, safari and IE (10 and 8). Works fine. There is only 1 function that matters, so if you get scared by the big fiddle, read below.

Note: There is a fair amount of my own "boilerplate" in this fiddle. You can remove all of that and use split's if you like. It's just an ultra-safe" set of functions I've come to rely on.

There is also a "JSFiddle" template in there that I use for many fiddles to simply quick fiddling.

collapse cell in jupyter notebook

As others have mentioned, you can do this via nbextensions. I wanted to give the brief explanation of what I did, which was quick and easy:

To enable collabsible headings: In your terminal, enable/install Jupyter Notebook Extensions by first entering:

pip install jupyter_contrib_nbextensions

Then, enter:

jupyter contrib nbextension install

Re-open Jupyter Notebook. Go to "Edit" tab, and select "nbextensions config". Un-check box directly under title "Configurable nbextensions", then select "collapsible headings".

Moment JS - check if a date is today or in the future

function isTodayOrFuture(date){
  date = stripTime(date);
  return date.diff(stripTime(moment.now())) >= 0;
}

function stripTime(date){
  date = moment(date);
  date.hours(0);
  date.minutes(0);
  date.seconds(0);
  date.milliseconds(0);
  return date;
}

And then just use it line this :

isTodayOrFuture(YOUR_TEST_DATE_HERE)

How can I send an inner <div> to the bottom of its parent <div>?

Make the outer div position="relative" and the inner div position="absolute" and set it's bottom="0".

vb.net get file names in directory?

System.IO.Directory.GetFiles() 

could help

How do I use a file grep comparison inside a bash if/else statement?

if takes a command and checks its return value. [ is just a command.

if grep -q ...
then
  ....
else
  ....
fi

What are the uses of "using" in C#?

The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts

using (MyResource myRes = new MyResource())
{
    myRes.DoSomething();
}

to

{ // Limits scope of myRes
    MyResource myRes= new MyResource();
    try
    {
        myRes.DoSomething();
    }
    finally
    {
        // Check for a null resource.
        if (myRes != null)
            // Call the object's Dispose method.
            ((IDisposable)myRes).Dispose();
    }
}

C# 8 introduces a new syntax, named "using declarations":

A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.

So the equivalent code of above would be:

using var myRes = new MyResource();
myRes.DoSomething();

And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.

Can I check if Bootstrap Modal Shown / Hidden?

In offical way:

> ($("element").data('bs.modal') || {})._isShown    // Bootstrap 4
> ($("element").data('bs.modal') || {}).isShown     // Bootstrap <= 3

{} is used to avoid the case that modal is not opened yet (it return undefined). You can also assign it equal {isShown: false} to keep it's more make sense.

svn: E155004: ..(path of resource).. is already locked

  1. Downlaod and copy sqlite.exe to .svn's parent directory
  2. Open shell in this directory
  3. Query to find locks in corresponding tables => in wc_lock* table (the table name is something like this)
  4. Delete the locked items in above table by sqlite query

just this steps helped me to resolve:

svn: E155004: Working copy 'resourceAddress' locked

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

How to view method information in Android Studio?

I'm using Visual Studio too much and I want to see params when I click on Ctrl+Space that's why I'm using Visual Studio keys. To change keymap to VS keymap: enter image description here enter image description here

Want custom title / image / description in facebook share link from a flash app

I have a Joomla Module that displays stuff... and I want to be able to share that stuff on facebook and not the Page's Title Meta Description... so my workaround is to have a secret .php file on the server that gets executed when it detects the FB's

$_SERVER['HTTP_USER_AGENT']

if($_SERVER['HTTP_USER_AGENT'] != 'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)') {
    echo 'Direct Access';
} else {
    echo 'FB Accessed';
}

and pass variables with the URL that formats that particular page with the title and meta desciption of the item I want to share from my joomla module...

a name="fb_share" share_url="MYURL/sharer.php?title=TITLE&desc=DESC"

hope this helps...

How to access the GET parameters after "?" in Express?

So, after checking out the express reference, I found that req.query.color would return me the value I'm looking for.

req.params refers to items with a ':' in the URL and req.query refers to items associated with the '?'

Example:

GET /something?color1=red&color2=blue

Then in express, the handler:

app.get('/something', (req, res) => {
    req.query.color1 === 'red'  // true
    req.query.color2 === 'blue' // true
})

Entity Framework 5 Updating a Record

I really like the accepted answer. I believe there is yet another way to approach this as well. Let's say you have a very short list of properties that you wouldn't want to ever include in a View, so when updating the entity, those would be omitted. Let's say that those two fields are Password and SSN.

db.Users.Attach(updatedUser);

var entry = db.Entry(updatedUser);
entry.State = EntityState.Modified;

entry.Property(e => e.Password).IsModified = false;
entry.Property(e => e.SSN).IsModified = false;   

db.SaveChanges();   

This example allows you to essentially leave your business logic alone after adding a new field to your Users table and to your View.

Update multiple tables in SQL Server using INNER JOIN

You can update with a join if you only affect one table like this:

UPDATE table1 
SET table1.name = table2.name 
FROM table1, table2 
WHERE table1.id = table2.id 
AND table2.foobar ='stuff'

But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.

However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.

SQL JOINS

But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.

Laravel password validation rule

A Custom Laravel Validation Rule will allow developers to provide a custom message with each use case for a better UX experience.

php artisan make:rule IsValidPassword

namespace App\Rules;

use Illuminate\Support\Str;
use Illuminate\Contracts\Validation\Rule;

class isValidPassword implements Rule
{
    /**
     * Determine if the Length Validation Rule passes.
     *
     * @var boolean
     */
    public $lengthPasses = true;

    /**
     * Determine if the Uppercase Validation Rule passes.
     *
     * @var boolean
     */
    public $uppercasePasses = true;

    /**
     * Determine if the Numeric Validation Rule passes.
     *
     * @var boolean
     */
    public $numericPasses = true;

    /**
     * Determine if the Special Character Validation Rule passes.
     *
     * @var boolean
     */
    public $specialCharacterPasses = true;

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->lengthPasses = (Str::length($value) >= 10);
        $this->uppercasePasses = (Str::lower($value) !== $value);
        $this->numericPasses = ((bool) preg_match('/[0-9]/', $value));
        $this->specialCharacterPasses = ((bool) preg_match('/[^A-Za-z0-9]/', $value));

        return ($this->lengthPasses && $this->uppercasePasses && $this->numericPasses && $this->specialCharacterPasses);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        switch (true) {
            case ! $this->uppercasePasses
                && $this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character.';

            case ! $this->numericPasses
                && $this->uppercasePasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one number.';

            case ! $this->specialCharacterPasses
                && $this->uppercasePasses
                && $this->numericPasses:
                return 'The :attribute must be at least 10 characters and contain at least one special character.';

            case ! $this->uppercasePasses
                && ! $this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one number.';

            case ! $this->uppercasePasses
                && ! $this->specialCharacterPasses
                && $this->numericPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one special character.';

            case ! $this->uppercasePasses
                && ! $this->numericPasses
                && ! $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character, one number, and one special character.';

            default:
                return 'The :attribute must be at least 10 characters.';
        }
    }
}

Then on your request validation:

$request->validate([
    'email'    => 'required|string|email:filter',
    'password' => [
        'required',
        'confirmed',
        'string',
        new isValidPassword(),
    ],
]);

How can I add some small utility functions to my AngularJS application?

The easiest way to add utility functions is to leave them at the global level:

function myUtilityFunction(x) { return "do something with "+x; }

Then, the simplest way to add a utility function (to a controller) is to assign it to $scope, like this:

$scope.doSomething = myUtilityFunction;

Then you can call it like this:

{{ doSomething(x) }}

or like this:

ng-click="doSomething(x)"

EDIT:

The original question is if the best way to add a utility function is through a service. I say no, if the function is simple enough (like the isNotString() example provided by the OP).

The benefit of writing a service is to replace it with another (via injection) for the purpose of testing. Taken to an extreme, do you need to inject every single utility function into your controller?

The documentation says to simply define behavior in the controller (like $scope.double): http://docs.angularjs.org/guide/controller

How to copy Docker images from one host to another without using a repository

For a flattened export of a container's filesystem, use;

docker export CONTAINER_ID > my_container.tar

Use cat my_container.tar | docker import - to import said image.

Parse string to date with moment.js

No need for moment.js to parse the input since its format is the standard one :

var date = new Date('2014-02-27T10:00:00');
var formatted = moment(date).format('D MMMM YYYY');

http://es5.github.io/#x15.9.1.15

dotnet ef not found in .NET Core 3

if your using snap package dotnet-sdk on linux this can resolve by updating your ~.bashrc / etc. as follows:

#!/bin/bash
export DOTNET_ROOT=/snap/dotnet-sdk/current
export MSBuildSDKsPath=$DOTNET_ROOT/sdk/$(${DOTNET_ROOT}/dotnet --version)/Sdks
export PATH="${PATH}:${DOTNET_ROOT}"
export PATH="$PATH:$HOME/.dotnet/tools"

How to use not contains() in xpath?

You can use not(expression) function

not() is a function in xpath (as opposed to an operator)

Example:

//a[not(contains(@id, 'xx'))]

OR

expression != true()

What is the difference between WCF and WPF?

WCF = Windows COMMUNICATION Foundation

WPF = Windows PRESENTATION Foundation.

WCF deals with communication (in simple terms - sending and receiving data as well as formatting and serialization involved), WPF deals with presentation (UI)

IntelliJ Organize Imports

Under "Settings -> Editor -> General -> Auto Import" there are several options regarding automatic imports. Only unambiguous imports may be added automatically; this is one of the options.

What is the difference between a Docker image and a container?

An instance of an image is called a container. You have an image, which is a set of layers as you describe. If you start this image, you have a running container of this image. You can have many running containers of the same image.

You can see all your images with docker images whereas you can see your running containers with docker ps (and you can see all containers with docker ps -a).

So a running instance of an image is a container.

Google Geocoding API - REQUEST_DENIED

If none of given solutions fixed the error, the issue probably about Google Cloud Billing settings. You must enable Billing on the Google Cloud Project at billing/enable.

Learn more

{
    "error_message" : "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started",
    "results" : [],
    "status" : "REQUEST_DENIED"
}

How to sort in-place using the merge sort algorithm?

I just tried in place merge algorithm for merge sort in JAVA by using the insertion sort algorithm, using following steps.
1) Two sorted arrays are available.
2) Compare the first values of each array; and place the smallest value into the first array.
3) Place the larger value into the second array by using insertion sort (traverse from left to right).
4) Then again compare the second value of first array and first value of second array, and do the same. But when swapping happens there is some clue on skip comparing the further items, but just swapping required.

I have made some optimization here; to keep lesser comparisons in insertion sort.
The only drawback i found with this solutions is it needs larger swapping of array elements in the second array.

e.g)

First___Array : 3, 7, 8, 9

Second Array : 1, 2, 4, 5

Then 7, 8, 9 makes the second array to swap(move left by one) all its elements by one each time to place himself in the last.

So the assumption here is swapping items is negligible compare to comparing of two items.

https://github.com/skanagavelu/algorithams/blob/master/src/sorting/MergeSort.java

package sorting;

import java.util.Arrays;

public class MergeSort {
    public static void main(String[] args) {
    int[] array = { 5, 6, 10, 3, 9, 2, 12, 1, 8, 7 };
    mergeSort(array, 0, array.length -1);
    System.out.println(Arrays.toString(array));

    int[] array1 = {4, 7, 2};
    System.out.println(Arrays.toString(array1));
    mergeSort(array1, 0, array1.length -1);
    System.out.println(Arrays.toString(array1));
    System.out.println("\n\n");

    int[] array2 = {4, 7, 9};
    System.out.println(Arrays.toString(array2));
    mergeSort(array2, 0, array2.length -1);
    System.out.println(Arrays.toString(array2));
    System.out.println("\n\n");

    int[] array3 = {4, 7, 5};
    System.out.println(Arrays.toString(array3));
    mergeSort(array3, 0, array3.length -1);
    System.out.println(Arrays.toString(array3));
    System.out.println("\n\n");

    int[] array4 = {7, 4, 2};
    System.out.println(Arrays.toString(array4));
    mergeSort(array4, 0, array4.length -1);
    System.out.println(Arrays.toString(array4));
    System.out.println("\n\n");

    int[] array5 = {7, 4, 9};
    System.out.println(Arrays.toString(array5));
    mergeSort(array5, 0, array5.length -1);
    System.out.println(Arrays.toString(array5));
    System.out.println("\n\n");

    int[] array6 = {7, 4, 5};
    System.out.println(Arrays.toString(array6));
    mergeSort(array6, 0, array6.length -1);
    System.out.println(Arrays.toString(array6));
    System.out.println("\n\n");

    //Handling array of size two
    int[] array7 = {7, 4};
    System.out.println(Arrays.toString(array7));
    mergeSort(array7, 0, array7.length -1);
    System.out.println(Arrays.toString(array7));
    System.out.println("\n\n");

    int input1[] = {1};
    int input2[] = {4,2};
    int input3[] = {6,2,9};
    int input4[] = {6,-1,10,4,11,14,19,12,18};
    System.out.println(Arrays.toString(input1));
    mergeSort(input1, 0, input1.length-1);
    System.out.println(Arrays.toString(input1));
    System.out.println("\n\n");

    System.out.println(Arrays.toString(input2));
    mergeSort(input2, 0, input2.length-1);
    System.out.println(Arrays.toString(input2));
    System.out.println("\n\n");

    System.out.println(Arrays.toString(input3));
    mergeSort(input3, 0, input3.length-1);
    System.out.println(Arrays.toString(input3));
    System.out.println("\n\n");

    System.out.println(Arrays.toString(input4));
    mergeSort(input4, 0, input4.length-1);
    System.out.println(Arrays.toString(input4));
    System.out.println("\n\n");
}

private static void mergeSort(int[] array, int p, int r) {
    //Both below mid finding is fine.
    int mid = (r - p)/2 + p;
    int mid1 = (r + p)/2;
    if(mid != mid1) {
        System.out.println(" Mid is mismatching:" + mid + "/" + mid1+ "  for p:"+p+"  r:"+r);
    }

    if(p < r) {
        mergeSort(array, p, mid);
        mergeSort(array, mid+1, r);
//      merge(array, p, mid, r);
        inPlaceMerge(array, p, mid, r);
        }
    }

//Regular merge
private static void merge(int[] array, int p, int mid, int r) {
    int lengthOfLeftArray = mid - p + 1; // This is important to add +1.
    int lengthOfRightArray = r - mid;

    int[] left = new int[lengthOfLeftArray];
    int[] right = new int[lengthOfRightArray];

    for(int i = p, j = 0; i <= mid; ){
        left[j++] = array[i++];
    }

    for(int i = mid + 1, j = 0; i <= r; ){
        right[j++] = array[i++];
    }

    int i = 0, j = 0;
    for(; i < left.length && j < right.length; ) {
        if(left[i] < right[j]){
            array[p++] = left[i++];
        } else {
            array[p++] = right[j++];
        }
    }
    while(j < right.length){
        array[p++] = right[j++];
    } 
    while(i < left.length){
        array[p++] = left[i++];
    }
}

//InPlaceMerge no extra array
private static void inPlaceMerge(int[] array, int p, int mid, int r) {
    int secondArrayStart = mid+1;
    int prevPlaced = mid+1;
    int q = mid+1;
    while(p < mid+1 && q <= r){
        boolean swapped = false;
        if(array[p] > array[q]) {
            swap(array, p, q);
            swapped = true;
        }   
        if(q != secondArrayStart && array[p] > array[secondArrayStart]) {
            swap(array, p, secondArrayStart);
            swapped = true;
        }
        //Check swapped value is in right place of second sorted array
        if(swapped && secondArrayStart+1 <= r && array[secondArrayStart+1] < array[secondArrayStart]) {
            prevPlaced = placeInOrder(array, secondArrayStart, prevPlaced);
        }
        p++;
        if(q < r) {     //q+1 <= r) {
            q++;
        }
    }
}

private static int placeInOrder(int[] array, int secondArrayStart, int prevPlaced) {
    int i = secondArrayStart;
    for(; i < array.length; i++) {
        //Simply swap till the prevPlaced position
        if(secondArrayStart < prevPlaced) {
            swap(array, secondArrayStart, secondArrayStart+1);
            secondArrayStart++;
            continue;
        }
        if(array[i] < array[secondArrayStart]) {
            swap(array, i, secondArrayStart);
            secondArrayStart++;
        } else if(i != secondArrayStart && array[i] > array[secondArrayStart]){
            break;
        }
    }
    return secondArrayStart;
}

private static void swap(int[] array, int m, int n){
    int temp = array[m];
    array[m] = array[n];
    array[n] = temp;
}
}