Programs & Examples On #Enterprisedb

EnterpriseDB is the vendor of Postgres Plus and Postgres Plus Advanced Server, two semi-compatible PostgreSQL variants.

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

For those wanting to use Postgresql on OpenSuse (and co), try the following:

zypper --no-refresh in php5-pgsql

fe_sendauth: no password supplied

I just put --password flag into my command and after hitting Enter it asked me for password, which I supplied.

Where are my postgres *.conf files?

In CentOS 7 with PostgreSQL 9.4 it's in the following directory:

/var/lib/pgsql/9.4/data

I can see it when I'm logged in as root.

Pass in an enum as a method parameter

Change the signature of the CreateFile method to expect a SupportedPermissions value instead of plain Enum.

public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions
    };

    return file.Id;
}

Then when you call your method you pass the SupportedPermissions value to your method

  var basicFile = CreateFile(myId, myName, myDescription, SupportedPermissions.basic);

Invoking a static method using reflection

public class Add {
    static int add(int a, int b){
        return (a+b);
    }
}

In the above example, 'add' is a static method that takes two integers as arguments.

Following snippet is used to call 'add' method with input 1 and 2.

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

Reference link.

Why am I getting a FileNotFoundError?

You might need to change your path by:

import os
path=os.chdir(str('Here should be the path to your file')) #This command changes directory

This is what worked for me at least! Hope it works for you too!

Structure padding and packing

I know this question is old and most answers here explains padding really well, but while trying to understand it myself I figured having a "visual" image of what is happening helped.

The processor reads the memory in "chunks" of a definite size (word). Say the processor word is 8 bytes long. It will look at the memory as a big row of 8 bytes building blocks. Every time it needs to get some information from the memory, it will reach one of those blocks and get it.

Variables Alignment

As seem in the image above, doesn't matter where a Char (1 byte long) is, since it will be inside one of those blocks, requiring the CPU to process only 1 word.

When we deal with data larger than one byte, like a 4 byte int or a 8 byte double, the way they are aligned in the memory makes a difference on how many words will have to be processed by the CPU. If 4-byte chunks are aligned in a way they always fit the inside of a block (memory address being a multiple of 4) only one word will have to be processed. Otherwise a chunk of 4-bytes could have part of itself on one block and part on another, requiring the processor to process 2 words to read this data.

The same applies to a 8-byte double, except now it must be in a memory address multiple of 8 to guarantee it will always be inside a block.

This considers a 8-byte word processor, but the concept applies to other sizes of words.

The padding works by filling the gaps between those data to make sure they are aligned with those blocks, thus improving the performance while reading the memory.

However, as stated on others answers, sometimes the space matters more then performance itself. Maybe you are processing lots of data on a computer that doesn't have much RAM (swap space could be used but it is MUCH slower). You could arrange the variables in the program until the least padding is done (as it was greatly exemplified in some other answers) but if that's not enough you could explicitly disable padding, which is what packing is.

Array to Collection: Optimized code

You can use:

list.addAll(Arrays.asList(array));

Compiling with g++ using multiple cores

You can do this with make - with gnu make it is the -j flag (this will also help on a uniprocessor machine).

For example if you want 4 parallel jobs from make:

make -j 4

You can also run gcc in a pipe with

gcc -pipe

This will pipeline the compile stages, which will also help keep the cores busy.

If you have additional machines available too, you might check out distcc, which will farm compiles out to those as well.

How should you diagnose the error SEHException - External component has thrown an exception

The component makers say that this has been fixed in the latest version of their component which we are using in-house, but this has been given to the customer yet.

Ask the component maker how to test whether the problem that the customer is getting is the problem which they say they've fixed in their latest version, without/before deploying their latest version to the customer.

How can I show a combobox in Android?

Not tested, but the closer you can get seems to be is with AutoCompleteTextView. You can write an adapter wich ignores the filter functions. Something like:

class UnconditionalArrayAdapter<T> extends ArrayAdapter<T> {
    final List<T> items;
    public UnconditionalArrayAdapter(Context context, int textViewResourceId, List<T> items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    public Filter getFilter() {
        return new NullFilter();
    }

    class NullFilter extends Filter {
        protected Filter.FilterResults performFiltering(CharSequence constraint) {
            final FilterResults results = new FilterResults();
            results.values = items;
            return results;
        }

        protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
            items.clear(); // `items` must be final, thus we need to copy the elements by hand.
            for (Object item : (List) results.values) {
                items.add((String) item);
            }
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}

... then in your onCreate:

String[] COUNTRIES = new String[] {"Belgium", "France", "Italy", "Germany"};
List<String> contriesList = Arrays.asList(COUNTRIES());
ArrayAdapter<String> adapter = new UnconditionalArrayAdapter<String>(this,
    android.R.layout.simple_dropdown_item_1line, contriesList);
AutoCompleteTextView textView = (AutoCompleteTextView)
    findViewById(R.id.countries_list);
textView.setAdapter(adapter);

The code is not tested, there can be some features with the filtering method I did not consider, but there you have it, the basic principles to emulate a ComboBox with an AutoCompleteTextView.

Edit Fixed NullFilter implementation. We need access on the items, thus the constructor of the UnconditionalArrayAdapter needs to take a reference to a List (kind of a buffer). You can also use e.g. adapter = new UnconditionalArrayAdapter<String>(..., new ArrayList<String>); and then use adapter.add("Luxemburg"), so you don't need to manage the buffer list.

How do I pass parameters to a jar file at the time of execution?

java [ options ] -jar file.jar [ argument ... ]

if you need to pass the log4j properties file use the below option

-Dlog4j.configurationFile=directory/file.xml


java -Dlog4j.configurationFile=directory/file.xml -jar <JAR FILE> [arguments ...]

Detect click outside React component

An example with Strategy

I like the provided solutions that use to do the same thing by creating a wrapper around the component.

Since this is more of a behavior I thought of Strategy and came up with the following.

I'm new with React and I need a bit of help in order to save some boilerplate in the use cases

Please review and tell me what you think.

ClickOutsideBehavior

import ReactDOM from 'react-dom';

export default class ClickOutsideBehavior {

  constructor({component, appContainer, onClickOutside}) {

    // Can I extend the passed component's lifecycle events from here?
    this.component = component;
    this.appContainer = appContainer;
    this.onClickOutside = onClickOutside;
  }

  enable() {

    this.appContainer.addEventListener('click', this.handleDocumentClick);
  }

  disable() {

    this.appContainer.removeEventListener('click', this.handleDocumentClick);
  }

  handleDocumentClick = (event) => {

    const area = ReactDOM.findDOMNode(this.component);

    if (!area.contains(event.target)) {
        this.onClickOutside(event)
    }
  }
}

Sample Usage

import React, {Component} from 'react';
import {APP_CONTAINER} from '../const';
import ClickOutsideBehavior from '../ClickOutsideBehavior';

export default class AddCardControl extends Component {

  constructor() {
    super();

    this.state = {
      toggledOn: false,
      text: ''
    };

    this.clickOutsideStrategy = new ClickOutsideBehavior({
      component: this,
      appContainer: APP_CONTAINER,
      onClickOutside: () => this.toggleState(false)
    });
  }

  componentDidMount () {

    this.setState({toggledOn: !!this.props.toggledOn});
    this.clickOutsideStrategy.enable();
  }

  componentWillUnmount () {
    this.clickOutsideStrategy.disable();
  }

  toggleState(isOn) {

    this.setState({toggledOn: isOn});
  }

  render() {...}
}

Notes

I thought of storing the passed component lifecycle hooks and override them with methods simillar to this:

const baseDidMount = component.componentDidMount;

component.componentDidMount = () => {
  this.enable();
  baseDidMount.call(component)
}

component is the component passed to the constructor of ClickOutsideBehavior.
This will remove the enable/disable boilerplate from the user of this behavior but it doesn't look very nice though

LINQ Join with Multiple Conditions in On Clause

Here you go with:

from b in _dbContext.Burden 
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }

How to compare two files in Notepad++ v6.6.8

2018 10 25. Update.

Notepad++ 7.5.8 does not have plugin manager by default. You have to download plugins manually.

Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin. I had a similar issue here.

How do I `jsonify` a list in Flask?

A list in a flask can be easily jsonify using jsonify like:

from flask import Flask,jsonify
app = Flask(__name__)

tasks = [
    {
        'id':1,
        'task':'this is first task'
    },
    {
        'id':2,
        'task':'this is another task'
    }
]

@app.route('/app-name/api/v0.1/tasks',methods=['GET'])
def get_tasks():
    return jsonify({'tasks':tasks})  #will return the json

if(__name__ == '__main__'):
    app.run(debug = True)

How to Call a Function inside a Render in React/Jsx

To call the function you have to add ()

{this.renderIcon()}   

How to return an array from a function?

Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.

So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:

int *gnabber(){
  static int foo[] = {1,2,3}
  return foo;
}

Nginx reverse proxy causing 504 Gateway Timeout

Had the same problem. Turned out it was caused by iptables connection tracking on the upstream server. After removing --state NEW,ESTABLISHED,RELATED from the firewall script and flushing with conntrack -F the problem was gone.

Reading file input from a multipart/form-data POST

I open-sourced a C# Http form parser here.

This is slightly more flexible than the other one mentioned which is on CodePlex, since you can use it for both Multipart and non-Multipart form-data, and also it gives you other form parameters formatted in a Dictionary object.

This can be used as follows:

non-multipart

public void Login(Stream stream)
{
    string username = null;
    string password = null;

    HttpContentParser parser = new HttpContentParser(stream);
    if (parser.Success)
    {
        username = HttpUtility.UrlDecode(parser.Parameters["username"]);
        password = HttpUtility.UrlDecode(parser.Parameters["password"]);
    }
}

multipart

public void Upload(Stream stream)
{
    HttpMultipartParser parser = new HttpMultipartParser(stream, "image");

    if (parser.Success)
    {
        string user = HttpUtility.UrlDecode(parser.Parameters["user"]);
        string title = HttpUtility.UrlDecode(parser.Parameters["title"]);

        // Save the file somewhere
        File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
    }
}

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

CodeIgniter : Unable to load the requested file:

I was getting this error in PyroCMS.

You can improve the error message in the Loader.php file that is in the code of the library.

Open the Loader.php file and find any calls to show_error. I replaced mine with the following:

show_error(sprintf("Unable to load the requested file: \"%s\" with instance title of \"%s\"", $_ci_file, $_ci_data['_ci_vars']['options']['instance_title']));

I was then able to see which file was causing the issues for me.

Overriding fields or properties in subclasses

I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.

abstract class Base 
{
 protected int myInt;
 protected abstract void setMyInt();
}

class Derived : Base 
{
 override protected void setMyInt()
 {
   myInt = 3;
 }
}

By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.

abstract class Father
{
    abstract public int MyInt { get; }
}

class Son : Father
{
    public override int MyInt
    {
        get { return 1; }
    }
}

Javascript Equivalent to C# LINQ Select

Yes, Array.map() or $.map() does the same thing.

//array.map:
var ids = this.fruits.map(function(v){
    return v.Id;
});

//jQuery.map:
var ids2 = $.map(this.fruits, function (v){
    return v.Id;
});

console.log(ids, ids2);

http://jsfiddle.net/NsCXJ/1/

Since array.map isn't supported in older browsers, I suggest that you stick with the jQuery method.

If you prefer the other one for some reason you could always add a polyfill for old browser support.

You can always add custom methods to the array prototype as well:

Array.prototype.select = function(expr){
    var arr = this;
    //do custom stuff
    return arr.map(expr); //or $.map(expr);
};

var ids = this.fruits.select(function(v){
    return v.Id;
});

An extended version that uses the function constructor if you pass a string. Something to play around with perhaps:

Array.prototype.select = function(expr){
    var arr = this;

    switch(typeof expr){

        case 'function':
            return $.map(arr, expr);
            break;

        case 'string':

            try{

                var func = new Function(expr.split('.')[0], 
                                       'return ' + expr + ';');
                return $.map(arr, func);

            }catch(e){

                return null;
            }

            break;

        default:
            throw new ReferenceError('expr not defined or not supported');
            break;
    }

};

console.log(fruits.select('x.Id'));

http://jsfiddle.net/aL85j/

Update:

Since this has become such a popular answer, I'm adding similar my where() + firstOrDefault(). These could also be used with the string based function constructor approach (which is the fastest), but here is another approach using an object literal as filter:

Array.prototype.where = function (filter) {

    var collection = this;

    switch(typeof filter) { 

        case 'function': 
            return $.grep(collection, filter); 

        case 'object':
            for(var property in filter) {
              if(!filter.hasOwnProperty(property)) 
                  continue; // ignore inherited properties

              collection = $.grep(collection, function (item) {
                  return item[property] === filter[property];
              });
            }
            return collection.slice(0); // copy the array 
                                      // (in case of empty object filter)

        default: 
            throw new TypeError('func must be either a' +
                'function or an object of properties and values to filter by'); 
    }
};


Array.prototype.firstOrDefault = function(func){
    return this.where(func)[0] || null;
};

Usage:

var persons = [{ name: 'foo', age: 1 }, { name: 'bar', age: 2 }];

// returns an array with one element:
var result1 = persons.where({ age: 1, name: 'foo' });

// returns the first matching item in the array, or null if no match
var result2 = persons.firstOrDefault({ age: 1, name: 'foo' }); 

Here is a jsperf test to compare the function constructor vs object literal speed. If you decide to use the former, keep in mind to quote strings correctly.

My personal preference is to use the object literal based solutions when filtering 1-2 properties, and pass a callback function for more complex filtering.

I'll end this with 2 general tips when adding methods to native object prototypes:

  1. Check for occurrence of existing methods before overwriting e.g.:

    if(!Array.prototype.where) { Array.prototype.where = ...

  2. If you don't need to support IE8 and below, define the methods using Object.defineProperty to make them non-enumerable. If someone used for..in on an array (which is wrong in the first place) they will iterate enumerable properties as well. Just a heads up.

Start an external application from a Google Chrome Extension?

Previously, you would do this through NPAPI plugins.

However, Google is now phasing out NPAPI for Chrome, so the preferred way to do this is using the native messaging API. The external application would have to register a native messaging host in order to exchange messages with your application.

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

Try putting the following in the environment variables for the scheme under run(debug)

OS_ACTIVITY_MODE = disable

Get random item from array

If you don't mind picking the same item again at some other time:

$items[rand(0, count($items) - 1)];

How to unstash only certain files?

For Windows users: curly braces have special meaning in PowerShell. You can either surround with single quotes or escape with backtick. For example:

git checkout 'stash@{0}' YourFile

Without it, you may receive an error:

Unknown switch 'e'

SQL Not Like Statement not working

mattgcon,

Should work, do you get more rows if you run the same SQL with the "NOT LIKE" line commented out? If not, check the data. I know you mentioned in your question, but check that the actual SQL statement is using that clause. The other answers with NULL are also a good idea.

Correct way to convert size in bytes to KB, MB, GB in JavaScript

This solution builds upon previous solutions, but takes into account both metric and binary units:

function formatBytes(bytes, decimals, binaryUnits) {
    if(bytes == 0) {
        return '0 Bytes';
    }
    var unitMultiple = (binaryUnits) ? 1024 : 1000; 
    var unitNames = (unitMultiple === 1024) ? // 1000 bytes in 1 Kilobyte (KB) or 1024 bytes for the binary version (KiB)
        ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']: 
        ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var unitChanges = Math.floor(Math.log(bytes) / Math.log(unitMultiple));
    return parseFloat((bytes / Math.pow(unitMultiple, unitChanges)).toFixed(decimals || 0)) + ' ' + unitNames[unitChanges];
}

Examples:

formatBytes(293489203947847, 1);    // 293.5 TB
formatBytes(1234, 0);   // 1 KB
formatBytes(4534634523453678343456, 2); // 4.53 ZB
formatBytes(4534634523453678343456, 2, true));  // 3.84 ZiB
formatBytes(4566744, 1);    // 4.6 MB
formatBytes(534, 0);    // 534 Bytes
formatBytes(273403407, 0);  // 273 MB

Converting ArrayList to HashMap

Using a supposed name property as the map key:

for (Product p: productList) { s.put(p.getName(), p); }

Discard all and get clean copy of latest revision?

If you're looking for a method that's easy, then you might want to try this.

I for myself can hardly remember commandlines for all of my tools, so I tend to do it using the UI:


1. First, select "commit"

Commit

2. Then, display ignored files. If you have uncommitted changes, hide them.

Show ignored files

3. Now, select all of them and click "Delete Unversioned".

Delete them

Done. It's a procedure that is far easier to remember than commandline stuff.

Making div content responsive

@media screen and (max-width : 760px) (for tablets and phones) and use with this: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Convert a hexadecimal string to an integer efficiently in C?

@Eric

Why is a code solution that works getting voted down? Sure, it's ugly and might not be the fastest way to do it, but it's more instructive that saying "strtol" or "sscanf". If you try it yourself you will learn something about how things happen under the hood.

I don't really think your solution should have been voted down, but my guess as to why it's happening is because it's less practical. The idea with voting is that the "best" answer will float to the top, and while your answer might be more instructive about what happens under the hood (or a way it might happen), it's definitely not the best way to parse hex numbers in a production system.

Again, I don't think there's anything wrong with your answer from an educational standpoint, and I certainly wouldn't (and didn't) vote it down. Don't get discouraged and stop posting just because some people didn't like one of your answers. It happens.

I doubt my answer makes you feel any better about yours being voted down, but I know it's especially not fun when you ask why something's being voted down and no one answers.

Should operator<< be implemented as a friend or as a member function?

The signature:

bool operator<<(const obj&, const obj&);

Seems rather suspect, this does not fit the stream convention nor the bitwise convention so it looks like a case of operator overloading abuse, operator < should return bool but operator << should probably return something else.

If you meant so say:

ostream& operator<<(ostream&, const obj&); 

Then since you can't add functions to ostream by necessity the function must be a free function, whether it a friend or not depends on what it has to access (if it doesn't need to access private or protected members there's no need to make it friend).

Android Studio Image Asset Launcher Icon Background Color

Using android 3.0.1 I noticed this weird behavior(solution), First: in background layer in the source_asset change the asset_type from image to color and than change it back to image. second: enable trim in scaling and then resize it to a small percentage and it will work perfectly. PS: If u didn't do the first step the scaling wont take affect. and if anyone have an explanation for this please provide. steps

Where is my m2 folder on Mac OS X Mavericks

If you have used brew to install maven, create .m2 directory and then copy settings.xml in .m2 directory.

mkdir ~/.m2
cp /usr/local/Cellar/maven32/3.2.5/libexec/conf/settings.xml ~/.m2

You may need to change the maven version in the path, mine is 3.2.5

Find records with a date field in the last 24 hours

You simply select dates that are higher than the current time minus 1 day.

SELECT * FROM news WHERE date >= now() - INTERVAL 1 DAY;

json parsing error syntax error unexpected end of input

Unexpected end of input means that the parser has ended prematurely. For example, it might be expecting "abcd...wxyz" but only sees "abcd...wxy.

This can be a typo error somewhere, or it could be a problem you get when encodings are mixed across different parts of the application.

One example: consider you are receiving data from a native app using chrome.runtime.sendNativeMessage:

chrome.runtime.sendNativeMessage('appname', {toJSON:()=>{return msg}}, (data)=>{
    console.log(data);
});

Now before your callback is called, the browser would attempt to parse the message using JSON.parse which can give you "unexpected end of input" errors if the supplied byte length does not match the data.

Aligning textviews on the left and right edges in Android layout

Dave Webb's answer did work for me. Thanks! Here my code, hope this helps someone!

<RelativeLayout
    android:background="#FFFFFF"
    android:layout_width="match_parent"
    android:minHeight="30dp"
    android:layout_height="wrap_content">
    <TextView
        android:height="25dp"
        android:layout_width="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="ABA Type"
        android:padding="3dip"
        android:layout_gravity="center_vertical"
        android:gravity="left|center_vertical"
        android:layout_height="match_parent" />
    <TextView
        android:background="@color/blue"
        android:minWidth="30px"
        android:minHeight="30px"
        android:layout_column="1"
        android:id="@+id/txtABAType"
        android:singleLine="false"
        android:layout_gravity="center_vertical"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="20dp"
        android:layout_width="wrap_content" />
</RelativeLayout>

Image: Image

How to prevent form from submitting multiple times from client side?

Use this code in your form.it will handle multiple clicks.

<script type="text/javascript">
    $(document).ready(function() {
        $("form").submit(function() {
            $(this).submit(function() {
                return false;
            });
            return true;
        });     
    }); 
</script>

it will work for sure.

Install GD library and freetype on Linux

For CentOS: When installing php-gd you need to specify the version. I fixed it by running: sudo yum install php55-gd

VSCode: How to Split Editor Vertically

To change the editor in Landscape and Vertical mode, follow the steps below.

  1. For example, open two files that you have in your left or right side bar, depending on where you are placed. By default it is always on the left.

  2. Now that you have both windows open, you have to use the key combination for PC (Alt + Shift + 1) for (Windows and Linux Operating Systems) or for MAC (Cmd + Option + 1), as commented here v-andrew.

How to get user agent in PHP

Use the native PHP $_SERVER['HTTP_USER_AGENT'] variable instead.

How to make zsh run as a login shell on Mac OS X (in iTerm)?

Go to the Users & Groups pane of the System Preferences -> Select the User -> Click the lock to make changes (bottom left corner) -> right click the current user select Advanced options... -> Select the Login Shell: /bin/zsh and OK

How can I declare and use Boolean variables in a shell script?

This is a speed test about different ways to test "Boolean" values in Bash:

#!/bin/bash
rounds=100000

b=true # For true; b=false for false
type -a true
time for i in $(seq $rounds); do command $b; done
time for i in $(seq $rounds); do $b; done
time for i in $(seq $rounds); do [ "$b" == true ]; done
time for i in $(seq $rounds); do test "$b" == true; done
time for i in $(seq $rounds); do [[ $b == true ]]; done

b=x; # Or any non-null string for true; b='' for false
time for i in $(seq $rounds); do [ "$b" ]; done
time for i in $(seq $rounds); do [[ $b ]]; done

b=1 # Or any non-zero integer for true; b=0 for false
time for i in $(seq $rounds); do ((b)); done

It would print something like

true is a shell builtin
true is /bin/true

real    0m0,815s
user    0m0,767s
sys     0m0,029s

real    0m0,562s
user    0m0,509s
sys     0m0,022s

real    0m0,829s
user    0m0,782s
sys     0m0,008s

real    0m0,782s
user    0m0,730s
sys     0m0,015s

real    0m0,402s
user    0m0,391s
sys     0m0,006s

real    0m0,668s
user    0m0,633s
sys     0m0,008s

real    0m0,344s
user    0m0,311s
sys     0m0,016s

real    0m0,367s
user    0m0,347s
sys     0m0,017s

How to write DataFrame to postgres table?

This is how I did it.

It may be faster because it is using execute_batch:

# df is the dataframe
if len(df) > 0:
    df_columns = list(df)
    # create (col1,col2,...)
    columns = ",".join(df_columns)

    # create VALUES('%s', '%s",...) one '%s' per column
    values = "VALUES({})".format(",".join(["%s" for _ in df_columns])) 

    #create INSERT INTO table (columns) VALUES('%s',...)
    insert_stmt = "INSERT INTO {} ({}) {}".format(table,columns,values)

    cur = conn.cursor()
    psycopg2.extras.execute_batch(cur, insert_stmt, df.values)
    conn.commit()
    cur.close()

Where can I download mysql jdbc jar from?

Go to http://dev.mysql.com/downloads/connector/j and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.

Download zip file and extract it, with in that you will find mysql-connector-XXX.jar file

If you are using maven then you can add the dependency from the link http://mvnrepository.com/artifact/mysql/mysql-connector-java

Select the version you want to use and add the dependency in your pom.xml file

Get exit code for command in bash/ksh

There are several things wrong with your script.

Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).

It's good practice to surround your variable references with curly braces, too. Your code might look like:

#!/bin/sh
command="/bin/date -u"          #...Example Only

safeRunCommand() {
   cmnd="$@"                    #...insure whitespace passed and preserved
   $cmnd
   ERROR_CODE=$?                #...so we have it for the command we want
   if [ ${ERROR_CODE} != 0 ]; then
      printf "Error when executing command: '${command}'\n"
      exit ${ERROR_CODE}        #...consider 'return()' here
   fi
}

safeRunCommand $command
command="cp"
safeRunCommand $command

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

@arad good point. In fact I just found this extension method (.NET 5.0):

PostAsJsonAsync<TValue>(HttpClient, String, TValue, CancellationToken)

from https://docs.microsoft.com/en-us/dotnet/api/system.net.http.json.httpclientjsonextensions.postasjsonasync?view=net-5.0

So one can now:

var data = new { foo = "Hello"; bar = 42; };
var response = await _Client.PostAsJsonAsync(_Uri, data, cancellationToken);

Make view 80% width of parent in React Native

You can also try react-native-extended-stylesheet that supports percentage for single-orientation apps:

import EStyleSheet from 'react-native-extended-stylesheet';

const styles = EStyleSheet.create({
  column: {
    width: '80%',
    height: '50%',
    marginLeft: '10%'
  }
});

Can I configure a subdomain to point to a specific port on my server

With only 1 IP you can forget DNS but you can use a MineProxy because the handshake packet of the client contains the host that then he connected to and a MineProxy will ready this host and proxy the connection to a server that is registered for that host

Using PowerShell credentials without being prompted for a password

There is another way, but...

DO NOT DO THIS IF YOU DO NOT WANT YOUR PASSWORD IN THE SCRIPT FILE (It isn't a good idea to store passwords in scripts, but some of us just like to know how.)

Ok, that was the warning, here's the code:

$username = "John Doe"
$password = "ABCDEF"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr

$cred will have the credentials from John Doe with the password "ABCDEF".

Alternative means to get the password ready for use:

$password = convertto-securestring -String "notverysecretpassword" -AsPlainText -Force

Capturing mobile phone traffic on Wireshark

Here are some suggestions:

  1. For Android phones, any network: Root your phone, then install tcpdump on it. This app is a tcpdump wrapper that will install tcpdump and enable you to start captures using a GUI. Tip: You will need to make sure you supply the right interface name for the capture and this varies from one device to another, eg -i eth0 or -i tiwlan0 - or use -i any to log all interfaces

  2. For Android 4.0+ phones: Android PCAP from Kismet uses the USB OTG interface to support packet capture without requiring root. I haven't tried this app, and there are some restrictions on the type of devices supported (see their page)

  3. For Android phones: tPacketCapture uses the Android VPN service to intercept packets and capture them. I have used this app successfully, but it also seems to affect the performance with large traffic volumes (eg video streaming)

  4. For IOS 5+ devices, any network: iOS 5 added a remote virtual interface (RVI) facility that lets you use Mac OS X packet trace programs to capture traces from an iOS device. See here for more details

  5. For all phones, wi-fi only: Set up your PC as a wireless access point, then run wireshark on the PC

  6. For all phones, wi-fi only: Get a capture device that can sniff wi-fi. This has the advantage of giving you 802.11x headers as well, but you may miss some of the packets

  7. Capture using a VPN server: Its fairly easy to set-up your own VPN server using OpenVPN. You can then route your traffic through your server by setting up the mobile device as a VPN client and capture the traffic on the server end.

Joining two table entities in Spring Data JPA

This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below

    @Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);

How to kill/stop a long SQL query immediately?

A simple answer, if the red "stop" box is not working, is to try pressing the "Ctrl + Break" buttons on the keyboard.

If you are running SQL Server on Linux, there is an app you can add to your systray called "killall" Just click on the "killall" button and then click on the program that is caught in a loop and it will terminate the program. Hope that helps.

setOnItemClickListener on custom ListView

If above answers don't work maybe you didn't add return value into getItem method in the custom adapter see this question and check out first answer.

HTTP requests and JSON parsing in Python

Try this:

import requests
import json

# Goole Maps API.
link = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'

# Request data from link as 'str'
data = requests.get(link).text

# convert 'str' to Json
data = json.loads(data)

# Now you can access Json 
for i in data['routes'][0]['legs'][0]['steps']:
    lattitude = i['start_location']['lat']
    longitude = i['start_location']['lng']
    print('{}, {}'.format(lattitude, longitude))

Click in OK button inside an Alert (Selenium IDE)

Try Selenium 2.0b1. It has different core than the first version. It should support popup dialogs according to documentation:

Popup Dialogs

Starting with Selenium 2.0 beta 1, there is built in support for handling popup dialog boxes. After you’ve triggered and action that would open a popup, you can access the alert with the following:

Java

Alert alert = driver.switchTo().alert();

Ruby

driver.switch_to.alert

This will return the currently open alert object. With this object you can now accept, dismiss, read it’s contents or even type into a prompt. This interface works equally well on alerts, confirms, prompts. Refer to the JavaDocs for more information.

Difference between using Throwable and Exception in a try catch

By catching Throwable it includes things that subclass Error. You should generally not do that, except perhaps at the very highest "catch all" level of a thread where you want to log or otherwise handle absolutely everything that can go wrong. It would be more typical in a framework type application (for example an application server or a testing framework) where it can be running unknown code and should not be affected by anything that goes wrong with that code, as much as possible.

What is the difference between "long", "long long", "long int", and "long long int" in C++?

Historically, in early C times, when processors had 8 or 16 bit wordlength,intwas identical to todays short(16 bit). In a certain sense, int is a more abstract data type thanchar,short,longorlong long, as you cannot be sure about the bitwidth.

When definingint n;you could translate this with "give me the best compromise of bitwidth and speed on this machine for n". Maybe in the future you should expect compilers to translateintto be 64 bit. So when you want your variable to have 32 bits and not more, better use an explicitlongas data type.

[Edit: #include <stdint.h> seems to be the proper way to ensure bitwidths using the int##_t types, though it's not yet part of the standard.]

How to create custom spinner like border around the spinner with down triangle on the right side?

You could design a simple nine-patch png image and use it as the background of spinner. Using GIMP you can put both border and right triangle in image.

Calling a java method from c++ in Android

If it's an object method, you need to pass the object to CallObjectMethod:

jobject result = env->CallObjectMethod(obj, messageMe, jstr);

What you were doing was the equivalent of jstr.messageMe().

Since your is a void method, you should call:

env->CallVoidMethod(obj, messageMe, jstr);

If you want to return a result, you need to change your JNI signature (the ()V means a method of void return type) and also the return type in your Java code.

Excel - find cell with same value in another worksheet and enter the value to the left of it

The easiest way is probably with VLOOKUP(). This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.

For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:

=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)

Then simply fill this formula down the rest of column D.

Explanation:

  • The first argument $D2 specifies the value to search for.
  • The second argument Sheet2!$A$2:$B$65535 specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535). Note I am assuming you have a header cell in row 1.
  • The third argument 2 specifies a 1-based index of the column to return from within the searched range. The value of 2 will return the second column in the range Sheet2!$A$2:$B$65535, namely the value of the B column.
  • The fourth argument FALSE says to only return exact matches.

How to uninstall/upgrade Angular CLI?

Run this command

npm uninstall angular-cli

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

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

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

Understanding the set() function

Sets are unordered, as you say. Even though one way to implement sets is using a tree, they can also be implemented using a hash table (meaning getting the keys in sorted order may not be that trivial).

If you'd like to sort them, you can simply perform:

sorted(set(y))

which will produce a sorted list containing the set's elements. (Not a set. Again, sets are unordered.)

Otherwise, the only thing guaranteed by set is that it makes the elements unique (nothing will be there more than once).

Hope this helps!

What can MATLAB do that R cannot do?

In my experience moving from MATLAB to Python is an easier transition - Python with numpy/scipy is closer to MATLAB in terms of style and features than R. There are also open source direct MATLAB clones Octave and Scilab.

There is certainly much that MATLAB can do that R can't - in my area MATLAB is used a lot for real time data aquisition - most hardware companies include MATLAB interfaces. While this may be possible with R I imagine it would be a lot more involved. Also Simulink provides a whole area of functionality which I think is missing from R. I'm sure there is more but I'm not so familiar with R.

Writing String to Stream and reading it back does not work

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

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

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

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

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

Remove directory from remote repository after adding them to .gitignore

As per my Answer here: How to remove a directory from git repository?

To remove folder/directory only from git repository and not from the local try 3 simple steps.


Steps to remove directory

git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master

Steps to ignore that folder in next commits

To ignore that folder from next commits make one file in root named .gitignore and put that folders name into it. You can put as many as you want

.gitignore file will be look like this

/FolderName

remove directory

Is it possible to write data to file using only JavaScript?

I found good answers here, but also found a simpler way.

The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute. (The reverse seems not possible, adding a href to a button does not work.)

You can style the link as a button using bootstrap, which is still pure javascript, except for styling.

Combining the button and the download link also reduces code, as fewer of those ugly getElementById calls are needed.

This example needs only one button click to create the text-blob and download it:

<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary" 
   onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
   Write To File
</a>

<script>
    // URL pointing to the Blob with the file contents
    var objUrl = null;
    // create the blob with file content, and attach the URL to the downloadlink; 
    // NB: link must have the download attribute
    // this method can go to your library
    function exportFile(fileContent, downloadLinkId) {
        // revoke the old object URL to avoid memory leaks.
        if (objUrl !== null) {
            window.URL.revokeObjectURL(objUrl);
        }
        // create the object that contains the file data and that can be referred to with a URL
        var data = new Blob([fileContent], { type: 'text/plain' });
        objUrl = window.URL.createObjectURL(data);
        // attach the object to the download link (styled as button)
        var downloadLinkButton = document.getElementById(downloadLinkId);
        downloadLinkButton.href = objUrl;
    };
</script>

How I add Headers to http.get or http.post in Typescript and angular 2?

if someone facing issue of CORS not working in mobile browser or mobile applications, you can set ALLOWED_HOSTS = ["your host ip"] in backend servers where your rest api exists, here your host ip is external ip to access ionic , like External: http://192.168.1.120:8100

After that in ionic type script make post or get using IP of backened server

in my case i used django rest framwork and i started server as:- python manage.py runserver 192.168.1.120:8000

and used this ip in ionic get and post calls of rest api

Adding double quote delimiters into csv file

Here's a way to do it without formulas or macros:

  1. Save your CSV as Excel
  2. Select any cells that might have commas
  3. Open to the Format menu and click on Cells
  4. Pick the Custom format
  5. Enter this => \"@\"
  6. Click OK
  7. Save the file as CSV

(from http://www.lenashore.com/2012/04/how-to-add-quotes-to-your-cells-in-excel-automatically/)

MultipartException: Current request is not a multipart request

i was facing the same issue with misspelled enctype="multipart/form-data", i was fix this exception by doing correct spelling . Current request is not a multipart request client side error so please check your form.

Getting a map() to return a list in Python 3.x

Why aren't you doing this:

[chr(x) for x in [66,53,0,94]]

It's called a list comprehension. You can find plenty of information on Google, but here's the link to the Python (2.6) documentation on list comprehensions. You might be more interested in the Python 3 documenation, though.

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

As additional to @Karthick Kumar answer from bootstrap docs

show is triggered at the start of an event

shown is triggered on the completion of an action

... so it should be:

$('.modal')
    .on('show.bs.modal', function (){
            $('body').css('overflow', 'hidden');
        })
    .on('hide.bs.modal', function (){
            // Also if you are using multiple modals (cascade) - additional check
            if ($('.modal.in').length == 1) {
                $('body').css('overflow', 'auto');
            }
        });

String to HtmlDocument

Using Html Agility Pack as suggested by SLaks, this becomes very easy:

string html = webClient.DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(html);

HtmlNode specificNode = doc.GetElementById("nodeId");
HtmlNodeCollection nodesMatchingXPath = doc.DocumentNode.SelectNodes("x/path/nodes");

What's the most elegant way to cap a number to a segment?

Update for ECMAScript 2017:

Math.clamp(x, lower, upper)

But note that as of today, it's a Stage 1 proposal. Until it gets widely supported, you can use a polyfill.

How to animate button in android?

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class HeightAnimation extends Animation {
    protected final int originalHeight;
    protected final View view;
    protected float perValue;

    public HeightAnimation(View view, int fromHeight, int toHeight) {
        this.view = view;
        this.originalHeight = fromHeight;
        this.perValue = (toHeight - fromHeight);
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        view.getLayoutParams().height = (int) (originalHeight + perValue * interpolatedTime);
        view.requestLayout();
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}

uss to:

HeightAnimation heightAnim = new HeightAnimation(view, view.getHeight(), viewPager.getHeight() - otherView.getHeight());
heightAnim.setDuration(1000);
view.startAnimation(heightAnim);

Pointer vs. Reference

If you have a parameter where you may need to indicate the absence of a value, it's common practice to make the parameter a pointer value and pass in NULL.

A better solution in most cases (from a safety perspective) is to use boost::optional. This allows you to pass in optional values by reference and also as a return value.

// Sample method using optional as input parameter
void PrintOptional(const boost::optional<std::string>& optional_str)
{
    if (optional_str)
    {
       cout << *optional_str << std::endl;
    }
    else
    {
       cout << "(no string)" << std::endl;
    }
}

// Sample method using optional as return value
boost::optional<int> ReturnOptional(bool return_nothing)
{
    if (return_nothing)
    {
       return boost::optional<int>();
    }

    return boost::optional<int>(42);
}

Calculate the number of business days between two dates?

Ok. I think it's time to post the right answer:

public static double GetBusinessDays(DateTime startD, DateTime endD)
{
    double calcBusinessDays =
        1 + ((endD - startD).TotalDays * 5 -
        (startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;

    if (endD.DayOfWeek == DayOfWeek.Saturday) calcBusinessDays--;
    if (startD.DayOfWeek == DayOfWeek.Sunday) calcBusinessDays--;

    return calcBusinessDays;
}

Original Source:

http://alecpojidaev.wordpress.com/2009/10/29/work-days-calculation-with-c/

Looking for a 'cmake clean' command to clear up CMake output

Maybe it's a little outdated, but since this is the first hit when you google cmake clean, I will add this:

Since you can start a build in the build dir with a specified target with

cmake --build . --target xyz

you can of course run

cmake --build . --target clean

to run the clean target in the generated build files.

How to solve "Fatal error: Class 'MySQLi' not found"?

In php.ini :

extension_dir ="c:/wamp64/bin/php/php7.4.9/ext/"

Make sure the PHP version is correct.

Regex for checking if a string is strictly alphanumeric

See the documentation of Pattern.

Assuming US-ASCII alphabet (a-z, A-Z), you could use \p{Alnum}.

A regex to check that a line contains only such characters is "^[\\p{Alnum}]*$".

That also matches empty string. To exclude empty string: "^[\\p{Alnum}]+$".

How do I edit an incorrect commit message in git ( that I've pushed )?

(From http://git.or.cz/gitwiki/GitTips#head-9f87cd21bcdf081a61c29985604ff4be35a5e6c0)

How to change commits deeper in history

Since history in Git is immutable, fixing anything but the most recent commit (commit which is not branch head) requires that the history is rewritten from the changed commit and forward.

You can use StGIT for that, initialize branch if necessary, uncommitting up to the commit you want to change, pop to it if necessary, make a change then refresh patch (with -e option if you want to correct commit message), then push everything and stg commit.

Or you can use rebase to do that. Create new temporary branch, rewind it to the commit you want to change using git reset --hard, change that commit (it would be top of current head), then rebase branch on top of changed commit, using git rebase --onto .

Or you can use git rebase --interactive, which allows various modifications like patch re-ordering, collapsing, ...

I think that should answer your question. However, note that if you have pushed code to a remote repository and people have pulled from it, then this is going to mess up their code histories, as well as the work they've done. So do it carefully.

SMTP connect() failed PHPmailer - PHP

 $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

Excel VBA Open workbook, perform actions, save as, close

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


Html.DropDownList - Disabled/Readonly

Or you can try something like this:

Html.DropDownList("Types", Model.Types, new { @readonly = "true" })

How do I check whether a file exists without exceptions?

If you imported NumPy already for other purposes then there is no need to import other libraries like pathlib, os, paths, etc.

import numpy as np
np.DataSource().exists("path/to/your/file")

This will return true or false based on its existence.

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

It seems necessary to state ones degree here: B.A. in Political Science and B.ed in Computer Science.

To the point:

Is this going to put people off coming to Scala?

Scala is difficult, because its underlying programming paradigm is difficult. Functional programming scares a lot of people. It is possible to build closures in PHP but people rarely do. So no, not this signature but all the rest will put people off, if they do not have the specific education to make them value the power of the underlying paradigm.

If this education is available, everyone can do it. Last year I build a chess computer with a bunch of school kids in SCALA! They had their problems but they did fine in the end.

If you're using Scala commercially, are you worried about this? Are you planning to adopt 2.8 immediately or wait to see what happens?

I would not be worried.

Form/JavaScript not working on IE 11 with error DOM7011

I got the same console warning, when an ajax request was firing, so my form was also not working properly.

I disabled caching on the server's ajax call with the following response headers:

Cache-Control: no-cache, no-store, must-revalidate
Expires: -1
Pragma: no-cache

After this, the form was working. Refer to the server language (c#, php, java etc) you are using on how to add these response headers.

How to draw in JPanel? (Swing/graphics Java)

When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics object outside the paint()/paintComponent()/etc. methods.

However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics() method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel's paintComponent(), you simply need to draw the BufferedImage instance unto the JPanel. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.

Use different Python version with virtualenv

This worked for my usage in Windows 10, where I have Python 3.7 and want to downgrade for a project in Python 3.6.6:

I used "venv" to create a new environment called "venv", I downloaded from https://www.python.org/downloads/windows/ ; install "Download Windows x86-64 executable installer-" ; then I used the following command line in the directory where I want to create my environment

>C:\Users\...\Python\Python36\python.exe -m venv venv

Finally, I activated the environnent using the command line:

>venv\Scripts\activate.bat

And check the python version by calling:

>python --version Python 3.6.6

How can I concatenate a string and a number in Python?

Python is strongly typed. There are no implicit type conversions.

You have to do one of these:

"asd%d" % 9
"asd" + str(9)

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

Eclipse: stop code from running (java)

I have a .bat file on my quick task bar (windows) with:

taskkill /F /IM java.exe

It's very quick, but it may not be good in many situations!

docker unauthorized: authentication required - upon push with successful login

The problem newbies face is that we tend to treat docker hub repository just like a maven repository and think that it might contain many a different files, folders and other contents.

A docker repository on the other hand is just a single image, it does not contain anything else. It can hold different versions of the same image, but its going to contain just one image.

So, name your repository on docker hub the same name as the image you want to push into it, and use your dockerhub username as prefix. For eg, if your username is myusername and your image name is docker-whale , make sure to name your dockerhub repository as docker-whale and use the below commands to tag and push your image to repository:

docker logout                                   # to make sure you're logged out and not cause any clashes
docker tag <imageId> myusername/docker-whale    # use :1.0.0 for specific version, default is 'latest'
docker login --username=myusername              # use the username/pwd to login to docker hub
docker push myusername/docker-whale             # use :1.0.0 for pushing specific version, default is 'latest'

How to select element using XPATH syntax on Selenium for Python?

HTML

<div id='a'>
  <div>
    <a class='click'>abc</a>
  </div>
</div>

You could use the XPATH as :

//div[@id='a']//a[@class='click']

output

<a class="click">abc</a>

That said your Python code should be as :

driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")

The remote certificate is invalid according to the validation procedure

Try put this before send e-mail

ServicePointManager.ServerCertificateValidationCallback = 
        delegate(object s, X509Certificate certificate, X509Chain chain,
        SslPolicyErrors sslPolicyErrors) { return true; };

Remenber to add the using libs!

Renaming column names of a DataFrame in Spark Scala

tow table join not rename the joined key

// method 1: create a new DF
day1 = day1.toDF(day1.columns.map(x => if (x.equals(key)) x else s"${x}_d1"): _*)

// method 2: use withColumnRenamed
for ((x, y) <- day1.columns.filter(!_.equals(key)).map(x => (x, s"${x}_d1"))) {
    day1 = day1.withColumnRenamed(x, y)
}

works!

Floating point comparison functions for C#

Further to Andrew Wang's answer: if the BitConverter method is too slow but you cannot use unsafe code in your project, this struct is ~6x quicker than BitConverter:

[StructLayout(LayoutKind.Explicit)]
public struct FloatToIntSafeBitConverter
{
    public static int Convert(float value)
    {
        return new FloatToIntSafeBitConverter(value).IntValue;
    }

    public FloatToIntSafeBitConverter(float floatValue): this()
    {
        FloatValue = floatValue;
    }

    [FieldOffset(0)]
    public readonly int IntValue;

    [FieldOffset(0)]
    public readonly float FloatValue;
}

(Incidentally, I tried using the accepted solution but it (well my conversion at least) failed some of the unit tests also mentioned in the answer. e.g. assertTrue(nearlyEqual(Float.MIN_VALUE, -Float.MIN_VALUE)); )

Cannot deserialize the current JSON array (e.g. [1,2,3])

You have an array, convert it to an object, something like:

data: [{"id": 3636, "is_default": true, "name": "Unit", "quantity": 1, "stock": "100000.00", "unit_cost": "0"}, {"id": 4592, "is_default": false, "name": "Bundle", "quantity": 5, "stock": "100000.00", "unit_cost": "0"}]

Netbeans how to set command line arguments in Java

  1. Create the Java code that can receive an argument as a command line argument.

    class TestCode{
        public static void main(String args[]){
            System.out.println("first argument is: "+args[0]);
        }
    }
    
  2. Run the program without arguments (press F6).

  3. In the Output window, at the bottom, click the double yellow arrow (or the yellow button) to open a Run dialog.

  4. If the argument you need to pass is testArgument, then here in this window pass the argument as application.args=testArgument.

This will give the output as follows in the same Output window:

first argument is: testArgument

For Maven, the instructions are similar, but change the exec.args property instead:

exec.args=-classpath %classpath package.ClassName PARAM1 PARAM2 PARAM3

Note: Use single quotes for string parameters that contain spaces.

Moment JS start and end of given month

Try the following code:

moment(startDate).startOf('months')
moment(startDate).endOf('months')

File uploading with Express 4.0: req.files undefined

PROBLEM SOLVED !!!!!!!

Turns out the storage function DID NOT run even once. because i had to include app.use(upload) as upload = multer({storage}).single('file');

 let storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, './storage')
          },
          filename: function (req, file, cb) {
            console.log(file) // this didn't print anything out so i assumed it was never excuted
            cb(null, file.fieldname + '-' + Date.now())
          }
    });

    const upload = multer({storage}).single('file');

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

If it's important you really need to benchmark both options!

Having said that, I have always used the exception method, the reasoning being it's better to only hit the database once.

Spring: How to inject a value to static field?

This is my sample code for load static variable

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class OnelinkConfig {
    public static int MODULE_CODE;
    public static int DEFAULT_PAGE;
    public static int DEFAULT_SIZE;

    @Autowired
    public void loadOnelinkConfig(@Value("${onelink.config.exception.module.code}") int code,
            @Value("${onelink.config.default.page}") int page, @Value("${onelink.config.default.size}") int size) {
        MODULE_CODE = code;
        DEFAULT_PAGE = page;
        DEFAULT_SIZE = size;
    }
}

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I had same issue. adding this to the application.properties solved the issue:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

Best Free Text Editor Supporting *More Than* 4GB Files?

Textpad also works well at opening files that size. I have done it many times when having to deal with extremely large log files in the 3-5gb range. Also, using grep to pull out the worthwhile lines and then look at those works great.

Going to a specific line number using Less in Unix

To open at a specific line straight from the command line, use:

less +320123 filename

If you want to see the line numbers too:

less +320123 -N filename

You can also choose to display a specific line of the file at a specific line of the terminal, for when you need a few lines of context. For example, this will open the file with line 320123 on the 10th line of the terminal:

less +320123 -j 10 filename

How to get row number in dataframe in Pandas?

 len(df[df["Lastname"]=="Smith"].values)

how to specify new environment location for conda create

While using the --prefix option works, you have to explicitly use it every time you create an environment. If you just want your environments stored somewhere else by default, you can configure it in your .condarc file.

Please see: https://conda.io/docs/user-guide/configuration/use-condarc.html#specify-environment-directories-envs-dirs

Customize list item bullets using CSS

Based on @dzimney answer and similar to @Crisman answer (but different)

That answer is good but has indention problem (bullets appear inside of li scope). Probably you don't want this. See simple example list below (this is a default HTML list):

  • Lorem ipsum dolor sit amet, ei cum offendit partiendo iudicabit. At mei quaestio honestatis, duo dicit affert persecuti ei. Etiam nusquam cu his, nec alterum posidonium philosophia te. Nec an purto iudicabit, no vix quod clita expetendis.

  • Quem suscipiantur no eos, sed impedit explicari ea, falli inermis comprehensam est in. Vide dicunt ancillae cum te, habeo delenit deserunt mei in. Tale sint ex his, ipsum essent appellantur et cum.

But if you use the mentioned answer the list will be like below (ignoring the size of the bullets):

Lorem ipsum dolor sit amet, ei cum offendit partiendo iudicabit. At mei quaestio honestatis, duo dicit affert persecuti ei. Etiam nusquam cu his, nec alterum posidonium philosophia te. Nec an purto iudicabit, no vix quod clita expetendis.

Quem suscipiantur no eos, sed impedit explicari ea, falli inermis comprehensam est in. Vide dicunt ancillae cum te, habeo delenit deserunt mei in. Tale sint ex his, ipsum essent appellantur et cum.


So I recommend this approach that resolves the issue:

_x000D_
_x000D_
li {_x000D_
    list-style-type: none;_x000D_
    position: relative;    /* It's needed for setting position to absolute in the next rule. */_x000D_
}_x000D_
_x000D_
li::before {_x000D_
    content: '¦';_x000D_
    position: absolute;_x000D_
    left: -0.8em;          /* Adjust this value so that it appears where you want. */_x000D_
    font-size: 1.1em;      /* Adjust this value so that it appears what size you want. */_x000D_
}
_x000D_
<ul>_x000D_
    <li>Lorem ipsum dolor sit amet, ei cum offendit partiendo iudicabit. At mei quaestio honestatis, duo dicit affert persecuti ei. Etiam nusquam cu his, nec alterum posidonium philosophia te. Nec an purto iudicabit, no vix quod clita expetendis.</li>_x000D_
    <li>Quem suscipiantur no eos, sed impedit explicari ea, falli inermis comprehensam est in. Vide dicunt ancillae cum te, habeo delenit deserunt mei in. Tale sint ex his, ipsum essent appellantur et cum.</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Playing sound notifications using Javascript?

I wrote a small function that can do it, with the Web Audio API...

var beep = function(duration, type, finishedCallback) {

    if (!(window.audioContext || window.webkitAudioContext)) {
        throw Error("Your browser does not support Audio Context.");
    }

    duration = +duration;

    // Only 0-4 are valid types.
    type = (type % 5) || 0;

    if (typeof finishedCallback != "function") {
        finishedCallback = function() {};   
    }

    var ctx = new (window.audioContext || window.webkitAudioContext);
    var osc = ctx.createOscillator();

    osc.type = type;

    osc.connect(ctx.destination);
    osc.noteOn(0);

    setTimeout(function() {
        osc.noteOff(0);
        finishedCallback();
    }, duration);

};

__init__ and arguments in Python

In python you must always pass in at least one argument to class methods, the argument is self and it is not meaningless its a reference to the instance itself

The SQL OVER() clause - when and why is it useful?

  • Also Called Query Petition Clause.
  • Similar to the Group By Clause

    • break up data into chunks (or partitions)
    • separate by partition bounds
    • function performs within partitions
    • re-initialised when crossing parting boundary

Syntax:
function (...) OVER (PARTITION BY col1 col3,...)

  • Functions

    • Familiar functions such as COUNT(), SUM(), MIN(), MAX(), etc
    • New Functions as well (eg ROW_NUMBER(), RATION_TO_REOIRT(), etc.)


More info with example : http://msdn.microsoft.com/en-us/library/ms189461.aspx

Python and JSON - TypeError list indices must be integers not str

I solved changing

readable_json['firstName']

by

readable_json[0]['firstName']

Amazon S3 upload file and get URL

@hussachai and @Jeffrey Kemp answers are pretty good. But they have something in common is the url returned is of virtual-host-style, not in path style. For more info regarding to the s3 url style, can refer to AWS S3 URL Styles. In case of some people want to have path style s3 url generated. Here's the step. Basically everything will be the same as @hussachai and @Jeffrey Kemp answers, only with one line setting change as below:

AmazonS3Client s3Client = (AmazonS3Client) AmazonS3ClientBuilder.standard()
                    .withRegion("us-west-2")
                    .withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
                    .withPathStyleAccessEnabled(true)
                    .build();

// Upload a file as a new object with ContentType and title specified.
PutObjectRequest request = new PutObjectRequest(bucketName, stringObjKeyName, fileToUpload);
s3Client.putObject(request);
URL s3Url = s3Client.getUrl(bucketName, stringObjKeyName);
logger.info("S3 url is " + s3Url.toExternalForm());

This will generate url like: https://s3.us-west-2.amazonaws.com/mybucket/myfilename

Do I really need to encode '&' as '&amp;'?

Update (March 2020): The W3C validator no longer complains about escaping URLs.

I was checking why Image URL's need escaping, hence tried it in https://validator.w3.org. The explanation is pretty nice. It highlights that even URL's need to be escaped. [PS:I guess it will unescaped when its consumed since URL's need &. Can anyone clarify?]

<img alt="" src="foo?bar=qut&qux=fop" />

An entity reference was found in the document, but there is no reference by that name defined. Often this is caused by misspelling the reference name, unencoded ampersands, or by leaving off the trailing semicolon (;). The most common cause of this error is unencoded ampersands in URLs as described by the WDG in "Ampersands in URLs". Entity references start with an ampersand (&) and end with a semicolon (;). If you want to use a literal ampersand in your document you must encode it as "&" (even inside URLs!). Be careful to end entity references with a semicolon or your entity reference may get interpreted in connection with the following text. Also keep in mind that named entity references are case-sensitive; &Aelig; and æ are different characters. If this error appears in some markup generated by PHP's session handling code, this article has explanations and solutions to your problem.

Can an Android App connect directly to an online mysql database

It is actually very easy. But there is no way you can achieve it directly. You need to select a service side technology. You can use anything for this part. And this is what we call a RESTful API or a SOAP API. It depends on you what to select. I have done many project with both. I would prefer REST. So what will happen you will have some scripts in your web server, and you know the URLs. For example we need to make a user registration. And for this we have

mydomain.com/v1/userregister.php

Now from the android side you will send an HTTP request to the above URL. And the above URL will handle the User Registration and will give you a response that whether the operation succeed or not.

For a complete detailed explanation of the above concept. You can visit the following link.

**Android MySQL Tutorial to Perform CRUD Operation**

How to change DatePicker dialog color for Android 5.0

Create a new style

<!-- Theme.AppCompat.Light.Dialog -->
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">@color/blue_500</item>
</style>

Java code:

The parent theme is the key here. Choose your colorAccent

DatePickerDialog = new DatePickerDialog(context,R.style.DialogTheme,this,now.get(Calendar.YEAR),now.get(Calendar.MONTH),now.get(Calendar.DAY_OF_MONTH);

Result:

enter image description here

Configure Apache .conf for Alias

Sorry not sure what was going on this worked in the end:

<VirtualHost *> 
    ServerName example.com
    DocumentRoot /var/www/html/mjp

    Alias /ncn "/var/www/html/ncn"

    <Directory "/var/www/html/ncn">
        Options None
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

catching stdout in realtime from subprocess

    p = subprocess.Popen(command,
                                bufsize=0,
                                universal_newlines=True)

I am writing a GUI for rsync in python, and have the same probelms. This problem has troubled me for several days until i find this in pyDoc.

If universal_newlines is True, the file objects stdout and stderr are opened as text files in universal newlines mode. Lines may be terminated by any of '\n', the Unix end-of-line convention, '\r', the old Macintosh convention or '\r\n', the Windows convention. All of these external representations are seen as '\n' by the Python program.

It seems that rsync will output '\r' when translate is going on.

Set up Python 3 build system with Sublime Text 3

Run Python Files in Sublime Text3

For Sublime Text 3, First Install Package Control:

  • Press Ctrl + Shift + P, a search bar will open
  • Type Install package and then press enter Click here to see Install Package Search Pic

  • After the package got installed. It may prompt to restart SublimeText

  • After completing the above step
  • Just again repeat the 1st and 2nd step, it will open the repositories this time
  • Search for Python 3 and Hit enter.
  • There you go.
  • Just press Ctrl + B in your python file and you'll get the output. Click here to see Python 3 repo pic

It perfectly worked for me. Hopefully, it helped you too. For any left requirements, visit https://packagecontrol.io/installation#st3 here.

How to change active class while click to another link in bootstrap use jquery?

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
$(document).ready(function () {_x000D_
        var url = window.location;_x000D_
        $('ul.nav a[href="' + url + '"]').parent().addClass('active');_x000D_
        $('ul.nav a').filter(function () {_x000D_
            return this.href == url;_x000D_
        }).parent().addClass('active').parent().parent().addClass('active');_x000D_
    });_x000D_
    _x000D_
    This works perfectly
_x000D_
_x000D_
_x000D_

.mp4 file not playing in chrome

After running into the same issue - here're some of my thoughts:

  • due to Chrome removing support for h264, on some machines, mp4 videos encoded with it will either not work (throwing an Parser error when viewing under Firebug/Network tab - consistent with issue submitted here), or crash the browser, depending upon the encoding settings
  • it isn't consistent - it entirely depends upon the codecs installed on the computer - while I didn't encounter this issue on my machine, we did have one in the office where the issue occurred (and thus we used this one for testing)
  • it might to do with Quicktime / divX settings (the machine in question had an older version of Quicktime than my native one - we didn't want to loose our testing pc though, so we didn't update it).

As it affects only Chrome (other browsers work fine with VideoForEverybody solution) the solution I've used is:

for every mp4 file, create a Theora encoded mp4 file (example.mp4 -> example_c.mp4) apply following js:

if (window.chrome)
    $("[type=video\\\/mp4]").each(function()
    {
        $(this).attr('src', $(this).attr('src').replace(".mp4", "_c.mp4"));
    });

Unfortunately it's a bad Chrome hack, but hey, at least it works.

Source: user: eithedog

This also can help: chrome could play html5 mp4 video but html5test said chrome did not support mp4 video codec

Also check your version of crome here: html5test

How to select all instances of a variable and edit variable name in Sublime

The Magic is, you have to start with an empty selection, so put your cursor in front of the word/character you want to multi-select and press Ctrl+D .

Android ACTION_IMAGE_CAPTURE Intent

It is very simple to solve this problem with Activity Result Code Simple try this method

if (reqCode == RECORD_VIDEO) {
   if(resCode == RESULT_OK) {
       if (uri != null) {
           compress();
       }
    } else if(resCode == RESULT_CANCELED && data!=null){
       Toast.makeText(MainActivity.this,"No Video Recorded",Toast.LENGTH_SHORT).show();
   }
}

Difference between Dictionary and Hashtable

Lets give an example that would explain the difference between hashtable and dictionary.

Here is a method that implements hashtable

public void MethodHashTable()
{
    Hashtable objHashTable = new Hashtable();
    objHashTable.Add(1, 100);    // int
    objHashTable.Add(2.99, 200); // float
    objHashTable.Add('A', 300);  // char
    objHashTable.Add("4", 400);  // string

    lblDisplay1.Text = objHashTable[1].ToString();
    lblDisplay2.Text = objHashTable[2.99].ToString();
    lblDisplay3.Text = objHashTable['A'].ToString();
    lblDisplay4.Text = objHashTable["4"].ToString();


    // ----------- Not Possible for HashTable ----------
    //foreach (KeyValuePair<string, int> pair in objHashTable)
    //{
    //    lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
    //}
}

The following is for dictionary

  public void MethodDictionary()
  {
    Dictionary<string, int> dictionary = new Dictionary<string, int>();
    dictionary.Add("cat", 2);
    dictionary.Add("dog", 1);
    dictionary.Add("llama", 0);
    dictionary.Add("iguana", -1);

    //dictionary.Add(1, -2); // Compilation Error

    foreach (KeyValuePair<string, int> pair in dictionary)
    {
        lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
    }
  }

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

Friend, don't worry, if you have any application installed built in codeigniter and you wanna add some language pack just follow these steps:

1. Add language files in folder application/language/arabic (i add arabic lang in sma2 built in ci)

2. Go to the file named setting.php in application/modules/settings/views/setting.php. Here you find the array

<?php /*

 $lang = array (
  'english' => 'English',

  'arabic' => 'Arabic',  // i add this here

  'spanish' => 'Español'

Now save and run the application. It's worked fine.

How to use icons and symbols from "Font Awesome" on Native Android Application

In case you only need a few font awesome icons, you can also use http://fa2png.io to generate normal pixel images. But if you add new icons/buttons regularly I'd recommend the .ttf version as its more flexible.

How to delete or add column in SQLITE?

As SQLite has limited support to ALTER TABLE so you can only ADD column at end of the table OR CHANGE TABLE_NAME in SQLite.

Here is the Best Answer of HOW TO DELETE COLUMN FROM SQLITE?

visit Delete column from SQLite table

How do I pipe or redirect the output of curl -v?

This simple example shows how to capture curl output, and use it in a bash script

test.sh

function main
{
  \curl -vs 'http://google.com'  2>&1
  # note: add -o /tmp/ignore.png if you want to ignore binary output, by saving it to a file. 
}

# capture output of curl to a variable
OUT=$(main)

# search output for something using grep.
echo
echo "$OUT" | grep 302 
echo
echo "$OUT" | grep title 

Java: How can I compile an entire directory structure of code ?

There is a way to do this without using a pipe character, which is convenient if you are forking a process from another programming language to do this:

find $JAVA_SRC_DIR -name '*.java' -exec javac -d $OUTPUT_DIR {} +

Though if you are in Bash and/or don't mind using a pipe, then you can do:

find $JAVA_SRC_DIR -name '*.java' | xargs javac -d $OUTPUT_DIR

How to reset (clear) form through JavaScript?

form.reset() is a DOM element method (not one on the jQuery object), so you need:

$("#client.frm")[0].reset();
//faster version:
$("#client")[0].reset();

Or without jQuery:

document.getElementById("client").reset();

Why can't I define a static method in a Java interface?

With the advent of Java 8 it is possible now to write default and static methods in interface. docs.oracle/staticMethod

For example:

public interface Arithmetic {

    public int add(int a, int b);

    public static int multiply(int a, int b) {
        return a * b;
    }
}
public class ArithmaticImplementation implements Arithmetic {

    @Override
    public int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = Arithmetic.multiply(2, 3);
        System.out.println(result);
    }
}

Result : 6

TIP : Calling an static interface method doesn't require to be implemented by any class. Surely, this happens because the same rules for static methods in superclasses applies for static methods on interfaces.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

Let me make it simple.
You can use @JoinColumn on either sides irrespective of mapping.

Let's divide this into three cases.
1) Uni-directional mapping from Branch to Company.
2) Bi-direction mapping from Company to Branch.
3) Only Uni-directional mapping from Company to Branch.

So any use-case will fall under this three categories. So let me explain how to use @JoinColumn and mappedBy.
1) Uni-directional mapping from Branch to Company.
Use JoinColumn in Branch table.
2) Bi-direction mapping from Company to Branch.
Use mappedBy in Company table as describe by @Mykhaylo Adamovych's answer.
3)Uni-directional mapping from Company to Branch.
Just use @JoinColumn in Company table.

@Entity
public class Company {

@OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY)
@JoinColumn(name="courseId")
private List<Branch> branches;
...
}

This says that in based on the foreign key "courseId" mapping in branches table, get me list of all branches. NOTE: you can't fetch company from branch in this case, only uni-directional mapping exist from company to branch.

What is the difference between association, aggregation and composition?

Problem with these answers is they are half the story: they explain that aggregation and composition are forms of association, but they don't say if it is possible for an association to be neither of those.

I gather based on some brief readings of many posts on SO and some UML docs that there are 4 main concrete forms of class association:

  1. composition: A is-composed-of-a B; B doesn't exist without A, like a room in a home
  2. aggregation: A has-a B; B can exist without A, like a student in a classroom
  3. dependency: A uses-a B; no lifecycle dependency between A and B, like a method call parameter, return value, or a temporary created during a method call
  4. generalization: A is-a B

When a relationship between two entities isn't one of these, it can just be called "an association" in the generic sense of the term, and further described other ways (note, stereotype, etc).

My guess is that the "generic association" is intended to be used primarily in two circumstances:

  • when the specifics of a relationship are still being worked out; such relationship in a diagram should be converted as soon as possible to what it actually is/will be (one of the other 4).
  • when a relationship doesn't match any of those 4 predetermined by UML; the "generic" association still gives you a way of representing a relationship that is "not one of the other ones", so that you aren't stuck using an incorrect relationship with a note "this is not actually aggregation, it's just that UML doesn't have any other symbol we could use"

Create an array with random values

function shuffle(maxElements) {
    //create ordered array : 0,1,2,3..maxElements
    for (var temArr = [], i = 0; i < maxElements; i++) {
        temArr[i] = i;
    }

    for (var finalArr = [maxElements], i = 0; i < maxElements; i++) {
        //remove rundom element form the temArr and push it into finalArrr
        finalArr[i] = temArr.splice(Math.floor(Math.random() * (maxElements - i)), 1)[0];
    }

    return finalArr
}

I guess this method will solve the issue with the probabilities, only limited by random numbers generator.

An existing connection was forcibly closed by the remote host

I had the same issue and managed to resolve it eventually. In my case, the port that the client sends the request to did not have a SSL cert binding to it. So I fixed the issue by binding a SSL cert to the port on the server side. Once that was done, this exception went away.

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

If you run Tomcat on Windows, you can use the neat "Tomcat Monitor" application that ships with Tomcat.

Go to the Java tab. At the bottom, below the "Java Options" textarea, you will find 3 input fields:

  • Initial memory pool ___ MB
  • Maximum memory pool ___ MB
  • Thread stack size _____ KB

Node.js quick file server (static files over HTTP)

One-line™ Proofs instead of promises

enter image description here

The first is http-server, hs - link

npm i -g http-server   // install
hs C:\repos            // run with one line?? FTW!!

The second is serve by ZEIT.co - link

npm i -g serve         // install
serve C:\repos         // run with one line?? FTW!!

Following are available options, if this is what helps you decide.

C:\Users\Qwerty>http-server --help
usage: http-server [path] [options]

options:
  -p           Port to use [8080]
  -a           Address to use [0.0.0.0]
  -d           Show directory listings [true]
  -i           Display autoIndex [true]
  -g --gzip    Serve gzip files when possible [false]
  -e --ext     Default file extension if none supplied [none]
  -s --silent  Suppress log messages from output
  --cors[=headers]   Enable CORS via the "Access-Control-Allow-Origin" header
                     Optionally provide CORS headers list separated by commas
  -o [path]    Open browser window after starting the server
  -c           Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.
               To disable caching, use -c-1.
  -U --utc     Use UTC time format in log messages.

  -P --proxy   Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com

  -S --ssl     Enable https.
  -C --cert    Path to ssl cert file (default: cert.pem).
  -K --key     Path to ssl key file (default: key.pem).

  -r --robots  Respond to /robots.txt [User-agent: *\nDisallow: /]
  -h --help    Print this list and exit.
C:\Users\Qwerty>serve --help

  Usage: serve.js [options] [command]

  Commands:

    help  Display help

  Options:

    -a, --auth      Serve behind basic auth
    -c, --cache     Time in milliseconds for caching files in the browser
    -n, --clipless  Don't copy address to clipboard (disabled by default)
    -C, --cors      Setup * CORS headers to allow requests from any origin (disabled by default)
    -h, --help      Output usage information
    -i, --ignore    Files and directories to ignore
    -o, --open      Open local address in browser (disabled by default)
    -p, --port   Port to listen on (defaults to 5000)
    -S, --silent    Don't log anything to the console
    -s, --single    Serve single page applications (sets `-c` to 1 day)
    -t, --treeless  Don't display statics tree (disabled by default)
    -u, --unzipped  Disable GZIP compression
    -v, --version   Output the version number

If you need to watch for changes, see hostr, credit Henry Tseng's answer

How to echo JSON in PHP

if you want to encode or decode an array from or to JSON you can use these functions

$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);

json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string

with json_decode you can take the results from the API and only output what you want, for example:

echo $myArray['payload']['ign'];

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

I had these exact symptoms and my issue was similar to Peter's. Was setting up an existing project on a new server. My project referenced the IIS7 URL Rewriting module, but that hadn't been installed yet on the new server. Installing it fixed my issue.

You can use the Microsoft Web Platform Installer to install it. Execute it, select Products, in the left menu select Server and find URL Rewrite in the list and install it.

Or you can download it here.

What does the "$" sign mean in jQuery or JavaScript?

The $ symbol simply invokes the jQuery library's selector functionality. So $("#Text") returns the jQuery object for the Text div which can then be modified.

Width of input type=text element

I think you are forgetting about the border. Having a one-pixel-wide border on the Div will take away two pixels of total length. Therefore it will appear as though the div is two pixels shorter than it actually is.

How to run batch file from network share without "UNC path are not supported" message?

I needed to be able to just Windows Explorer browse through the server share, then double-click launch the batch file. @dbenham led me to an easier solution for my scenario (without the popd worries):

:: Capture UNC or mapped-drive path script was launched from
set NetPath=%~dp0

:: Assumes that setup.exe is in the same UNC path
%NetPath%setup.exe

:: Note that NetPath has a trailing backslash ("\")
robocopy.exe "%NetPath%Custom" /copyall "C:\Program Files (x86)\WP\Custom Templates"
Regedit.exe /s %NetPath%..\WPX5\Custom\Migrate.reg

:: I am not sure if WPX5 was typo, so use ".." for parent directory
set NetPath=
pause

How to test if a DataSet is empty?

To check dataset is empty or not You have to check null and tables count.

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlString, sqlConn);
da.Fill(ds);
if(ds != null && ds.Tables.Count > 0)
{
 // your code
}

ASP.NET MVC on IIS 7.5

Please note for Windows 8 users you need to add/remove windows components and remove the version of .net reboot then re-install in order to register it with IIS. I presume this happens if you get .net 4.5 from visual studio and install IIS afterwards.

I get conflicting provisioning settings error when I try to archive to submit an iOS app

Try either of the following

1.Removing and adding ios platform and rebuild the project for ios

ionic cordova platform rm ios
ionic cordova platform add ios
ionic cordova build ios --release

2.Changing the Xcode Build Setting

The solution was to uncheck it, then check it again and reselect the Team. Xcode then fixed whatever was causing the issue on its own.

3.Change the following code in platform

This didn’t make any sense to me, since I had set the project to auto sign in xcode. Like you, the check and uncheck didn’t work. But then I read the last file path given and followed it. The file path is APP > Platforms > ios > Cordova > build-release.xconfig

And in the file, iPhone Distribution is explicitly set for CODE_SIGN_IDENTITY.

Change:

CODE_SIGN_IDENTITY = iPhone Distribution
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Distribution

To:

CODE_SIGN_IDENTITY = iPhone Developer
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Developer

How to create text file and insert data to that file on Android

I'm using Kotlin here

Just adding the information in here, you can also create readable file outside Private Directory for the apps by doing this example

var teks="your teks"
var NamaFile="Text1.txt"
var strwrt:FileWriter
 strwrt=FileWriter(File("sdcard/${NamaFile}"))
            strwrt.write(teks)
            strwrt.close()

after that you can acces File Manager and look up on the Internal Storage. Text1.txt will be on there below all the folder.

How to execute XPath one-liners from shell?

Since this project is apparently fairly new, check out https://github.com/jeffbr13/xq , seems to be a wrapper around lxml, but that is all you really need (and posted ad hoc solutions using lxml in other answers as well)

Django templates: If false?

In old version you can only use the ifequal or ifnotequal

{% ifequal YourVariable ExpectValue %}
    # Do something here.
{% endifequal %}

Example:

{% ifequal userid 1 %}
  Hello No.1
{% endifequal %}

{% ifnotequal username 'django' %}
  You are not django!
{% else %}
  Hi django!
{% endifnotequal %}

As in the if tag, an {% else %} clause is optional.

The arguments can be hard-coded strings, so the following is valid:

{% ifequal user.username "adrian" %} ... {% endifequal %} An alternative to the ifequal tag is to use the if tag and the == operator.

ifnotequal Just like ifequal, except it tests that the two arguments are not equal.

An alternative to the ifnotequal tag is to use the if tag and the != operator.

However, now we can use if/else easily

{% if somevar >= 1 %}
{% endif %}

{% if "bc" in "abcdef" %}
  This appears since "bc" is a substring of "abcdef"
{% endif %}

Complex expressions

All of the above can be combined to form complex expressions. For such expressions, it can be important to know how the operators are grouped when the expression is evaluated - that is, the precedence rules. The precedence of the operators, from lowest to highest, is as follows:

  • or
  • and
  • not
  • in
  • ==, !=, <, >, <=, >=

More detail

https://docs.djangoproject.com/en/dev/ref/templates/builtins/

How to debug .htaccess RewriteRule not working

Generally any change in the .htaccess should have visible effects. If no effect, check your configuration apache files, something like:

<Directory ..>
    ...
    AllowOverride None
    ...
</Directory>

Should be changed to

AllowOverride All

And you'll be able to change directives in .htaccess files.

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

You are converting cert into BKS Keystore, why aren't you using .cert directly, from https://developer.android.com/training/articles/security-ssl.html:

CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream instream = context.getResources().openRawResource(R.raw.gtux_cert);
Certificate ca;
try {
    ca = cf.generateCertificate(instream);
} finally {
    caInput.close();
}

KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
kStore.load(null, null);
kStore.setCertificateEntry("ca", ca);

TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(););
tmf.init(kStore);

SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);

okHttpClient.setSslSocketFactory(context.getSocketFactory());

How do I iterate through children elements of a div using jQuery?

If you need to loop through child elements recursively:

function recursiveEach($element){
    $element.children().each(function () {
        var $currentElement = $(this);
        // Show element
        console.info($currentElement);
        // Show events handlers of current element
        console.info($currentElement.data('events'));
        // Loop her children
        recursiveEach($currentElement);
    });
}

// Parent div
recursiveEach($("#div"));   

NOTE: In this example I show the events handlers registered with an object.

Storage permission error in Marshmallow

After lots of searching This code work for me:

Check the permission already has: Check WRITE_EXTERNAL_STORAGE permission Allowed or not?

if(isReadStorageAllowed()){
            //If permission is already having then showing the toast
            //Toast.makeText(SplashActivity.this,"You already have the permission",Toast.LENGTH_LONG).show();
            //Existing the method with return
            return;
        }else{
            requestStoragePermission();
        }



private boolean isReadStorageAllowed() {
    //Getting the permission status
    int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);

    //If permission is granted returning true
    if (result == PackageManager.PERMISSION_GRANTED)
        return true;

    //If permission is not granted returning false
    return false;
}

//Requesting permission
private void requestStoragePermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)){
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_STORAGE);
}

Implement Override onRequestPermissionsResult method for checking is the user allow or denie

 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    //Checking the request code of our request
    if(requestCode == REQUEST_WRITE_STORAGE){

        //If permission is granted
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

            //Displaying a toast
            Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();

        }else{
            //Displaying another toast if permission is not granted
            Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
        }
    }

how to add key value pair in the JSON object already declared

You can use dot notation or bracket notation ...

var obj = {};
obj = {
  "1": "aa",
  "2": "bb"
};

obj.another = "valuehere";
obj["3"] = "cc";

How to convert an array into an object using stdClass()

The quick and dirty way is using json_encode and json_decode which will turn the entire array (including sub elements) into an object.

$clasa = json_decode(json_encode($clasa)); //Turn it into an object

The same can be used to convert an object into an array. Simply add , true to json_decode to return an associated array:

$clasa = json_decode(json_encode($clasa), true); //Turn it into an array

An alternate way (without being dirty) is simply a recursive function:

function convertToObject($array) {
    $object = new stdClass();
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $value = convertToObject($value);
        }
        $object->$key = $value;
    }
    return $object;
}

or in full code:

<?php
    function convertToObject($array) {
        $object = new stdClass();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = convertToObject($value);
            }
            $object->$key = $value;
        }
        return $object;
    }

    $clasa = array(
            'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
            'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
            'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
            'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
            'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
    );

    $obj = convertToObject($clasa);
    print_r($obj);
?>

which outputs (note that there's no arrays - only stdClass's):

stdClass Object
(
    [e1] => stdClass Object
        (
            [nume] => Nitu
            [prenume] => Andrei
            [sex] => m
            [varsta] => 23
        )

    [e2] => stdClass Object
        (
            [nume] => Nae
            [prenume] => Ionel
            [sex] => m
            [varsta] => 27
        )

    [e3] => stdClass Object
        (
            [nume] => Noman
            [prenume] => Alice
            [sex] => f
            [varsta] => 22
        )

    [e4] => stdClass Object
        (
            [nume] => Geangos
            [prenume] => Bogdan
            [sex] => m
            [varsta] => 23
        )

    [e5] => stdClass Object
        (
            [nume] => Vasile
            [prenume] => Mihai
            [sex] => m
            [varsta] => 25
        )

)

So you'd refer to it by $obj->e5->nume.

DEMO

Getting multiple values with scanf()

Could do this, but then the user has to separate the numbers by a space:

#include "stdio.h"

int main()
{
    int minx, x, y, z;

    printf("Enter four ints: ");
    scanf( "%i %i %i %i", &minx, &x, &y, &z);

    printf("You wrote: %i %i %i %i", minx, x, y, z);
}

NodeJS - Error installing with NPM

I encountered the issue with the error:

gyp ERR! configure error

gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.

Here is what I was doing and what finally worked.

Disclaimer: I am just getting my hands into Node, Angular after many years in the Java, Linux world among others...

Environment Description: Windows 8.1 64-bit; Cygwin; cygwin bash shell

Command used that led to error: npm install -g karma

Error: gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT HON env variable.

Discovery: 'which python' on bash shell clearly shows '/usr/bin/python'. Now that is annoying!

Solution: This is only applicable to those using the environment similar to what I have, i.e. using cygwin and bash shell. Hope it helps in other environments as well but keep in mind that your kettle of tea may look a little different than mine.

  1. Firstly, need to set the $PYTHON shell env variable in .bashrc using the explicit windows path to the python executable and not the unix like root path (/usr/bin) used by cygwin.
  2. Secondly, and this one took a lot of trial/error and here's the gotcha! Cygwin installs python under /usr/bin (which is really a mirror of /bin on windows) with the version, i.e. (in my system) /usr/bin/python2.7.exe and then adds a link /usr/bin/python --> python2.7.exe. The problem is that gyp cannot follow this link and keeps giving the annoying error that it cannot find python even though you can find it just fine from the shell command line.
  3. With the above background now add the following line to your .bashrc

export PYTHON="C:/cygwin64/bin/python2.7.exe (or whatever is the version on your system)"

  1. Now source your .bashrc from your home directory (on cygwin)--> 'source .bashrc'

You should be fine now and gyp will find the python executable.

I hope this helps someone stumbling on the same or similar issue.

What does $_ mean in PowerShell?

This is the variable for the current value in the pipe line, which is called $PSItem in Powershell 3 and newer.

1,2,3 | %{ write-host $_ } 

or

1,2,3 | %{ write-host $PSItem } 

For example in the above code the %{} block is called for every value in the array. The $_ or $PSItem variable will contain the current value.

Equivalent of Clean & build in Android Studio?

I don't know if there's a way to get a clean build via the UI, but it's easy to do from the commandline using gradle wrapper. From the root directory of your project:

./gradlew clean 

Default instance name of SQL Server Express

You're right, it's localhost\SQLEXPRESS (just no $) and yes, it's the same for both 2005 and 2008 express versions.

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

Here is the screen print showing the options to ignore the file or folder after the installation of the .ignore plugin. The generated file name would be .gitignore enter image description here

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

How to debug apk signed for release?

In case of you decided the debug your apk which is already in market but not assigned to be debuggable and you do not want to publish it again. So follow the below steps;

  1. Decompile the Apk with ApkTool(eg. apktool d <APK_PATH>)
  2. Open the AndroidManifest.xml from decompiled files
  3. Set android:debuggable="true" in application tag
  4. Compile the modified source with ApkTool (eg. apktool b <MODIFIED_PATH>)
  5. Debuggable apk ready(which unsigned means cannot publish store). You can debug as you wish.

Compiling LaTex bib source

You have to run 'bibtex':

latex paper.tex
bibtex paper
latex paper.tex
latex paper.tex
dvipdf paper.dvi

Git merge without auto commit

If you only want to commit all the changes in one commit as if you typed yourself, --squash will do too

$ git merge --squash v1.0
$ git commit

How to maximize a plt.show() window using Python

Try plt.figure(figsize=(6*3.13,4*3.13)) to make the plot larger.

jQuery equivalent of JavaScript's addEventListener method

_x000D_
_x000D_
$( "button" ).on( "click", function(event) {_x000D_
_x000D_
    alert( $( this ).html() );_x000D_
    console.log( event.target );_x000D_
_x000D_
} );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
_x000D_
<button>test 1</button>_x000D_
<button>test 2</button>
_x000D_
_x000D_
_x000D_

How to get value of checked item from CheckedListBox?

You may try this :

string s = "";

foreach(DataRowView drv in checkedListBox1.CheckedItems)
{
    s += drv[0].ToString()+",";
}
s=s.TrimEnd(',');

How to create a user in Django?

Bulk user creation with set_password

I you are creating several test users, bulk_create is much faster, but we can't use create_user with it.

set_password is another way to generate the hashed passwords:

def users_iterator():
    for i in range(nusers):
        is_superuser = (i == 0)
        user = User(
            first_name='First' + str(i),
            is_staff=is_superuser,
            is_superuser=is_superuser,
            last_name='Last' + str(i),
            username='user' + str(i),
        )
        user.set_password('asdfqwer')
        yield user

class Command(BaseCommand):
    def handle(self, **options):
        User.objects.bulk_create(iter(users_iterator()))

Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django

Tested in Django 1.9.

How to convert date in to yyyy-MM-dd Format?

UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..

Joda-Time

The accepted answer by NidhishKrishnan is correct.

For fun, here is the same kind of code in Joda-Time 2.3.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

java.util.Date date = new Date(); // A Date object coming from other code.

// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );

DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );

When run…

dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30

How to change Named Range Scope

This still needs more refining however works with all simple references, without killing existing local names.

Type GlobalNamesToLocalNames_Type
   Name As String
   Sheet As String
   Ref As String
End Type

Sub GlobalNamesToLocalNames(Optional Void As Variant)
   Dim List() As GlobalNamesToLocalNames_Type
   Dim Count As Long
   Dim Name As Name
   Dim Dat() As String
   Dim X As Long

   ' count the size
   For Each Name In ActiveWorkbook.Names
      Count = Count + 1
   Next
   ReDim List(Count - 1)
   Count = 0

   ' Collecect all name data
   For Each Name In ActiveWorkbook.Names
      With List(Count)
         ' Pick up only the name
         If InStr(Name.Name, "!") > 0 Then
            Dat = Split(Name.Name, "!")
            .Name = Dat(1)
         Else
            .Name = Name.Name
         End If
         ' pick up the sheet and refer
         Dat = Split(Name.RefersTo, "!")
         .Sheet = Mid(Dat(0), 2)
         .Ref = Dat(1)
         ' make local sheet name
         .Name = .Sheet & "!" & .Name
      End With
      Count = Count + 1
   Next

   ' Delete all names
   For Each Name In ActiveWorkbook.Names
      Name.Delete
   Next

   'rebuild all the names
   For X = 0 To Count - 1
      With List(X)
         If Left(.Ref, 1) <> "#" Then
            ActiveWorkbook.Names.Add Name:=.Name, RefersToLocal:="=" & .Sheet & "!" & .Ref
         End If
      End With
   Next
End Sub

PivotTable's Report Filter using "greater than"

Maybe in your data source add a column which does a sumif over all rows. Not sure what your data looks like but something like =(sumif([column holding pivot row heads),[current row head value in row], probability column)>.2). This will give you a True when the pivot table will show >20%.
Then add a filter on your pivot table on this column for TRUE values

Read a plain text file with php

$your_variable = file_get_contents("file_to_read.txt");

pandas three-way joining multiple dataframes on columns

In python 3.6.3 with pandas 0.22.0 you can also use concat as long as you set as index the columns you want to use for the joining

pd.concat(
    (iDF.set_index('name') for iDF in [df1, df2, df3]),
    axis=1, join='inner'
).reset_index()

where df1, df2, and df3 are defined as in John Galt's answer

import pandas as pd
df1 = pd.DataFrame(np.array([
    ['a', 5, 9],
    ['b', 4, 61],
    ['c', 24, 9]]),
    columns=['name', 'attr11', 'attr12']
)
df2 = pd.DataFrame(np.array([
    ['a', 5, 19],
    ['b', 14, 16],
    ['c', 4, 9]]),
    columns=['name', 'attr21', 'attr22']
)
df3 = pd.DataFrame(np.array([
    ['a', 15, 49],
    ['b', 4, 36],
    ['c', 14, 9]]),
    columns=['name', 'attr31', 'attr32']
)

Using :focus to style outer div?

While this can't be achieved with CSS/HTML alone, it can be achieved with JavaScript (without need of a library):

var textareas = document.getElementsByTagName('textarea');

for (i=0;i<textareas.length;i++){
    // you can omit the 'if' if you want to style the parent node regardless of its
    // element type
    if (textareas[i].parentNode.tagName.toString().toLowerCase() == 'div') {
        textareas[i].onfocus = function(){
            this.parentNode.style.borderStyle = 'solid';
        }
        textareas[i].onblur = function(){
            this.parentNode.style.borderStyle = 'dashed';
        }
    }
}

JS Fiddle demo.

Incidentally, with a library, such as jQuery, the above could be condensed down to:

$('textarea').focus(
    function(){
        $(this).parent('div').css('border-style','solid');
    }).blur(
    function(){
        $(this).parent('div').css('border-style','dashed');
    });

JS Fiddle demo.

References:

Django - "no module named django.core.management"

You must choose your Project first before running the server , type this workon your_project_name then python manage.py runserver

How to copy a file to another path?

Old Question,but I would like to add complete Console Application example, considering you have files and proper permissions for the given folder, here is the code

 class Program
 {
    static void Main(string[] args)
    {
        //path of file
        string pathToOriginalFile = @"E:\C-sharp-IO\test.txt";

        
        //duplicate file path 
        string PathForDuplicateFile = @"E:\C-sharp-IO\testDuplicate.txt";
         
          //provide source and destination file paths
        File.Copy(pathToOriginalFile, PathForDuplicateFile);

        Console.ReadKey();

    }
}

Source: File I/O in C# (Read, Write, Delete, Copy file using C#)

Android Studio and Gradle build error

If you are using the Gradle Wrapper (the recommended option in Android Studio), you enable stacktrace by running gradlew compileDebug --stacktrace from the command line in the root folder of your project (where the gradlew file is).

If you are not using the gradle wrapper, you use gradle compileDebug --stacktrace instead (presumably).

You don't really need to run with --stacktrace though, running gradlew compileDebug by itself, from the command line, should tell you where the error is.

I based this information on this comment:

Android Studio new project can not run, throwing error

How to make 'submit' button disabled?

Here is a working example (you'll have to trust me that there's a submit() method on the controller - it prints an Object, like {user: 'abc'} if 'abc' is entered in the input field):

<form #loginForm="ngForm" (ngSubmit)="submit(loginForm.value)">
    <input type="text" name="user" ngModel required>
    <button  type="submit"  [disabled]="loginForm.invalid">
        Submit
    </button>
</form>

As you can see:

  • don't use loginForm.form, just use loginForm
  • loginForm.invalid works as well as !loginForm.valid
  • if you want submit() to be passed the correct value(s), the input element should have name and ngModel attributes

Also, this is when you're NOT using the new FormBuilder, which I recommend. Things are very different when using FormBuilder.

Add a new element to an array without specifying the index in Bash

As Dumb Guy points out, it's important to note whether the array starts at zero and is sequential. Since you can make assignments to and unset non-contiguous indices ${#array[@]} is not always the next item at the end of the array.

$ array=(a b c d e f g h)
$ array[42]="i"
$ unset array[2]
$ unset array[3]
$ declare -p array     # dump the array so we can see what it contains
declare -a array='([0]="a" [1]="b" [4]="e" [5]="f" [6]="g" [7]="h" [42]="i")'
$ echo ${#array[@]}
7
$ echo ${array[${#array[@]}]}
h

Here's how to get the last index:

$ end=(${!array[@]})   # put all the indices in an array
$ end=${end[@]: -1}    # get the last one
$ echo $end
42

That illustrates how to get the last element of an array. You'll often see this:

$ echo ${array[${#array[@]} - 1]}
g

As you can see, because we're dealing with a sparse array, this isn't the last element. This works on both sparse and contiguous arrays, though:

$ echo ${array[@]: -1}
i

PHP Curl UTF-8 Charset

I was fetching a windows-1252 encoded file via cURL and the mb_detect_encoding(curl_exec($ch)); returned UTF-8. Tried utf8_encode(curl_exec($ch)); and the characters were correct.

How to resolve "Server Error in '/' Application" error?

I just had the same issue on visual studio 2012. For a internet application project. How to resolve “Server Error in '/' Application” error?

Searching for answer I came across this post, but none of these answer help me. Than I found another post here on stackoverflow that has the answer for resolving this issue. Specified argument was out of the range of valid values. Parameter name: site

Variable is accessed within inner class. Needs to be declared final

If you don't want to make it final, you can always just make it a global variable.

How to use random in BATCH script?

@echo off & setLocal EnableDelayedExpansion

for /L %%a in (1 1 100) do (
echo !random!
)

What are the differences between ArrayList and Vector?

ArrayList is newer and 20-30% faster.

If you don't need something explitly apparent in Vector, use ArrayList

Call a React component method from outside

I've done something like this:

class Cow extends React.Component {

    constructor (props) {
        super(props);
        this.state = {text: 'hello'};
    }

    componentDidMount () {
        if (this.props.onMounted) {
            this.props.onMounted({
                say: text => this.say(text)
            });
        }
    }

    render () {
        return (
            <pre>
                 ___________________
                < {this.state.text} >
                 -------------------
                        \   ^__^
                         \  (oo)\_______
                            (__)\       )\/\
                                ||----w |
                                ||     ||
            </pre>
        );
    }

    say (text) {
        this.setState({text: text});
    }

}

And then somewhere else:

class Pasture extends React.Component {

    render () {
        return (
            <div>
                <Cow onMounted={callbacks => this.cowMounted(callbacks)} />
                <button onClick={() => this.changeCow()} />
            </div>
        );
    }

    cowMounted (callbacks) {
        this.cowCallbacks = callbacks;
    }

    changeCow () {
        this.cowCallbacks.say('moo');
    }

}

I haven't tested this exact code, but this is along the lines of what I did in a project of mine and it works nicely :). Of course this is a bad example, you should just use props for this, but in my case the sub-component did an API call which I wanted to keep inside that component. In such a case this is a nice solution.

How does the Spring @ResponseBody annotation work?

First of all, the annotation doesn't annotate List. It annotates the method, just as RequestMapping does. Your code is equivalent to

@RequestMapping(value="/orders", method=RequestMethod.GET)
@ResponseBody
public List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

Now what the annotation means is that the returned value of the method will constitute the body of the HTTP response. Of course, an HTTP response can't contain Java objects. So this list of accounts is transformed to a format suitable for REST applications, typically JSON or XML.

The choice of the format depends on the installed message converters, on the values of the produces attribute of the @RequestMapping annotation, and on the content type that the client accepts (that is available in the HTTP request headers). For example, if the request says it accepts XML, but not JSON, and there is a message converter installed that can transform the list to XML, then XML will be returned.

How can I cast int to enum?

Sometimes you have an object to the MyEnum type. Like

var MyEnumType = typeof(MyEnum);

Then:

Enum.ToObject(typeof(MyEnum), 3)

Get folder name of the file in Python

I'm using 2 ways to get the same response: one of them use:

   os.path.basename(filename)

due to errors that I found in my script I changed to:

Path = filename[:(len(filename)-len(os.path.basename(filename)))]

it's a workaround due to python's '\\'

How can I move a tag on a git branch to a different commit?

If you want to move an annotated tag, changing only the targeted commit but preserving the annotation message and other metadata use:

moveTag() {
  local tagName=$1
  # Support passing branch/tag names (not just full commit hashes)
  local newTarget=$(git rev-parse $2^{commit})

  git cat-file -p refs/tags/$tagName | 
    sed "1 s/^object .*$/object $newTarget/g" | 
    git hash-object -w --stdin -t tag | 
    xargs -I {} git update-ref refs/tags/$tagName {}
}

usage: moveTag <tag-to-move> <target>

The above function was developed by referencing teerapap/git-move-annotated-tag.sh.

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

When your function is deterministic, you are safe to declare it to be deterministic. The location of "DETERMINISTIC" keyword is as follows.

enter image description here

What encoding/code page is cmd.exe using?

Type

chcp

to see your current code page (as Dewfy already said).

Use

nlsinfo

to see all installed code pages and find out what your code page number means.

You need to have Windows Server 2003 Resource kit installed (works on Windows XP) to use nlsinfo.

Copy Paste in Bash on Ubuntu on Windows

Edit / Paste from the title bar's context menu (until they fix the control key shortcuts)

Logging framework incompatibility

You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.

pythonw.exe or python.exe?

See here: http://docs.python.org/using/windows.html

pythonw.exe "This suppresses the terminal window on startup."

what does "dead beef" mean?

It is also used for debugging purposes.

Here is a handy list of some of these values:

http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Magic_debug_values