Programs & Examples On #Cgpdfcontext

Pandas - How to flatten a hierarchical index in columns

You could also do as below. Consider df to be your dataframe and assume a two level index (as is the case in your example)

df.columns = [(df.columns[i][0])+'_'+(datadf_pos4.columns[i][1]) for i in range(len(df.columns))]

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

Java Regex Replace with Capturing Group

Source: java-implementation-of-rubys-gsub

Usage:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

Implementation (redesigned):

import static java.lang.String.format;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

Finding the direction of scrolling in a UIScrollView?

In iOS8 Swift I used this method:

override func scrollViewDidScroll(scrollView: UIScrollView){

    var frame: CGRect = self.photoButton.frame
    var currentLocation = scrollView.contentOffset.y

    if frame.origin.y > currentLocation{
        println("Going up!")
    }else if frame.origin.y < currentLocation{
        println("Going down!")
    }

    frame.origin.y = scrollView.contentOffset.y + scrollHeight
    photoButton.frame = frame
    view.bringSubviewToFront(photoButton)

}

I have a dynamic view which changes locations as the user scrolls so the view can seem like it stayed in the same place on the screen. I am also tracking when user is going up or down.

Here is also an alternative way:

func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    if targetContentOffset.memory.y < scrollView.contentOffset.y {
        println("Going up!")
    } else {
        println("Going down!")
    }
}

What is the use of join() in Python threading?

The method join()

blocks the calling thread until the thread whose join() method is called is terminated.

Source : http://docs.python.org/2/library/threading.html

stale element reference: element is not attached to the page document

Use this code:

public class LinkTest 
{   
    public static void main(String[] args) 
    {
        WebDriver driver = new FirefoxDriver();
        driver.navigate().to("file:///C:/Users/vkiran/Desktop/xyz.html");
        List<WebElement> alllinks =driver.findElements(By.xpath("//*[@id='sliding-navigation']//a"));
        String a[]=new String[alllinks.size()];
        for(int i=0;i<alllinks.size();i++)
        {
            a[i]=alllinks.get(i).getText(); 
            if(a[i].startsWith("B"))
            {
                System.out.println("clicking on this link::"+driver.findElement(By.linkText(a[i])).getText());
                driver.findElement(By.linkText(a[i])).click();  

            }
            else
            {
                System.out.println("does not starts with B so not clicking");
            }
        }
}
}

Bash script to cd to directory with spaces in pathname

When you double-quote a path, you're stopping the tilde expansion. So there are a few ways to do this:

cd ~/"My Code"
cd ~/'My Code'

The tilde is not quoted here, so tilde expansion will still be run.

cd "$HOME/My Code"

You can expand environment variables inside double-quoted strings; this is basically what the tilde expansion is doing

cd ~/My\ Code

You can also escape special characters (such as space) with a backslash.

Explicitly set column value to null SQL Developer

It is clear that most people who haven't used SQL Server Enterprise Manager don't understand the question (i.e. Justin Cave).

I came upon this post when I wanted to know the same thing.

Using SQL Server, when you are editing your data through the MS SQL Server GUI Tools, you can use a KEYBOARD SHORTCUT to insert a NULL rather than having just an EMPTY CELL, as they aren't the same thing. An empty cell can have a space in it, rather than being NULL, even if it is technically empty. The difference is when you intentionally WANT to put a NULL in a cell rather than a SPACE or to empty it and NOT using a SQL statement to do so.

So, the question really is, how do I put a NULL value in the cell INSTEAD of a space to empty the cell?

I think the answer is, that the way the Oracle Developer GUI works, is as Laniel indicated above, And THAT should be marked as the answer to this question.

Oracle Developer seems to default to NULL when you empty a cell the way the op is describing it.

Additionally, you can force Oracle Developer to change how your null cells look by changing the color of the background color to further demonstrate when a cell holds a null:

Tools->Preferences->Advanced->Display Null Using Background Color

or even the VALUE it shows when it's null:

Tools->Preferences->Advanced->Display Null Value As

Hope that helps in your transition.

How to do a PUT request with curl?

Quick Answer:

In a single line, the curl command would be:

a) If sending form data:

curl -X PUT -H "Content-Type: multipart/form-data;" -F "key1=val1" "YOUR_URI"

b) If sending raw data as json:

curl -X PUT -H "Content-Type: application/json" -d '{"key1":"value"}' "YOUR_URI"

c) If sending a file with a POST request:

curl -X POST "YOUR_URI" -F 'file=@/file-path.csv'

Alternative solution:

You can use the POSTMAN app from Chrome Store to get the equivalent cURL request. This is especially useful when writing more complicated requests.

For the request with other formats or for different clients like java, PHP, you can check out POSTMAN/comment below.

POSTMAN to get the request code

Dynamic variable names in Bash

Use declare

There is no need on using prefixes like on other answers, neither arrays. Use just declare, double quotes, and parameter expansion.

I often use the following trick to parse argument lists contanining one to n arguments formatted as key=value otherkey=othervalue etc=etc, Like:

# brace expansion just to exemplify
for variable in {one=foo,two=bar,ninja=tip}
do
  declare "${variable%=*}=${variable#*=}"
done
echo $one $two $ninja 
# foo bar tip

But expanding the argv list like

for v in "$@"; do declare "${v%=*}=${v#*=}"; done

Extra tips

# parse argv's leading key=value parameters
for v in "$@"; do
  case "$v" in ?*=?*) declare "${v%=*}=${v#*=}";; *) break;; esac
done
# consume argv's leading key=value parameters
while (( $# )); do
  case "$v" in ?*=?*) declare "${v%=*}=${v#*=}";; *) break;; esac
  shift
done

How to write MySQL query where A contains ( "a" or "b" )

I've used most of the times the LIKE option and it works just fine. I just like to share one of my latest experiences where I used INSTR function. Regardless of the reasons that made me consider this options, what's important here is that the use is similar: instr(A, 'text 1') > 0 or instr(A, 'text 2') > 0 Another option could be: (instr(A, 'text 1') + instr(A, 'text 2')) > 0

I'd go with the LIKE '%text1%' OR LIKE '%text2%' option... if not hope this other option helps

How do I reference a local image in React?

const photo = require(`../../uploads/images/${obj.photo}`).default;
...
<img src={photo} alt="user_photo" />

Loop through properties in JavaScript object with Lodash

It would be helpful to understand why you need to do this with lodash. If you just want to check if a key exists in an object, you don't need lodash.

myObject.options.hasOwnProperty('property');

If your looking to see if a value exists, you can use _.invert

_.invert(myObject.options)[value]

How to update array value javascript?

If you want to reassign an element in an array, you can do the following:

var blah = ['Jan', 'Fed', 'Apr'];

console.log(blah);

function reassign(array, index, newValue) {
    array[index] = newValue;
    return array;
}

reassign(blah, [2], 'Mar');

Is there a concurrent List in Java's JDK?

If you never plan to delete elements from the list (since this requires changing the index of all elements after the deleted element), then you can use ConcurrentSkipListMap<Integer, T> in place of ArrayList<T>, e.g.

NavigableMap<Integer, T> map = new ConcurrentSkipListMap<>();

This will allow you to add items to the end of the "list" as follows, as long as there is only one writer thread (otherwise there is a race condition between map.size() and map.put()):

// Add item to end of the "list":
map.put(map.size(), item);

You can also obviously modify the value of any item in the "list" (i.e. the map) by simply calling map.put(index, item).

The average cost for putting items into the map or retrieving them by index is O(log(n)), and ConcurrentSkipListMap is lock-free, which makes it significantly better than say Vector (the old synchronized version of ArrayList).

You can iterate back and forth through the "list" by using the methods of the NavigableMap interface.

You could wrap all the above into a class that implements the List interface, as long as you understand the race condition caveats (or you could synchronize just the writer methods) -- and you would need to throw an unsupported operation exception for the remove methods. There's quite a bit of boilerplate needed to implement all the required methods, but here's a quick attempt at an implementation.

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;

public class ConcurrentAddOnlyList<V> implements List<V> {
    private NavigableMap<Integer, V> map = new ConcurrentSkipListMap<>();

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return map.values().contains(o);
    }

    @Override
    public Iterator<V> iterator() {
        return map.values().iterator();
    }

    @Override
    public Object[] toArray() {
        return map.values().toArray();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return map.values().toArray(a);
    }

    @Override
    public V get(int index) {
        return map.get(index);
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return map.values().containsAll(c);
    }

    @Override
    public int indexOf(Object o) {
        for (Entry<Integer, V> ent : map.entrySet()) {
            if (Objects.equals(ent.getValue(), o)) {
                return ent.getKey();
            }
        }
        return -1;
    }

    @Override
    public int lastIndexOf(Object o) {
        for (Entry<Integer, V> ent : map.descendingMap().entrySet()) {
            if (Objects.equals(ent.getValue(), o)) {
                return ent.getKey();
            }
        }
        return -1;
    }

    @Override
    public ListIterator<V> listIterator(int index) {
        return new ListIterator<V>() {
            private int currIdx = 0;

            @Override
            public boolean hasNext() {
                return currIdx < map.size();
            }

            @Override
            public V next() {
                if (currIdx >= map.size()) {
                    throw new IllegalArgumentException(
                            "next() called at end of list");
                }
                return map.get(currIdx++);
            }

            @Override
            public boolean hasPrevious() {
                return currIdx > 0;
            }

            @Override
            public V previous() {
                if (currIdx <= 0) {
                    throw new IllegalArgumentException(
                            "previous() called at beginning of list");
                }
                return map.get(--currIdx);
            }

            @Override
            public int nextIndex() {
                return currIdx + 1;
            }

            @Override
            public int previousIndex() {
                return currIdx - 1;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }

            @Override
            public void set(V e) {
                // Might change size of map if currIdx == map.size(),
                // so need to synchronize 
                synchronized (map) {
                    map.put(currIdx, e);
                }
            }

            @Override
            public void add(V e) {
                synchronized (map) {
                    // Insertion is not supported except at end of list
                    if (currIdx < map.size()) {
                        throw new UnsupportedOperationException();
                    }
                    map.put(currIdx++, e);
                }
            }
        };
    }

    @Override
    public ListIterator<V> listIterator() {
        return listIterator(0);
    }

    @Override
    public List<V> subList(int fromIndex, int toIndex) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean add(V e) {
        synchronized (map) {
            map.put(map.size(), e);
            return true;
        }
    }

    @Override
    public boolean addAll(Collection<? extends V> c) {
        synchronized (map) {
            for (V val : c) {
                add(val);
            }
            return true;
        }
    }

    @Override
    public V set(int index, V element) {
        synchronized (map) {
            if (index < 0 || index > map.size()) {
                throw new IllegalArgumentException("Index out of range");
            }
            return map.put(index, element);
        }
    }

    @Override
    public void clear() {
        synchronized (map) {
            map.clear();
        }
    }

    @Override
    public synchronized void add(int index, V element) {
        synchronized (map) {
            if (index < map.size()) {
                // Insertion is not supported except at end of list
                throw new UnsupportedOperationException();
            } else if (index < 0 || index > map.size()) {
                throw new IllegalArgumentException("Index out of range");
            }
            // index == map.size()
            add(element);
        }
    }

    @Override
    public synchronized boolean addAll(
            int index, Collection<? extends V> c) {
        synchronized (map) {
            if (index < map.size()) {
                // Insertion is not supported except at end of list
                throw new UnsupportedOperationException();
            } else if (index < 0 || index > map.size()) {
                throw new IllegalArgumentException("Index out of range");
            }
            // index == map.size()
            for (V val : c) {
                add(val);
            }
            return true;
        }
    }

    @Override
    public boolean remove(Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public V remove(int index) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        throw new UnsupportedOperationException();
    }
}

Don't forget that even with the writer thread synchronization as shown above, you need to be careful not to run into race conditions that might cause you to drop items, if for example you try to iterate through a list in a reader thread while a writer thread is adding to the end of the list.

You can even use ConcurrentSkipListMap as a double-ended list, as long as you don't need the key of each item to represent the actual position within the list (i.e. adding to the beginning of the list will assign items negative keys). (The same race condition caveat applies here, i.e. there should be only one writer thread.)

// Add item after last item in the "list":
map.put(map.isEmpty() ? 0 : map.lastKey() + 1, item);

// Add item before first item in the "list":
map.put(map.isEmpty() ? 0 : map.firstKey() - 1, item);

How to change scroll bar position with CSS?

Here is another way, by rotating element with the scrollbar for 180deg, wrapping it's content into another element, and rotating that wrapper for -180deg. Check the snippet below

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 2px solid black;_x000D_
  margin: 15px;_x000D_
}_x000D_
#vertical {_x000D_
  direction: rtl;_x000D_
  overflow-y: scroll;_x000D_
  overflow-x: hidden;_x000D_
  background: gold;_x000D_
}_x000D_
#vertical p {_x000D_
  direction: ltr;_x000D_
  margin-bottom: 0;_x000D_
}_x000D_
#horizontal {_x000D_
  direction: rtl;_x000D_
  transform: rotate(180deg);_x000D_
  overflow-y: hidden;_x000D_
  overflow-x: scroll;_x000D_
  background: tomato;_x000D_
  padding-top: 30px;_x000D_
}_x000D_
#horizontal span {_x000D_
  direction: ltr;_x000D_
  display: inline-block;_x000D_
  transform: rotate(-180deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id=vertical>_x000D_
  <p>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content</p>_x000D_
</div>_x000D_
<div id=horizontal><span> content_content_content_content_content_content_content_content_content_content_content_content_content_content</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

To resolve this, you should open up a terminal window and type this command:

sudo chown -R user ~/.composer (with user being your current user, in your case, kramer65)

After you have ran this command, you should have permission to run your composer global require command.

You may also need to remove the .composer file from the current directory, to do this open up a terminal window and type this command:

sudo rm -rf .composer

Alter and Assign Object Without Side Effects

You will have the same object two times in your array, because object values are passed by reference. You have to create a new object like this

myElement.id = 244;
myElement.value = 3556;
myArray[0] = $.extend({}, myElement); //for shallow copy or
myArray[0] = $.extend(true, {}, myElement); // for deep copy

or

myArray.push({ id: 24, value: 246 });

ToList().ForEach in Linq

you want this?

    employees.ForEach(emp =>
    {
        collection.AddRange(emp.Departments.Where(dept => { dept.SomeProperty = null; return true; }));
    });

How can I count the number of children?

Try to get using:

var count = $("ul > li").size();
alert(count);

Alternative to mysql_real_escape_string without connecting to DB

From further research, I've found:

http://dev.mysql.com/doc/refman/5.1/en/news-5-1-11.html

Security Fix:

An SQL-injection security hole has been found in multi-byte encoding processing. The bug was in the server, incorrectly parsing the string escaped with the mysql_real_escape_string() C API function.

This vulnerability was discovered and reported by Josh Berkus and Tom Lane as part of the inter-project security collaboration of the OSDB consortium. For more information about SQL injection, please see the following text.

Discussion. An SQL injection security hole has been found in multi-byte encoding processing. An SQL injection security hole can include a situation whereby when a user supplied data to be inserted into a database, the user might inject SQL statements into the data that the server will execute. With regards to this vulnerability, when character set-unaware escaping is used (for example, addslashes() in PHP), it is possible to bypass the escaping in some multi-byte character sets (for example, SJIS, BIG5 and GBK). As a result, a function such as addslashes() is not able to prevent SQL-injection attacks. It is impossible to fix this on the server side. The best solution is for applications to use character set-aware escaping offered by a function such mysql_real_escape_string().

However, a bug was detected in how the MySQL server parses the output of mysql_real_escape_string(). As a result, even when the character set-aware function mysql_real_escape_string() was used, SQL injection was possible. This bug has been fixed.

Workarounds. If you are unable to upgrade MySQL to a version that includes the fix for the bug in mysql_real_escape_string() parsing, but run MySQL 5.0.1 or higher, you can use the NO_BACKSLASH_ESCAPES SQL mode as a workaround. (This mode was introduced in MySQL 5.0.1.) NO_BACKSLASH_ESCAPES enables an SQL standard compatibility mode, where backslash is not considered a special character. The result will be that queries will fail.

To set this mode for the current connection, enter the following SQL statement:

SET sql_mode='NO_BACKSLASH_ESCAPES';

You can also set the mode globally for all clients:

SET GLOBAL sql_mode='NO_BACKSLASH_ESCAPES';

This SQL mode also can be enabled automatically when the server starts by using the command-line option --sql-mode=NO_BACKSLASH_ESCAPES or by setting sql-mode=NO_BACKSLASH_ESCAPES in the server option file (for example, my.cnf or my.ini, depending on your system). (Bug#8378, CVE-2006-2753)

See also Bug#8303.

Leap year calculation

Here comes a rather obsqure idea. When every year dividable with 100 gets 365 days, what shall be done at this time? In the far future, when even years dividable with 400 only can get 365 days.

Then there is a possibility or reason to make corrections in years dividable with 80. Normal years will have 365 day and those dividable with 400 can get 366 days. Or is this a loose-loose situation.

Reporting Services permissions on SQL Server R2 SSRS

in my case this error resolved by adding permission level to root folder .

i previously only granted permission in 2 place. one in site setting and one in a new folder that has custom permission .

but the user permission to browse the root folder was also required. Note The "Folder setting" in root folder

another time i had similar problem and adding users in the following windows group SQLServerReportServerUser$servername$MSRS10_50.MSSQLSERVER and running IE as Administrator or turning off UAC resolved my problem .

Git cli: get user info from username

While its true that git commits don't have a specific field called "username", a git repo does have users, and the users do have names. ;) If what you want is the github username, then knittl's answer is right. But since your question asked about git cli and not github, here's how you get a git user's email address using the command line:

To see a list of all users in a git repo using the git cli:

git log --format="%an %ae" | sort | uniq

To search for a specific user by name, e.g., "John":

git log --format="%an %ae" | sort | uniq | grep -i john

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

'this' is undefined in JavaScript class methods

JavaScript's OOP is a little funky (or a lot) and it takes some getting used to. This first thing you need to keep in mind is that there are no Classes and thinking in terms of classes can trip you up. And in order to use a method attached to a Constructor (the JavaScript equivalent of a Class definition) you need to instantiate your object. For example:

Ninja = function (name) {
    this.name = name;
};
aNinja = new Ninja('foxy');
aNinja.name; //-> 'foxy'

enemyNinja = new Ninja('boggis');
enemyNinja.name; //=> 'boggis'

Note that Ninja instances have the same properties but aNinja cannot access the properties of enemyNinja. (This part should be really easy/straightforward) Things get a bit different when you start adding stuff to the prototype:

Ninja.prototype.jump = function () {
   return this.name + ' jumped!';
};
Ninja.prototype.jump(); //-> Error.
aNinja.jump(); //-> 'foxy jumped!'
enemyNinja.jump(); //-> 'boggis jumped!'

Calling this directly will throw an error because this only points to the correct object (your "Class") when the Constructor is instantiated (otherwise it points to the global object, window in a browser)

How to create Python egg file

I think you should use python wheels for distribution instead of egg now.

Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

You can try the below command

conda upgrade --all

and try to restart the notebook.

Hope this helps

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

Replace

import { Router, Route, Link, browserHistory } from 'react-router';

With

import { BrowserRouter as Router, Route } from 'react-router-dom';

It will start working. It is because react-router-dom exports BrowserRouter

SOAP-UI - How to pass xml inside parameter

To send CDATA in a request object use the SoapObject.setInnerText("..."); method.

How can I remove duplicate rows?

I had a table where I needed to preserve non-duplicate rows. I'm not sure on the speed or efficiency.

DELETE FROM myTable WHERE RowID IN (
  SELECT MIN(RowID) AS IDNo FROM myTable
  GROUP BY Col1, Col2, Col3
  HAVING COUNT(*) = 2 )

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

Sometimes this error occurs when the .ts file is not saved. So make sure all files in the project are saved otherwise try to restart the editor.

Purpose of Unions in C and C++

@bobobobo code is correct as @Joshua pointed out (sadly I'm not allowed to add comments, so doing it here, IMO bad decision to disallow it in first place):

https://en.cppreference.com/w/cpp/language/data_members#Standard_layout tells that it is fine to do so, at least since C++14

In a standard-layout union with an active member of non-union class type T1, it is permitted to read a non-static data member m of another union member of non-union class type T2 provided m is part of the common initial sequence of T1 and T2 (except that reading a volatile member through non-volatile glvalue is undefined).

since in the current case T1 and T2 donate the same type anyway.

C++ deprecated conversion from string constant to 'char*'

The warning:

deprecated conversion from string constant to 'char*'

is given because you are doing somewhere (not in the code you posted) something like:

void foo(char* str);
foo("hello");

The problem is that you are trying to convert a string literal (with type const char[]) to char*.

You can convert a const char[] to const char* because the array decays to the pointer, but what you are doing is making a mutable a constant.

This conversion is probably allowed for C compatibility and just gives you the warning mentioned.

Datatable vs Dataset

One major difference is that DataSets can hold multiple tables and you can define relationships between those tables.

If you are only returning a single result set though I would think a DataTable would be more optimized. I would think there has to be some overhead (granted small) to offer the functionality a DataSet does and keep track of multiple DataTables.

HTML Button Close Window

Closing a window that was opened by the user through JavaScript is considered to be a security risk, thus not all browsers will allow this (which is why all solutions are hacks/workarounds). Browsers that are steadily maintained remove these types of hacks, and solutions that work one day may be broken the next.

This was addressed here by rvighne in a similar question on the subject.

Change the name of a key in dictionary

this function gets a dict, and another dict specifying how to rename keys; it returns a new dict, with renamed keys:

def rekey(inp_dict, keys_replace):
    return {keys_replace.get(k, k): v for k, v in inp_dict.items()}

test:

def test_rekey():
    assert rekey({'a': 1, "b": 2, "c": 3}, {"b": "beta"}) == {'a': 1, "beta": 2, "c": 3}

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

How to find what code is run by a button or element in Chrome using Developer Tools

This solution needs the jQuery's data method.

  1. Open Chrome's console (although any browser with jQuery loaded will work)
  2. Run $._data($(".example").get(0), "events")
  3. Drill down the output to find the desired event handler.
  4. Right-click on "handler" and select "Show function definition"
  5. The code will be shown in the Sources tab

$._data() is just accessing jQuery's data method. A more readable alternative could be jQuery._data().

Interesting point by this SO answer:

As of jQuery 1.8, the event data is no longer available from the "public API" for data. Read this jQuery blog post. You should now use this instead:

jQuery._data( elem, "events" ); elem should be an HTML Element, not a jQuery object, or selector.

Please note, that this is an internal, 'private' structure, and shouldn't be modified. Use this for debugging purposes only.

In older versions of jQuery, you might have to use the old method which is:

jQuery( elem ).data( "events" );

A version agnostic jQuery would be: (jQuery._data || jQuery.data)(elem, 'events');

Get all unique values in a JavaScript array (remove duplicates)

The task is to get a unique array from an array consisted of arbitrary types (primitive and non primitive).

The approach based on using new Map(...) is not new. Here it is leveraged by JSON.stringify(...), JSON.parse(...) and [].map method. The advantages are universality (applicability for an array of any types), short ES6 notation and probably performance for this case:

_x000D_
_x000D_
const dedupExample = [
    { a: 1 },
    { a: 1 },
    [ 1, 2 ],
    [ 1, 2 ],
    1,
    1,
    '1',
    '1'
]

const getUniqArr = arr => {
    const arrStr = arr.map(item => JSON.stringify(item))
    return [...new Set(arrStr)]
        .map(item => JSON.parse(item))
}

console.info(getUniqArr(dedupExample))
   /* [ {a: 1}, [1, 2], 1, '1' ] */
_x000D_
_x000D_
_x000D_

Check if an array item is set in JS

TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)

function arrayIndexExists(array, index){
    if ( typeof index !== 'number' && index === parseInt(index).toString()) {
        index = parseInt(index);
    } else {
        return false;//to avoid checking typeof again
    }
    return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
}

The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.

Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)

Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.

This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);

var foo = new Array();
foo;
//[]
foo.length;
//0
foo['bar'] = 'bar';
//"bar"
foo;
//[]
foo.length;
//0
foo.bar;
//"bar"

This shows that associative keys are not used to access elements in the array, but for properties of the object.

foo[0] = 0;
//0
foo;
//[0]
foo.length;
//1
foo[2] = undefined
//undefined
typeof foo[2]
//"undefined"
foo.length
//3

This shows that checking typeof doesn't allow you to see if an element has been set.

var foo = new Array();
//undefined
foo;
//[]
foo[0] = 0;
//0
foo['0']
//0
foo[' 0']
//undefined

This shows the exception I mentioned above and why you can't just use parseInt();

If you want to use associative arrays, you are better off using simple objects as other answers have recommended.

Getting the class name from a static method in Java

Verbatim use of caller's class like MyClass.class.getName() actually does the job, but is prone to copy/paste errors if you propagate this code to numerous classes/subclasses where you need this class name.

And Tom Hawtin's recipe is in fact not bad, one just needs to cook it the right way :)

In case you have a base class with a static method that may be called from subclasses, and this static method needs to know the actual caller's class, this may be achieved like the following:

class BaseClass {
  static sharedStaticMethod (String callerClassName, Object... otherArgs) {
    useCallerClassNameAsYouWish (callerClassName);
    // and direct use of 'new Object() { }.getClass().getEnclosingClass().getName()'
    // instead of 'callerClassName' is not going to help here,
    // as it returns "BaseClass"
  }
}

class SubClass1 extends BaseClass {
  static someSubclassStaticMethod () {
    // this call of the shared method is prone to copy/paste errors
    sharedStaticMethod (SubClass1.class.getName(),
                        other_arguments);
    // and this call is safe to copy/paste
    sharedStaticMethod (new Object() { }.getClass().getEnclosingClass().getName(),
                        other_arguments);
  }
}

Command CompileSwift failed with a nonzero exit code in Xcode 10

For me, just cleaning project works using ShiftCommandK & OptionShiftCommandK.

How can I select random files from a directory in bash?

Here's a script that uses GNU sort's random option:

ls |sort -R |tail -$N |while read file; do
    # Something involving $file, or you can leave
    # off the while to just get the filenames
done

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

Select distinct using linq

You should override Equals and GetHashCode meaningfully, in this case to compare the ID:

public class LinqTest
{
    public int id { get; set; }
    public string value { get; set; }

    public override bool Equals(object obj)
    {
        LinqTest obj2 = obj as LinqTest;
        if (obj2 == null) return false;
        return id == obj2.id;
    }

    public override int GetHashCode()
    {
        return id;
    }
}

Now you can use Distinct:

List<LinqTest> uniqueIDs = myList.Distinct().ToList();

How do I use Assert to verify that an exception has been thrown?

This is going to depend on what test framework are you using?

In MbUnit, for example, you can specify the expected exception with an attribute to ensure that you are getting the exception you really expect.

[ExpectedException(typeof(ArgumentException))]

How do I open phone settings when a button is clicked?

Adding to @Luca Davanzo

iOS 11, some permissions settings have moved to the app path:

iOS 11 Support

 static func open(_ preferenceType: PreferenceType) throws {
    var preferencePath: String
    if #available(iOS 11.0, *), preferenceType == .video || preferenceType == .locationServices || preferenceType == .photos {
        preferencePath = UIApplicationOpenSettingsURLString
    } else {
        preferencePath = "\(PreferencesExplorer.preferencePath)=\(preferenceType.rawValue)"
    }

    if let url = URL(string: preferencePath) {
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url)
        }
    } else {
        throw PreferenceExplorerError.notFound(preferencePath)
    }
}

Best way to remove from NSMutableArray while iterating?

I define a category that lets me filter using a block, like this:

@implementation NSMutableArray (Filtering)

- (void)filterUsingTest:(BOOL (^)(id obj, NSUInteger idx))predicate {
    NSMutableIndexSet *indexesFailingTest = [[NSMutableIndexSet alloc] init];

    NSUInteger index = 0;
    for (id object in self) {
        if (!predicate(object, index)) {
            [indexesFailingTest addIndex:index];
        }
        ++index;
    }
    [self removeObjectsAtIndexes:indexesFailingTest];

    [indexesFailingTest release];
}

@end

which can then be used like this:

[myMutableArray filterUsingTest:^BOOL(id obj, NSUInteger idx) {
    return [self doIWantToKeepThisObject:obj atIndex:idx];
}];

difference between css height : 100% vs height : auto

A height of 100% for is, presumably, the height of your browser's inner window, because that is the height of its parent, the page. An auto height will be the minimum height of necessary to contain .

Difference between static, auto, global and local variable in the context of c and c++

static is a heavily overloaded word in C and C++. static variables in the context of a function are variables that hold their values between calls. They exist for the duration of the program.

local variables persist only for the lifetime of a function or whatever their enclosing scope is. For example:

void foo()
{
    int i, j, k;
    //initialize, do stuff
} //i, j, k fall out of scope, no longer exist

Sometimes this scoping is used on purpose with { } blocks:

{ 
   int i, j, k;
   //...
} //i, j, k now out of scope

global variables exist for the duration of the program.

auto is now different in C and C++. auto in C was a (superfluous) way of specifying a local variable. In C++11, auto is now used to automatically derive the type of a value/expression.

How do I disable form fields using CSS?

Since the rules are running in JavaScript, why not disable them using javascript (or in my examples case, jQuery)?

$('#fieldId').attr('disabled', 'disabled'); //Disable
$('#fieldId').removeAttr('disabled'); //Enable

UPDATE

The attr function is no longer the primary approach to this, as was pointed out in the comments below. This is now done with the prop function.

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

Tensorflow installation error: not a supported wheel on this platform

It means that the version of your default python (python -V) and the version of your default pip (pip -V) do not match. You have built tensorflow with your default python and trying to use a different pip version to install it. In mac, delete /usr/local/bin/pip and rename(copy) pipx.y (whatever x.y version that matches your python version) to pip in that folder.

How do I make a C++ console program exit?

simple enough..

exit ( 0 ); }//end of function

Make sure there is a space on both sides of the 0. Without spaces, the program will not stop.

Setting dropdownlist selecteditem programmatically

            ddlemployee.DataSource = ds.Tables[0];
            ddlemployee.DataTextField = "Employee Name";
            ddlemployee.DataValueField = "RecId";
            ddlemployee.DataBind();
            ddlemployee.Items.Insert(0, "All");

How to Calculate Jump Target Address and Branch Target Address?

For small functions like this you could just count by hand how many hops it is to the target, from the instruction under the branch instruction. If it branches backwards make that hop number negative. if that number doesn't require all 16 bits, then for every number to the left of the most significant of your hop number, make them 1's, if the hop number is positive make them all 0's Since most branches are close to they're targets, this saves you a lot of extra arithmetic for most cases.

  • chris

Any way to limit border length?

Hope this helps:

_x000D_
_x000D_
#mainDiv {_x000D_
  height: 100px;_x000D_
  width: 80px;_x000D_
  position: relative;_x000D_
  border-bottom: 2px solid #f51c40;_x000D_
  background: #3beadc;_x000D_
}_x000D_
_x000D_
#borderLeft {_x000D_
  border-left: 2px solid #f51c40;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  bottom: 0;_x000D_
}
_x000D_
<div id="mainDiv">_x000D_
  <div id="borderLeft"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Regex to accept alphanumeric and some special character in Javascript?

use:

/^[ A-Za-z0-9_@./#&+-]*$/

You can also use the character class \w to replace A-Za-z0-9_

Just what is an IntPtr exactly?

It's a value type large enough to store a memory address as used in native or unsafe code, but not directly usable as a memory address in safe managed code.

You can use IntPtr.Size to find out whether you're running in a 32-bit or 64-bit process, as it will be 4 or 8 bytes respectively.

Node.js Error: Cannot find module express

Unless you set Node_PATH, the only other option is to install express in the app directory, like npm install express --save. Express may already be installed but node cannot find it for some reason

Create an Array of Arraylists

This works:

ArrayList<String>[] group = new ArrayList[4];

Matplotlib scatter plot with different text at each data point

Python 3.6+:

coordinates = [('a',1,2), ('b',3,4), ('c',5,6)]
for x in coordinates: plt.annotate(x[0], (x[1], x[2]))

How to read a configuration file in Java

app.config

app.name=Properties Sample Code
app.version=1.09  

Source code:

Properties prop = new Properties();
String fileName = "app.config";
InputStream is = null;
try {
    is = new FileInputStream(fileName);
} catch (FileNotFoundException ex) {
    ...
}
try {
    prop.load(is);
} catch (IOException ex) {
    ...
}
System.out.println(prop.getProperty("app.name"));
System.out.println(prop.getProperty("app.version"));

Output:

Properties Sample Code
1.09  

Attach IntelliJ IDEA debugger to a running Java process

in AndroidStudio or idea

  1. Config the application will be debug, open Edit Configurations

add "VM Options" Config “-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005” remember "address"

enter image description here

  1. Config Remote Debugger if not exits, Click + to add

specify "Port" same as in Step 1 "address" enter image description here

How do I keep a label centered in WinForms?

You could try out the following code snippet:

private Point CenterOfMenuPanel<T>(T control, int height=0) where T:Control {
    Point center = new Point( 
        MenuPanel.Size.Width / 2 - control.Width * 2,
        height != 0 ? height : MenuPanel.Size.Height / 2 - control.Height / 2);

    return center;
}

It's Really Center

enter image description here

How to get the row number from a datatable?

You do know that DataRow is the row of a DataTable correct?

What you currently have already loop through each row. You just have to keep track of how many rows there are in order to get the current row.

int i = 0;
int index = 0;
foreach (DataRow row in dt.Rows) 
{
index = i;
// do stuff
i++;
} 

How do I calculate the date six months from the current date using the datetime Python module?

I found this solution to be good. (This uses the python-dateutil extension)

from datetime import date
from dateutil.relativedelta import relativedelta

six_months = date.today() + relativedelta(months=+6)

The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)

$ date(2010,12,31)+relativedelta(months=+1)
  datetime.date(2011, 1, 31)

$ date(2010,12,31)+relativedelta(months=+2)
  datetime.date(2011, 2, 28)

Easiest way to toggle 2 classes in jQuery

Here is a simplified version: (albeit not elegant, but easy-to-follow)

$("#yourButton").toggle(function() 
{
        $('#target').removeClass("a").addClass("b"); //Adds 'a', removes 'b'

}, function() {
        $('#target').removeClass("b").addClass("a"); //Adds 'b', removes 'a'

});

Alternatively, a similar solution:

$('#yourbutton').click(function()
{
     $('#target').toggleClass('a b'); //Adds 'a', removes 'b' and vice versa
});

how to get data from selected row from datagridview

To get the cell value, you need to read it directly from DataGridView1 using e.RowIndex and e.ColumnIndex properties.

Eg:

Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
   Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value

   If IsDBNull(value) Then 
      TextBox1.Text = "" ' blank if dbnull values
   Else
      TextBox1.Text = CType(value, String)
   End If
End Sub

How to comment out a block of Python code in Vim

CtrlK for comment (Visual Mode):

vnoremap <silent> <C-k> :s#^#\##<cr>:noh<cr>

CtrlU for uncomment (Visual Mode):

vnoremap <silent> <C-u> :s#^\###<cr>:noh<cr>

Symfony2 : How to get form validation errors after binding the request to the form

Translated Form Error Messages (Symfony2.3)

My version of solving the problem:

/src/Acme/MyBundle/Resources/config/services.yml

services:
    form_errors:
        class: Acme\MyBundle\Form\FormErrors

/src/Acme/MyBundle/Form/FormErrors.php

<?php
namespace Acme\MyBundle\Form;

class FormErrors
{
    public function getArray(\Symfony\Component\Form\Form $form)
    {
        return $this->getErrors($form);
    }

    private function getErrors($form)
    {
        $errors = array();

        if ($form instanceof \Symfony\Component\Form\Form) {

            // ??????? ?????? ????????
            foreach ($form->getErrors() as $error) {

                $errors[] = $error->getMessage();
            }

            // ?????????? ??? ???????? ?????????
            foreach ($form->all() as $key => $child) {
                /** @var $child \Symfony\Component\Form\Form */
                if ($err = $this->getErrors($child)) {
                    $errors[$key] = $err;
                }
            }
        }

        return $errors;
    }
}

/src/Acme/MyBundle/Controller/DefaultController.php

$form = $this->createFormBuilder($entity)->getForm();
$form_errors = $this->get('form_errors')->getArray($form);
return new JsonResponse($form_errors);

In Symfony 2.5 you can get all fields errors very easy:

    $errors = array();
    foreach ($form as $fieldName => $formField) {
        foreach ($formField->getErrors(true) as $error) {
            $errors[$fieldName] = $error->getMessage();
        }
    }

ImportError: No module named mysql.connector using Python2

Depending on your python version and how you installed it, it is possible that mysql connector isn't installed, you can install it with pip

To install mysql connector:

pip install mysql-connector-python

How to get the selected radio button’s value?

document.forms.your-form-name.elements.radio-button-name.value

Best way to check if a URL is valid

Given issues with filter_var() needing http://, I use:

$is_url = filter_var($filename, FILTER_VALIDATE_URL) || array_key_exists('scheme', parse_url($filename));

How to give a user only select permission on a database

For the GUI minded people, you can:

  • Right click the Database in Management Studio.
  • Choose Properties
  • Select Permissions
  • If your user does not show up in the list, choose Search and type their name
  • Select the user in the Users or Roles list
  • In the lower window frame, Check the Select permission under the Grant column

Timeout for python requests.get entire response

Just another one solution (got it from http://docs.python-requests.org/en/master/user/advanced/#streaming-uploads)

Before upload you can find out the content size:

TOO_LONG = 10*1024*1024  # 10 Mb
big_url = "http://ipv4.download.thinkbroadband.com/1GB.zip"
r = requests.get(big_url, stream=True)
print (r.headers['content-length'])
# 1073741824  

if int(r.headers['content-length']) < TOO_LONG:
    # upload content:
    content = r.content

But be careful, a sender can set up incorrect value in the 'content-length' response field.

How to generate javadoc comments in Android Studio

I'm not sure I completely understand the question, but a list of keyboard short cuts can be found here - Hope this helps!

How to apply multiple transforms in CSS?

You have to put them on one line like this:

li:nth-child(2) {
    transform: rotate(15deg) translate(-20px,0px);
}

When you have multiple transform directives, only the last one will be applied. It's like any other CSS rule.


Keep in mind multiple transform one line directives are applied from right to left.

This: transform: scale(1,1.5) rotate(90deg);
and: transform: rotate(90deg) scale(1,1.5);

will not produce the same result:

_x000D_
_x000D_
.orderOne, .orderTwo {_x000D_
  font-family: sans-serif;_x000D_
  font-size: 22px;_x000D_
  color: #000;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.orderOne {_x000D_
  transform: scale(1, 1.5) rotate(90deg);_x000D_
}_x000D_
_x000D_
.orderTwo {_x000D_
  transform: rotate(90deg) scale(1, 1.5);_x000D_
}
_x000D_
<div class="orderOne">_x000D_
  A_x000D_
</div>_x000D_
_x000D_
<div class="orderTwo">_x000D_
  A_x000D_
</div>
_x000D_
_x000D_
_x000D_

React.js: Identifying different inputs with one onChange handler

You can also do it like this:

...
constructor() {
    super();
    this.state = { input1: 0, input2: 0 };
    this.handleChange = this.handleChange.bind(this);
}

handleChange(input, value) {
    this.setState({
        [input]: value
    })
}

render() {
    const total = this.state.input1 + this.state.input2;
    return (
        <div>
            {total}<br />
            <input type="text" onChange={e => this.handleChange('input1', e.target.value)} />
            <input type="text" onChange={e => this.handleChange('input2', e.target.value)} />
        </div>
    )
}

How to export private key from a keystore of self-signed certificate

Use Keystore Explorer gui - http://keystore-explorer.sourceforge.net/ - allows you to extract the private key from a .jks in various formats.

C compile error: Id returned 1 exit status

Is a simple MAYUS word. verify the log.

how to create a cookie and add to http response from inside my service layer?

Following @Aravind's answer with more details

@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
    myServiceMethodSettingCookie(request, response);        //Do service call passing the response
    return new ModelAndView("CustomerAddView");
}

// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
    final String cookieName = "my_cool_cookie";
    final String cookieValue = "my cool value here !";  // you could assign it some encoded value
    final Boolean useSecureCookie = false;
    final int expiryTime = 60 * 60 * 24;  // 24h in seconds
    final String cookiePath = "/";

    Cookie cookie = new Cookie(cookieName, cookieValue);

    cookie.setSecure(useSecureCookie);  // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL

    cookie.setMaxAge(expiryTime);  // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

    cookie.setPath(cookiePath);  // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories

    response.addCookie(cookie);
}

Related docs:

http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html

http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html

SVN how to resolve new tree conflicts when file is added on two branches

What if the incoming changes are the ones you want? I'm unable to run svn resolve --accept theirs-full

svn resolve --accept base

Open a Web Page in a Windows Batch FIle

You can use the start command to do much the same thing as ShellExecute. For example

 start "" http://www.stackoverflow.com

This will launch whatever browser is the default browser, so won't necessarily launch Internet Explorer.

how to add script src inside a View when using Layout

If you are using Razor view engine then edit the _Layout.cshtml file. Move the @Scripts.Render("~/bundles/jquery") present in footer to the header section and write the javascript / jquery code as you want:

@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
    $(document).ready(function () {
        var divLength = $('div').length;
        alert(divLength);
    });
</script>

How to compare strings

You could use strcmp():

/* strcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char szKey[] = "apple";
  char szInput[80];
  do {
     printf ("Guess my favourite fruit? ");
     gets (szInput);
  } while (strcmp (szKey,szInput) != 0);
  puts ("Correct answer!");
  return 0;
}

How can I use an array of function pointers?

This should be a short & simple copy & paste piece of code example of the above responses. Hopefully this helps.

#include <iostream>
using namespace std;

#define DBG_PRINT(x) do { std::printf("Line:%-4d" "  %15s = %-10d\n", __LINE__, #x, x); } while(0);

void F0(){ printf("Print F%d\n", 0); }
void F1(){ printf("Print F%d\n", 1); }
void F2(){ printf("Print F%d\n", 2); }
void F3(){ printf("Print F%d\n", 3); }
void F4(){ printf("Print F%d\n", 4); }
void (*fArrVoid[N_FUNC])() = {F0, F1, F2, F3, F4};

int Sum(int a, int b){ return(a+b); }
int Sub(int a, int b){ return(a-b); }
int Mul(int a, int b){ return(a*b); }
int Div(int a, int b){ return(a/b); }
int (*fArrArgs[4])(int a, int b) = {Sum, Sub, Mul, Div};

int main(){
    for(int i = 0; i < 5; i++)  (*fArrVoid[i])();
    printf("\n");

    DBG_PRINT((*fArrArgs[0])(3,2))
    DBG_PRINT((*fArrArgs[1])(3,2))
    DBG_PRINT((*fArrArgs[2])(3,2))
    DBG_PRINT((*fArrArgs[3])(3,2))

    return(0);
}

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

Only Objective-C is allowed by now... but since a few months ago you are allowed to write scripts that will be interpreted in your application.

So you may be able to write a LUA interpreter or a Python interpreter, then write some part of your application in this scripting language. If you want your application accepted on the App Store, these scripts have to be bundled with the application (your application cannot download it from the Internet for example)

see new app store rules

what is the basic difference between stack and queue?

STACK:

  1. Stack is defined as a list of element in which we can insert or delete elements only at the top of the stack.
  2. The behaviour of a stack is like a Last-In First-Out(LIFO) system.
  3. Stack is used to pass parameters between function. On a call to a function, the parameters and local variables are stored on a stack.
  4. High-level programming languages such as Pascal, c, etc. that provide support for recursion use the stack for bookkeeping. Remember in each recursive call, there is a need to save the current value of parameters, local variables, and the return address (the address to which the control has to return after the call).

QUEUE:

  1. Queue is a collection of the same type of element. It is a linear list in which insertions can take place at one end of the list,called rear of the list, and deletions can take place only at other end, called the front of the list
  2. The behaviour of a queue is like a First-In-First-Out (FIFO) system.

How to map calculated properties with JPA and Hibernate

You have three options:

  • either you are calculating the attribute using a @Transient method
  • you can also use @PostLoad entity listener
  • or you can use the Hibernate specific @Formula annotation

While Hibernate allows you to use @Formula, with JPA, you can use the @PostLoad callback to populate a transient property with the result of some calculation:

@Column(name = "price")
private Double price;

@Column(name = "tax_percentage")
private Double taxes;

@Transient
private Double priceWithTaxes;

@PostLoad
private void onLoad() {
    this.priceWithTaxes = price * taxes;
}

So, you can use the Hibernate @Formula like this:

@Formula("""
    round(
       (interestRate::numeric / 100) *
       cents *
       date_part('month', age(now(), createdOn)
    )
    / 12)
    / 100::numeric
    """)
private double interestDollars;

Function to clear the console in R and RStudio

Here's a function:

clear <- function() cat(c("\033[2J","\033[0;0H"))

then you can simply call it, as you call any other R function, clear().

If you prefer to simply type clear (instead of having to type clear(), i.e. with the parentheses), then you can do

clear_fun <- function() cat(c("\033[2J","\033[0;0H"));
makeActiveBinding("clear", clear_fun, baseenv())

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

You have to retrieve it from the HOST header.

var host = req.get('host');

It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.


If this is for supporting cross-origin requests, you would instead use the Origin header.

var origin = req.get('origin');

Note that some cross-origin requests require validation through a "preflight" request:

req.options('/route', function (req, res) {
    var origin = req.get('origin');
    // ...
});

If you're looking for the client's IP, you can retrieve that with:

var userIP = req.socket.remoteAddress;

Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.

Multiple Java versions running concurrently under Windows

Invoking Java with "java -version:1.5", etc. should run with the correct version of Java. (Obviously replace 1.5 with the version you want.)

If Java is properly installed on Windows there are paths to the vm for each version stored in the registry which it uses so you don't need to mess about with environment versions on Windows.

How can I make the computer beep in C#?

In .Net 2.0, you can use Console.Beep().

// Default beep
Console.Beep();

You can also specify the frequency and length of the beep in milliseconds.

// Beep at 5000 Hz for 1 second
Console.Beep(5000, 1000);

For more information refer http://msdn.microsoft.com/en-us/library/8hftfeyw%28v=vs.110%29.aspx

JavaScript - Hide a Div at startup (load)

Using CSS you can just set display:none for the element in a CSS file or in a style attribute

#div { display:none; }
<div id="div"></div>



<div style="display:none"></div>

or having the js just after the div might be fast enough too, but not as clean

How to convert an object to a byte array in C#

I found another way to convert an object to a byte[], here is my solution:

IEnumerable en = (IEnumerable) myObject;
byte[] myBytes = en.OfType<byte>().ToArray();

Regards

regex.test V.S. string.match to know if a string matches a regular expression

This is my benchmark results benchmark results

test 4,267,740 ops/sec ±1.32% (60 runs sampled)

exec 3,649,719 ops/sec ±2.51% (60 runs sampled)

match 3,623,125 ops/sec ±1.85% (62 runs sampled)

indexOf 6,230,325 ops/sec ±0.95% (62 runs sampled)

test method is faster than the match method, but the fastest method is the indexOf

Calculate cosine similarity given 2 sentence strings

I have similar solution but might be useful for pandas

import math
import re
from collections import Counter
import pandas as pd

WORD = re.compile(r"\w+")


def get_cosine(vec1, vec2):
    intersection = set(vec1.keys()) & set(vec2.keys())
    numerator = sum([vec1[x] * vec2[x] for x in intersection])

    sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())])
    sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())])
    denominator = math.sqrt(sum1) * math.sqrt(sum2)

    if not denominator:
        return 0.0
    else:
        return float(numerator) / denominator


def text_to_vector(text):
    words = WORD.findall(text)
    return Counter(words)

df=pd.read_csv('/content/drive/article.csv')
df['vector1']=df['headline'].apply(lambda x: text_to_vector(x)) 
df['vector2']=df['snippet'].apply(lambda x: text_to_vector(x)) 
df['simscore']=df.apply(lambda x: get_cosine(x['vector1'],x['vector2']),axis=1)

How can I delete a file from a Git repository?

Just by going on the file in your github repository you can see the delete icon beside Raw|Blame and don't forget to click on commit changes button. And you can see that your file has been deleted.

Converting Decimal to Binary Java

public static void main(String h[])
{
    Scanner sc=new Scanner(System.in);
    int decimal=sc.nextInt();

    String binary="";

    if(decimal<=0)
    {
        System.out.println("Please Enter more than 0");

    }
    else
    {
        while(decimal>0)
        {

            binary=(decimal%2)+binary;
            decimal=decimal/2;

        }
        System.out.println("binary is:"+binary);

    }

}

How to take screenshot of a div with JavaScript?

var shot1=imagify($('#widget')[0], (base64) => {
  $('img.screenshot').attr('src', base64);
});

Take a look at htmlshot package , then, check deeply the client side section:

npm install htmlshot

How to efficiently remove duplicates from an array without using Set

We can remove duplicates using heap data structure.

  1. Create a min Heap or Max heap [I use min Heap](Takes O(n))
  2. remove the elements from the heap and store it into another list if that element is not in that list. This takes O(nlog(n)) since we remove an element from the heap and it takes log n we do this until the all n elements removed from the heap n * logn

Overall Time complexity is O(nlog(n)).

Python code for my approach

import heapq

l =[1,2,4,6,3,2,6,1]

heapq.heapify(l)
no_duplicate_list =[]

try:
    while True:
        e = heapq.heappop(l)# will return the minimum value from the heap 
        if no_duplicate_list ==[]:
            no_duplicate_list.append(e)
        else:
            if e == no_duplicate_list[-1]:
                continue
            no_duplicate_list.append(e)
except IndexError as i:
    print(no_duplicate_list) #[1, 2, 3, 4, 6]

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

you can always use loadash functions ,like _.nil or _.undefined .They are pretty good to use.

How to change dot size in gnuplot

Use the pointtype and pointsize options, e.g.

plot "./points.dat" using 1:2 pt 7 ps 10  

where pt 7 gives you a filled circle and ps 10 is the size.

See: Plotting data.

Best practice to validate null and empty collection in Java

We'll check a Collection object is empty, null or not. these all methods which are given below, are present in org.apache.commons.collections4.CollectionUtils package.

Check on List or set type of collection Objects.

CollectionUtils.isEmpty(listObject);
CollectionUtils.isNotEmpty(listObject);

Check on Map type of Objects.

MapUtils.isEmpty(mapObject);
MapUtils.isNotEmpty(mapObject);

The return type of all methods is boolean.

How to use sys.exit() in Python

you didn't import sys in your code, nor did you close the () when calling the function... try:

import sys
sys.exit()

Storing SHA1 hash values in MySQL

So the length is between 10 16-bit chars, and 40 hex digits.

In any case decide the format you are going to store, and make the field a fixed size based on that format. That way you won't have any wasted space.

What's the difference between ".equals" and "=="?

Here is a simple interpretation about your problem:

== (equal to) used to evaluate arithmetic expression

where as

equals() method used to compare string

Therefore, it its better to use == for numeric operations & equals() method for String related operations. So, for comparison of objects the equals() method would be right choice.

Importing a GitHub project into Eclipse

Using the command line is an option, and would remove the need for an Eclipse Plugin. First, create a directory to hold the project.

mkdir myGitRepo
cd myGitRepo

Clone the desired repository in the directory you just created.

git clone https://github.com/JonasHelming/gitTutorial.git

Then open Eclipse and select the directory you created (myGitRepo) as the Eclipse Workspace.

Don't worry that the Project Explorer is empty, Eclipse can't recognize the source files yet.

Lastly, create a new Java project with the exact same name as the project you pulled. In this case, it was 'gitTutorial'.

File -> New -> Java Project

At this point, the project's sub directories should contain the files pulled from Github. Take a look at the following post in my blog for a more detailed explanation.

http://brianredd.com/application/pull-java-project-from-github

How can I get the timezone name in JavaScript?

This gets the timezone code (e.g., GMT) in older javascript (I'm using google app script with old engine):

function getTimezoneName() {
  return new Date().toString().get(/\((.+)\)/);
}

I'm just putting this here in case someone needs it.

Cannot create Maven Project in eclipse

It's actually easy and straight forward.

just navigate to your .m2 folder.

.m2/repository/org/apache/maven

inside this maven folder, you will see a folder called Archetypes... delete this folder and the problem is solved.

but if you don't feel like deleting the whole folder, you can navigate into the archetype folder and delete all the archetype you want there. The reason why it keeps failing is because, the archetype you are trying to create is trying to tell you that she already exists in that folder, hence move away...

summarily, deleting the archetype folder in the .m2 folder is the easiest solution.

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

As well as the solution from marc_s, you can also use osql or sqlcmd

This includes headers and it can act like bcp using -Q and -o. However, they don't support format files like bcp.

Total Number of Row Resultset getRow Method

You need to call ResultSet#beforeFirst() to put the cursor back to before the first row before you return the ResultSet object. This way the user will be able to use next() the usual way.

resultSet.last();
rows = resultSet.getRow();
resultSet.beforeFirst();
return resultSet;

However, you have bigger problems with the code given as far. It's leaking DB resources and it is also not a proper OOP approach. Lookup the DAO pattern. Ultimately you'd like to end up as

public List<Operations> list() throws SQLException {
    // Declare Connection, Statement, ResultSet, List<Operation>.

    try {
        // Use Connection, Statement, ResultSet.

        while (resultSet.next()) {
            // Add new Operation to list.
        }
    } finally {
        // Close ResultSet, Statement, Connection.
    }

    return list;
}

This way the caller has just to use List#size() to know about the number of records.

Hexadecimal value 0x00 is a invalid character

Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:

  • Unicode NUL (0x00) is illegal in all versions of XML and validating parsers must reject input that contains it.
  • Despite the above; real-world non-validated XML can contain any kind of garbage ill-formed bytes imaginable.
  • XML 1.1 allows zero-width and nonprinting control characters (except NUL), so you cannot look at an XML 1.1 file in a text editor and tell what characters it contains.

Given what you wrote, I suspect whatever converts the database data to XML is broken; it's propagating non-XML characters.

Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.

If the converter output looks good, the problem is in your XML consumer; it's inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.

Check file encoding (for UTF-16)

Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn't, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.

C# RSA encryption/decryption with transmission

public static string Encryption(string strText)
        {
            var publicKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

            var testData = Encoding.UTF8.GetBytes(strText);

            using (var rsa = new RSACryptoServiceProvider(1024))
            {
                try
                {
                    // client encrypting data with public key issued by server                    
                    rsa.FromXmlString(publicKey.ToString());

                    var encryptedData = rsa.Encrypt(testData, true);

                    var base64Encrypted = Convert.ToBase64String(encryptedData);

                    return base64Encrypted;
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }

        public static string Decryption(string strText)
        {
            var privateKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent><P>/aULPE6jd5IkwtWXmReyMUhmI/nfwfkQSyl7tsg2PKdpcxk4mpPZUdEQhHQLvE84w2DhTyYkPHCtq/mMKE3MHw==</P><Q>3WV46X9Arg2l9cxb67KVlNVXyCqc/w+LWt/tbhLJvV2xCF/0rWKPsBJ9MC6cquaqNPxWWEav8RAVbmmGrJt51Q==</Q><DP>8TuZFgBMpBoQcGUoS2goB4st6aVq1FcG0hVgHhUI0GMAfYFNPmbDV3cY2IBt8Oj/uYJYhyhlaj5YTqmGTYbATQ==</DP><DQ>FIoVbZQgrAUYIHWVEYi/187zFd7eMct/Yi7kGBImJStMATrluDAspGkStCWe4zwDDmdam1XzfKnBUzz3AYxrAQ==</DQ><InverseQ>QPU3Tmt8nznSgYZ+5jUo9E0SfjiTu435ihANiHqqjasaUNvOHKumqzuBZ8NRtkUhS6dsOEb8A2ODvy7KswUxyA==</InverseQ><D>cgoRoAUpSVfHMdYXW9nA3dfX75dIamZnwPtFHq80ttagbIe4ToYYCcyUz5NElhiNQSESgS5uCgNWqWXt5PnPu4XmCXx6utco1UVH8HGLahzbAnSy6Cj3iUIQ7Gj+9gQ7PkC434HTtHazmxVgIR5l56ZjoQ8yGNCPZnsdYEmhJWk=</D></RSAKeyValue>";

            var testData = Encoding.UTF8.GetBytes(strText);

            using (var rsa = new RSACryptoServiceProvider(1024))
            {
                try
                {                    
                    var base64Encrypted = strText;

                    // server decrypting data with private key                    
                    rsa.FromXmlString(privateKey);

                    var resultBytes = Convert.FromBase64String(base64Encrypted);
                    var decryptedBytes = rsa.Decrypt(resultBytes, true);
                    var decryptedData = Encoding.UTF8.GetString(decryptedBytes);
                    return decryptedData.ToString();
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

How do I grep recursively?

For a list of available flags:

grep --help 

Returns all matches for the regexp texthere in the current directory, with the corresponding line number:

grep -rn "texthere" .

Returns all matches for texthere, starting at the root directory, with the corresponding line number and ignoring case:

grep -rni "texthere" /

flags used here:

  • -r recursive
  • -n print line number with output
  • -i ignore case

how to customize `show processlist` in mysql?

The command

show full processlist

can be replaced by:

SELECT * FROM information_schema.processlist

but if you go with the latter version you can add WHERE clause to it:

SELECT * FROM information_schema.processlist WHERE `INFO` LIKE 'SELECT %';

For more information visit this

Get selected value/text from Select on change

_x000D_
_x000D_
function test(){_x000D_
  var sel1 = document.getElementById("select_id");_x000D_
  var strUser1 = sel1.options[sel1.selectedIndex].value;_x000D_
  console.log(strUser1);_x000D_
  alert(strUser1);_x000D_
  // Inorder to get the Test as value i.e "Communication"_x000D_
  var sel2 = document.getElementById("select_id");_x000D_
  var strUser2 = sel2.options[sel2.selectedIndex].text;_x000D_
  console.log(strUser2);_x000D_
  alert(strUser2);_x000D_
}
_x000D_
<select onchange="test()" id="select_id">_x000D_
  <option value="0">-Select-</option>_x000D_
  <option value="1">Communication</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

IE8 support for CSS Media Query

Internet Explorer versions before IE9 do not support media queries.

If you are looking for a way of degrading the design for IE8 users, you may find IE's conditional commenting helpful. Using this, you can specify an IE 8/7/6 specific style sheet which over writes the previous rules.

For example:

<link rel="stylesheet" type="text/css" media="all" href="style.css"/>
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" media="all" href="style-ie.css"/>
<![endif]-->

This won't allow for a responsive design in IE8, but could be a simpler and more accessible solution than using a JS plugin.

Rails: How does the respond_to block work?

There is one more thing you should be aware of - MIME.

If you need to use a MIME type and it isn't supported by default, you can register your own handlers in config/initializers/mime_types.rb:

Mime::Type.register "text/markdown", :markdown

Use JavaScript to place cursor at end of text in text input element

Check this solution!

_x000D_
_x000D_
//fn setCurPosition_x000D_
$.fn.setCurPosition = function(pos) {_x000D_
    this.focus();_x000D_
    this.each(function(index, elem) {_x000D_
        if (elem.setSelectionRange) {_x000D_
            elem.setSelectionRange(pos, pos);_x000D_
        } else if (elem.createTextRange) {_x000D_
            var range = elem.createTextRange();_x000D_
            range.collapse(true);_x000D_
            range.moveEnd('character', pos);_x000D_
            range.moveStart('character', pos);_x000D_
            range.select();_x000D_
        }_x000D_
    });_x000D_
    return this;_x000D_
};_x000D_
_x000D_
// USAGE - Set Cursor ends_x000D_
$('#str1').setCurPosition($('#str1').val().length);_x000D_
_x000D_
// USAGE - Set Cursor at 7 position_x000D_
// $('#str2').setCurPosition(7);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p>Set cursor at any position</p>_x000D_
<p><input type="text" id="str1" value="my string here" /></p>_x000D_
<p><input type="text" id="str2" value="my string here" /></p>
_x000D_
_x000D_
_x000D_

PostgreSQL - max number of parameters in "IN" clause?

explain select * from test where id in (values (1), (2));

QUERY PLAN

 Seq Scan on test  (cost=0.00..1.38 rows=2 width=208)
   Filter: (id = ANY ('{1,2}'::bigint[]))

But if try 2nd query:

explain select * from test where id = any (values (1), (2));

QUERY PLAN

Hash Semi Join  (cost=0.05..1.45 rows=2 width=208)
       Hash Cond: (test.id = "*VALUES*".column1)
       ->  Seq Scan on test  (cost=0.00..1.30 rows=30 width=208)
       ->  Hash  (cost=0.03..0.03 rows=2 width=4)
             ->  Values Scan on "*VALUES*"  (cost=0.00..0.03 rows=2 width=4)

We can see that postgres build temp table and join with it

how to remove the first two columns in a file using shell (awk, sed, whatever)

Its pretty straight forward to do it with only shell

while read A B C; do
echo "$C"
done < oldfile >newfile

Increasing the timeout value in a WCF service

You can choose two ways:

1) By code in the client

public static void Main()
{
    Uri baseAddress = new Uri("http://localhost/MyServer/MyService");

    try
    {
        ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService));

        WSHttpBinding binding = new WSHttpBinding();
        binding.OpenTimeout = new TimeSpan(0, 10, 0);
        binding.CloseTimeout = new TimeSpan(0, 10, 0);
        binding.SendTimeout = new TimeSpan(0, 10, 0);
        binding.ReceiveTimeout = new TimeSpan(0, 10, 0);

        serviceHost.AddServiceEndpoint("ICalculator", binding, baseAddress);
        serviceHost.Open();

        // The service can now be accessed.
        Console.WriteLine("The service is ready.");
        Console.WriteLine("Press <ENTER> to terminate service.");
        Console.WriteLine();
        Console.ReadLine();

    }
    catch (CommunicationException ex)
    {
        // Handle exception ...
    }
}

2)By WebConfig in a web server

<configuration>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding openTimeout="00:10:00" 
                 closeTimeout="00:10:00" 
                 sendTimeout="00:10:00" 
                 receiveTimeout="00:10:00">
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>

For more detail view the official documentations

Configuring Timeout Values on a Binding

Class WSHttpBinding

Mixing C# & VB In The Same Project

In our scenario, its a single VB.NET project (Windows Desktop application) in a single solution. However we wanted to take advantage of C# features like signed/unsigned integers and XML literals and string features in VB.NET. So depending on the features, at runtime we build the code file, compile using respective Rosalyn compiler (VB/CS) into DLL and dynamically load into current assembly. Of course we had to work on delinking, unloading, reloading, naming etc of the dynamic DLLs and the memory management were we largely used dynamic GUID for naming to avoid conflict. It works fine where app user may connect to any DB from our desktop app, write SQL query, convert the connection to LINQ connection and write LINQ queries too which all requires dynamic building of source code, compiling into DLL and attaching to current assembly.

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

Format date to MM/dd/yyyy in JavaScript

All other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. Notice the subtle difference? MM indicates that a leading zero must pad the month if the month is a single digit, thus having it always be a double digit number.

i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31.

I've created a simple function to achieve this. Notice that the same padding is applied not only to the month but also to the day of the month, which in fact makes this MM/DD/yyyy:

_x000D_
_x000D_
function getFormattedDate(date) {_x000D_
  var year = date.getFullYear();_x000D_
_x000D_
  var month = (1 + date.getMonth()).toString();_x000D_
  month = month.length > 1 ? month : '0' + month;_x000D_
_x000D_
  var day = date.getDate().toString();_x000D_
  day = day.length > 1 ? day : '0' + day;_x000D_
  _x000D_
  return month + '/' + day + '/' + year;_x000D_
}
_x000D_
_x000D_
_x000D_


Update for ES2017 using String.padStart(), supported by all major browsers except IE.

_x000D_
_x000D_
function getFormattedDate(date) {_x000D_
    let year = date.getFullYear();_x000D_
    let month = (1 + date.getMonth()).toString().padStart(2, '0');_x000D_
    let day = date.getDate().toString().padStart(2, '0');_x000D_
  _x000D_
    return month + '/' + day + '/' + year;_x000D_
}
_x000D_
_x000D_
_x000D_

How do I add a resources folder to my Java project in Eclipse

Try To Give Full path for reading image.

Example image = ImageIO.read(new File("D:/work1/Jan14Stackoverflow/src/Strawberry.jpg"));

your code is not producing any exception after giving the full path. If you want to just read an image file in java code. Refer the following - http://docs.oracle.com/javase/tutorial/2d/images/examples/LoadImageApp.java

If the object of your class is created at end your code works fine for me and displays the image

// PracticeFrame pframe = new PracticeFrame();//comment this

new PracticeFrame().add(panel);

Is there a format code shortcut for Visual Studio?

Select all text in the document and press Ctrl + E + D.

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

How to search for a string in cell array in MATLAB?

Other answers are probably simpler for this case, but for completeness I thought I would add the use of cellfun with an anonymous function

indices = find(cellfun(@(x) strcmp(x,'KU'), strs))

which has the advantage that you can easily make it case insensitive or use it in cases where you have cell array of structures:

indices = find(cellfun(@(x) strcmpi(x.stringfield,'KU'), strs))

SQL - Query to get server's IP address

Most solutions for getting the IP address via t-sql fall into these two camps:

  1. Run ipconfig.exe via xp_cmdshell and parse the output

  2. Query DMV sys.dm_exec_connections

I'm not a fan of option #1. Enabling xp_cmdshell has security drawbacks, and there's lots of parsing involved anyway. That's cumbersome. Option #2 is elegant. And it's a pure t-sql solution, which I almost always prefer. Here are two sample queries for option #2:

SELECT c.local_net_address
FROM sys.dm_exec_connections AS c
WHERE c.session_id = @@SPID;

SELECT TOP(1) c.local_net_address
FROM sys.dm_exec_connections AS c
WHERE c.local_net_address IS NOT NULL;

Sometimes, neither of the above queries works, though. Query #1 returns NULL if you're connected over Shared Memory (logged in and running SSMS on the SQL host). Query #2 may return nothing if there are no connections using a non-Shared Memory protocol. This scenario is likely when connected to a newly installed SQL instance. The solution? Force a connection over TCP/IP. To do this, create a new connection in SSMS and use the "tcp:" prefix with the server name. Then re-run either query and you'll get the IP address.

SSMS - Connect to Database Engine

"inconsistent use of tabs and spaces in indentation"

There was a duplicate of this question from here but I thought I would offer a view to do with modern editors and the vast array of features they offer. With python code, anything that needs to be intented in a .py file, needs to either all be intented using the tab key, or by spaces. Convention is to use four spaces for an indentation. Most editors have the ability to visually show on the editor whether the code is being indented with spaces or tabs, which helps greatly for debugging. For example, with atom, going to preferences and then editor you can see the following two options:

atom editor to show tabs and spaces

Then if your code is using spaces, you will see small dots where your code is indented:

enter image description here

And if it is indented using tabs, you will see something like this:

enter image description here

Now if you noticed, you can see that when using tabs, there are more errors/warnings on the left, this is because of something called pep8 pep8 documentation, which is basically a uniform style guide for python, so that all developers mostly code to the same standard and appearance, which helps when trying to understand other peoples code, it is in pep8 which favors the use of spaces to indent rather than tabs. And we can see the editor showing that there is a warning relating to pep8 warning code W191,

I hope all the above helps you understand the nature of the problem you are having and how to prevent it in the future.

PHP Configuration: It is not safe to rely on the system's timezone settings

also you can try this

date.timezone = <?php date('Y'); ?>

Select current element in jQuery

When the jQuery click event calls your event handler, it sets "this" to the object that was clicked on. To turn it into a jQuery object, just pass it to the "$" function: $(this). So, to get, for example, the next sibling element, you would do this inside the click handler:

var nextSibling = $(this).next();

Edit: After reading Kevin's comment, I realized I might be mistaken about what you want. If you want to do what he asked, i.e. select the corresponding link in the other div, you could use $(this).index() to get the clicked link's position. Then you would select the link in the other div by its position, for example with the "eq" method.

var $clicked = $(this);
var linkIndex = $clicked.index();
$clicked.parent().next().children().eq(linkIndex);

If you want to be able to go both ways, you will need some way of determining which div you are in so you know if you need "next()" or "prev()" after "parent()"

Automatic prune with Git fetch or pull

Since git 1.8.5 (Q4 2013):

"git fetch" (hence "git pull" as well) learned to check "fetch.prune" and "remote.*.prune" configuration variables and to behave as if the "--prune" command line option was given.

That means that, if you set remote.origin.prune to true:

git config remote.origin.prune true

Any git fetch or git pull will automatically prune.

Note: Git 2.12 (Q1 2017) will fix a bug related to this configuration, which would make git remote rename misbehave.
See "How do I rename a git remote?".


See more at commit 737c5a9:

Without "git fetch --prune", remote-tracking branches for a branch the other side already has removed will stay forever.
Some people want to always run "git fetch --prune".

To accommodate users who want to either prune always or when fetching from a particular remote, add two new configuration variables "fetch.prune" and "remote.<name>.prune":

  • "fetch.prune" allows to enable prune for all fetch operations.
  • "remote.<name>.prune" allows to change the behaviour per remote.

The latter will naturally override the former, and the --[no-]prune option from the command line will override the configured default.

Since --prune is a potentially destructive operation (Git doesn't keep reflogs for deleted references yet), we don't want to prune without users consent, so this configuration will not be on by default.

Meaning of $? (dollar question mark) in shell scripts

This is the exit status of the last executed command.

For example the command true always returns a status of 0 and false always returns a status of 1:

true
echo $? # echoes 0
false
echo $? # echoes 1

From the manual: (acessible by calling man bash in your shell)

$?       Expands to the exit status of the most recently executed foreground pipeline.

By convention an exit status of 0 means success, and non-zero return status means failure. Learn more about exit statuses on wikipedia.

There are other special variables like this, as you can see on this online manual: https://www.gnu.org/s/bash/manual/bash.html#Special-Parameters

Sort Array of object by object field in Angular 6

You can simply use Arrays.sort()

array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));

Working Example :

_x000D_
_x000D_
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
 _x000D_
 console.log(array);
_x000D_
_x000D_
_x000D_

WPF User Control Parent

If you just want to get a specific parent, not only the window, a specific parent in the tree structure, and also not using recursion, or hard break loop counters, you can use the following:

public static T FindParent<T>(DependencyObject current)
    where T : class 
{
    var dependency = current;

    while((dependency = VisualTreeHelper.GetParent(dependency) ?? LogicalTreeHelper.GetParent(dependency)) != null
        && !(dependency is T)) { }

    return dependency as T;
}

Just don't put this call in a constructor (since the Parent property is not yet initialized). Add it in the loading event handler, or in other parts of your application.

How do I test which class an object is in Objective-C?

if you want to get the name of the class simply call:-

id yourObject= [AnotherClass returningObject];

NSString *className=[yourObject className];

NSLog(@"Class name is : %@",className);

Java Generate Random Number Between Two Given Values

You could use e.g. r.nextInt(101)

For a more generic "in between two numbers" use:

Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;

This gives you a random number in between 10 (inclusive) and 100 (exclusive)

How do I create a pause/wait function using Qt?

Small +1 to kshark27's answer to make it dynamic:

#include <QTime>

void delay( int millisecondsToWait )
{
    QTime dieTime = QTime::currentTime().addMSecs( millisecondsToWait );
    while( QTime::currentTime() < dieTime )
    {
        QCoreApplication::processEvents( QEventLoop::AllEvents, 100 );
    }
}

How to get first 5 characters from string

For single-byte strings (e.g. US-ASCII, ISO 8859 family, etc.) use substr and for multi-byte strings (e.g. UTF-8, UTF-16, etc.) use mb_substr:

// singlebyte strings
$result = substr($myStr, 0, 5);
// multibyte strings
$result = mb_substr($myStr, 0, 5);

how to call url of any other website in php

As other's have mentioned, PHP's cURL functions will allow you to perform advanced HTTP requests. You can also use file_get_contents to access REST APIs:

$payload = file_get_contents('http://api.someservice.com/SomeMethod?param=value');

Starting with PHP 5 you can also create a stream context which will allow you to change headers or post data to the service.

How do you stop MySQL on a Mac OS install?

If you installed the MySQL 5 package with MacPorts:

sudo launchctl  unload -w /Library/LaunchDaemons/org.macports.mysql.plist 

Or

sudo launchctl  unload -w /Library/LaunchDaemons/org.macports.mysql5-devel.plist 

if you installed the mysql5-devel package.

integrating barcode scanner into php application?

If you have Bluetooth, Use twedge on windows and getblue app on android, they also have a few videos of it. It's made by TEC-IT. I've got it to work by setting the interface option to bluetooth server in TWedge and setting the output setting in getblue to Bluetooth client and selecting my computer from the Bluetooth devices list. Make sure your computer and phone is paired. Also to get the barcode as input set the action setting in TWedge to Keyboard Wedge. This will allow for you to first click the input text box on said form, then scan said product with your phone and wait a sec for the barcode number to be put into the text box. Using this method requires no php that doesn't already exist in your current form processing, just process the text box as usual and viola your phone scans bar codes, sends them to your pc via Bluetooth wirelessly, your computer inserts the barcode into whatever text field is selected in any application or website. Hope this helps.

Which is faster: Stack allocation or Heap allocation

Stack allocation will almost always be as fast or faster than heap allocation, although it is certainly possible for a heap allocator to simply use a stack based allocation technique.

However, there are larger issues when dealing with the overall performance of stack vs. heap based allocation (or in slightly better terms, local vs. external allocation). Usually, heap (external) allocation is slow because it is dealing with many different kinds of allocations and allocation patterns. Reducing the scope of the allocator you are using (making it local to the algorithm/code) will tend to increase performance without any major changes. Adding better structure to your allocation patterns, for example, forcing a LIFO ordering on allocation and deallocation pairs can also improve your allocator's performance by using the allocator in a simpler and more structured way. Or, you can use or write an allocator tuned for your particular allocation pattern; most programs allocate a few discrete sizes frequently, so a heap that is based on a lookaside buffer of a few fixed (preferably known) sizes will perform extremely well. Windows uses its low-fragmentation-heap for this very reason.

On the other hand, stack-based allocation on a 32-bit memory range is also fraught with peril if you have too many threads. Stacks need a contiguous memory range, so the more threads you have, the more virtual address space you will need for them to run without a stack overflow. This won't be a problem (for now) with 64-bit, but it can certainly wreak havoc in long running programs with lots of threads. Running out of virtual address space due to fragmentation is always a pain to deal with.

when exactly are we supposed to use "public static final String"?

  1. Static means..You can use it without instantiate of the class or using any object.
  2. final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:

      public class StringTest { 
               static final String str = "Hello"; 
      public static void main(String args[]) { 
               // str = "world"; // gives error 
               System.out.println(str); // called without the help of an object                       
               System.out.println(StringTest.str);// called with class name  
                 } 
             } 
    

Thanks

Add and remove multiple classes in jQuery

You can separate multiple classes with the space:

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

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

Replace image src location using CSS

You can use a background image

_x000D_
_x000D_
.application-title img {_x000D_
  width:200px;_x000D_
  height:200px;_x000D_
  box-sizing:border-box;_x000D_
  padding-left: 200px;_x000D_
  /*width of the image*/_x000D_
  background: url(http://lorempixel.com/200/200/city/2) left top no-repeat;_x000D_
}
_x000D_
<div class="application-title">_x000D_
  <img src="http://lorempixel.com/200/200/city/1/">_x000D_
</div><br />_x000D_
Original Image: <br />_x000D_
_x000D_
<img src="http://lorempixel.com/200/200/city/1/">
_x000D_
_x000D_
_x000D_

EOFError: EOF when reading a line

width, height = map(int, input().split())
def rectanglePerimeter(width, height):
   return ((width + height)*2)
print(rectanglePerimeter(width, height))

Running it like this produces:

% echo "1 2" | test.py
6

I suspect IDLE is simply passing a single string to your script. The first input() is slurping the entire string. Notice what happens if you put some print statements in after the calls to input():

width = input()
print(width)
height = input()
print(height)

Running echo "1 2" | test.py produces

1 2
Traceback (most recent call last):
  File "/home/unutbu/pybin/test.py", line 5, in <module>
    height = input()
EOFError: EOF when reading a line

Notice the first print statement prints the entire string '1 2'. The second call to input() raises the EOFError (end-of-file error).

So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input() once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what

width, height = map(int, input().split())

does.

Note, there are other ways to pass input to your program. If you had run test.py in a terminal, then you could have typed 1 and 2 separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1 and 2 programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with

test.py 1 2

Redirecting from cshtml page

This clearly is a bad case of controller logic in a view. It would be better to do this in a controller and return the desired view.

[ChildActionOnly]
public ActionResult Results() 
{
    EnumerableRowCollection<DataRow> custs = ViewBag.Customers;
    bool anyRows = custs.Any();

    if(anyRows == false)
    {
        return View("NoResults");
    }
    else
    {
        return View("OtherView");
    }
}

Modify NoResults.cshtml to a Partial.

And call this as a Partial view in the parent view

@Html.Partial("Results")

You might have to pass the Customer collection as a model to the Result action or in a ViewDataDictionary due to reasons explained here: Can't access ViewBag in a partial view in ASP.NET MVC3

The ChildActionOnly attribute will make sure you cannot go to this page by navigating and that this view must be rendered as a partial, thus by a parent view. cfr: Using ChildActionOnly in MVC

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Use a special character \b, which matches empty string at the beginning or at the end of a word:

print re.sub(r'\b[uU]\b', 'you', text)

spaces are not a reliable solution because there are also plenty of other punctuation marks, so an abstract character \b was invented to indicate a word's beginning or end.

How to change package name in flutter?

Changing name manually doesn't seem to work, throws gradle errors, well in my case it does throw error.

So I usually create a new flutter project.

I use below mentioned command to create a new flutter app

flutter create --org com.yourdomain appname

your project will have the package name as -> com.yourdomain.appname


if you just want to keep your package name as com.appname then make some changes as below

flutter create --org com appname

to add java instead of kotlin for android add -a java

flutter create -a java --org com.yourdomain appname

EDIT


If you have already created a project you can use change_app_package_name package to change the package name.

flutter pub run change_app_package_name:main com.package.appname

How to make FileFilter in java?

Since Java7 you can simply use FileNameExtensionFilter(String description, String... extensions)

A simple JFileChooser analog to the example would be:

JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text files", "txt"));

I know the question was answered long ago, but this is actually the simplest solution.

Win32Exception (0x80004005): The wait operation timed out

I had the same issue, and by Running "exec sp_updatestats" the issue solved and works now

Cocoa Touch: How To Change UIView's Border Color And Thickness?

@IBInspectable is working for me on iOS 9 , Swift 2.0

extension UIView {

@IBInspectable var borderWidth: CGFloat {
get {
        return layer.borderWidth
    }
    set(newValue) {
        layer.borderWidth = newValue
    }
}

@IBInspectable var cornerRadius: CGFloat {
    get {
        return layer.cornerRadius
    }
    set(newValue) {
        layer.cornerRadius = newValue
    }
}

@IBInspectable var borderColor: UIColor? {
    get {
        if let color = layer.borderColor {
            return UIColor(CGColor: color)
        }
        return nil
    }
    set(newValue) {
        layer.borderColor = newValue?.CGColor
    }
}

How do I find a stored procedure containing <text>?

First ensure that you're running the query under your user credentials, and also in the right database context.

USE YOUR_DATABASE_NAME;

Otherwise, sys.procedures won't return anything. Now run the query as below:

select * from sys.procedures p 
join sys.syscomments s on p.object_id = s.id 
where text like '%YOUR_TEXT%';

Another option is to use INFORMATION_SCHEMA.ROUTINES.ROUTINE_DEFINITION, but be aware that it only holds limited number of characters (i.e., first 4000 characters) of the routine.

select * from YOUR_DATABASE_NAME.INFORMATION_SCHEMA.ROUTINES
where ROUTINE_DEFINITION like '%YOUR_TEXT%';

I tested on Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)

Select columns from result set of stored procedure

It might be helpful to know why this is so difficult. A stored procedure may only return text (print 'text'), or may return multiple tables, or may return no tables at all.

So something like SELECT * FROM (exec sp_tables) Table1 will not work

How do I detect if I am in release or debug mode?

I am using this solution in case to find out that my app is running on debug version.

if (BuildConfig.BUILD_TYPE.equals("debug")){
   //Do something
}

Android Relative Layout Align Center

I hope this will work

EDITED

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingRight="15dp" >

    <ImageView
        android:id="@+id/place_category_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:contentDescription="ss"
        android:paddingTop="10dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/place_distance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:text="320" />

    <TextView
        android:id="@+id/place_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="15dp"
        android:layout_toRightOf="@+id/place_category_icon"
        android:text="Place Name"
        android:textColor="#FFFF00"
        android:textSize="14sp"
        android:textStyle="bold" />

</RelativeLayout>

getting the screen density programmatically in android?

Blundell's answer as a static helper method:

private static String getDensityName(Context context) {
    float density = context.getResources().getDisplayMetrics().density;
    if (density >= 4.0) {
        return "xxxhdpi";
    }
    if (density >= 3.0) {
        return "xxhdpi";
    }
    if (density >= 2.0) {
        return "xhdpi";
    }
    if (density >= 1.5) {
        return "hdpi";
    }
    if (density >= 1.0) {
        return "mdpi";
    }
    return "ldpi";
}

Blank HTML SELECT without blank item in dropdown list

You can by setting selectedIndex to -1 using .prop: http://jsfiddle.net/R9auG/.

For older jQuery versions use .attr instead of .prop: http://jsfiddle.net/R9auG/71/.

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

I did git revert a multiple times ,and it worked for me make sure un-check the files while reverting you need changes. Stash your changes and pull again.

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

Nope IF is the way to go, what is the problem you have with using it?

BTW your example won't ever get to the third block of code as it and the second block are exactly alike.

fs.writeFile in a promise, asynchronous-synchronous stuff

If you want to import the promise based version of fs as an ES module you can do:

import { promises as fs } from 'fs'

await fs.writeFile(...)

As soon as node v14 is released (see this PR), you can also use

import { writeFile } from 'fs/promises'

Why am I getting tree conflicts in Subversion?

I found the solution reading the link that Gary gave (and I suggest to follow this way).

Summarizing to resolve the tree conflict committing your working directory with SVN client 1.6.x you can use:

svn resolve --accept working -R .

where . is the directory in conflict.

WARNING: "Committing your working directory" means that your sandbox structure will be the one you are committing, so if, for instance, you deleted some file from your sandbox they will be deleted from the repository too. This applies only to the conflicted directory.

In this way, we are suggesting SVN to resolve the conflict (--resolve), accepting the working copy inside your sandbox (--accept working), recursively (-R), starting from the current directory (.).

In TortoiseSVN, selecting "Resolved" on right click, actually resolves this issue.

Easy way of running the same junit test over and over?

This works much easier for me.

public class RepeatTests extends TestCase {

    public static Test suite() {
        TestSuite suite = new TestSuite(RepeatTests.class.getName());

        for (int i = 0; i < 10; i++) {              
        suite.addTestSuite(YourTest.class);             
        }

        return suite;
    }
}

Python display text with font & color?

There are 2 possibilities. In either case PyGame has to be initialized by pygame.init.

import pygame
pygame.init()

Use either the pygame.font module and create a pygame.font.SysFont or pygame.font.Font object. render() a pygame.Surface with the text and blit the Surface to the screen:

my_font = pygame.font.SysFont(None, 50)
text_surface = myfont.render("Hello world!", True, (255, 0, 0))
screen.blit(text_surface, (10, 10))

Or use the pygame.freetype module. Create a pygame.freetype.SysFont() or pygame.freetype.Font object. render() a pygame.Surface with the text or directly render_to() the text to the screen:

my_ft_font = pygame.freetype.SysFont('Times New Roman', 50)
my_ft_font.render_to(screen, (10, 10), "Hello world!", (255, 0, 0))

See also Text and font


Minimal pygame.font example: repl.it/@Rabbid76/PyGame-Text

import pygame

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

font = pygame.font.SysFont(None, 100)
text = font.render('Hello World', True, (255, 0, 0))

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    window.blit(text, text.get_rect(center = window.get_rect().center))
    pygame.display.flip()

pygame.quit()
exit()

Minimal pygame.freetype example: repl.it/@Rabbid76/PyGame-FreeTypeText

import pygame
import pygame.freetype

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

ft_font = pygame.freetype.SysFont('Times New Roman', 80)

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    text_rect = ft_font.get_rect('Hello World')
    text_rect.center = window.get_rect().center
    ft_font.render_to(window, text_rect.topleft, 'Hello World', (255, 0, 0))
    pygame.display.flip()

pygame.quit()
exit()

Developing C# on Linux

Mono is a runtime environment that can run .NET applications and that works on both Windows and Linux. It includes a C# compiler.

As an IDE, you could use MonoDevelop, and I suppose there's something available for Eclipse, too.

Note that WinForms support on Mono is there, but somewhat lacking. Generally, Mono developers seem to prefer different GUI toolkits such as Gtk#.

Summarizing multiple columns with dplyr?

We can summarize by using summarize_at, summarize_all and summarize_if on dplyr 0.7.4. We can set the multiple columns and functions by using vars and funs argument as below code. The left-hand side of funs formula is assigned to suffix of summarized vars. In the dplyr 0.7.4, summarise_each(and mutate_each) is already deprecated, so we cannot use these functions.

options(scipen = 100, dplyr.width = Inf, dplyr.print_max = Inf)

library(dplyr)
packageVersion("dplyr")
# [1] ‘0.7.4’

set.seed(123)
df <- data_frame(
  a = sample(1:5, 10, replace=T), 
  b = sample(1:5, 10, replace=T), 
  c = sample(1:5, 10, replace=T), 
  d = sample(1:5, 10, replace=T), 
  grp = as.character(sample(1:3, 10, replace=T)) # For convenience, specify character type
)

df %>% group_by(grp) %>% 
  summarise_each(.vars = letters[1:4],
                 .funs = c(mean="mean"))
# `summarise_each()` is deprecated.
# Use `summarise_all()`, `summarise_at()` or `summarise_if()` instead.
# To map `funs` over a selection of variables, use `summarise_at()`
# Error: Strings must match column names. Unknown columns: mean

You should change to the following code. The following codes all have the same result.

# summarise_at
df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = names(.)[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = vars(a,b,c,d),
               .funs = c(mean="mean"))

# summarise_all
df %>% group_by(grp) %>% 
  summarise_all(.funs = c(mean="mean"))

# summarise_if
df %>% group_by(grp) %>% 
  summarise_if(.predicate = function(x) is.numeric(x),
               .funs = funs(mean="mean"))
# A tibble: 3 x 5
# grp a_mean b_mean c_mean d_mean
# <chr>  <dbl>  <dbl>  <dbl>  <dbl>
# 1     1   2.80   3.00    3.6   3.00
# 2     2   4.25   2.75    4.0   3.75
# 3     3   3.00   5.00    1.0   2.00

You can also have multiple functions.

df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:2],
               .funs = c(Mean="mean", Sd="sd"))
# A tibble: 3 x 5
# grp a_Mean b_Mean      a_Sd     b_Sd
# <chr>  <dbl>  <dbl>     <dbl>    <dbl>
# 1     1   2.80   3.00 1.4832397 1.870829
# 2     2   4.25   2.75 0.9574271 1.258306
# 3     3   3.00   5.00        NA       NA

Microsoft Excel mangles Diacritics in .csv files?

I've also noticed that the question was "answered" some time ago but I don't understand the stories that say you can't open a utf8-encoded csv file successfully in Excel without using the text wizard.

My reproducible experience: Type Old MacDonald had a farm,ÈÌÉÍØ into Notepad, hit Enter, then Save As (using the UTF-8 option).

Using Python to show what's actually in there:

>>> open('oldmac.csv', 'rb').read()
'\xef\xbb\xbfOld MacDonald had a farm,\xc3\x88\xc3\x8c\xc3\x89\xc3\x8d\xc3\x98\r\n'
>>> ^Z

Good. Notepad has put a BOM at the front.

Now go into Windows Explorer, double click on the file name, or right click and use "Open with ...", and up pops Excel (2003) with display as expected.

jQuery how to bind onclick event to dynamically added HTML element

All of these methods are deprecated. You should use the on method to solve your problem.

If you want to target a dynamically added element you'll have to use

$(document).on('click', selector-to-your-element , function() {
     //code here ....
});

this replace the deprecated .live() method.

How to find out if an installed Eclipse is 32 or 64 bit version?

Hit Ctrl+Alt+Del to open the Windows Task manager and switch to the processes tab.

32-bit programs should be marked with *32.

Shuffling a list of objects

The shuffling process is "with replacement", so the occurrence of each item may change! At least when when items in your list is also list.

E.g.,

ml = [[0], [1]] * 10

After,

random.shuffle(ml)

The number of [0] may be 9 or 8, but not exactly 10.

How to detect duplicate values in PHP array?

Perhaps something like this (untested code but should give you an idea)?

$new = array();

foreach ($array as $value)
{
    if (isset($new[$value]))
        $new[$value]++;
    else
        $new[$value] = 1;
}

Then you'll get a new array with the values as keys and their value is the number of times they existed in the original array.

Getting user input

Use the following simple way to interactively get user data by a prompt as Arguments on what you want.

Version : Python 3.X

name = input('Enter Your Name: ')
print('Hello ', name)

Adding external library in Android studio

1)just get your lib from here http://search.maven.org/

2)create a libs folder in app directory

3)paste ur library there

4)right click on ur library and click "Add as Library"

5)thats all u need to do!

I hope this will definitely gonna help you!!!!

jQuery - find child with a specific class

Based on your comment, moddify this:

$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV

to:

$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV

More about selectors: https://api.jquery.com/category/selectors/

Open a workbook using FileDialog and manipulate it in Excel VBA

Thankyou Frank.i got the idea. Here is the working code.

Option Explicit
Private Sub CommandButton1_Click()

  Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
  Dim fd As Office.FileDialog

  Set fd = Application.FileDialog(msoFileDialogFilePicker)

  With fd
    .AllowMultiSelect = False
    .Title = "Please select the file."
    .Filters.Clear
    .Filters.Add "Excel 2003", "*.xls?"

    If .Show = True Then
      fileName = Dir(.SelectedItems(1))

    End If
  End With

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks.Open (fileName)

  For Each sheet In Workbooks(fileName).Worksheets
    total = Workbooks("import-sheets.xlsm").Worksheets.Count
    Workbooks(fileName).Worksheets(sheet.Name).Copy _
        after:=Workbooks("import-sheets.xlsm").Worksheets(total)
  Next sheet

  Workbooks(fileName).Close

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

I had a such problem too because i was using IMG tag and UL tag.

Try to apply the 'corners' plugin to elements such as $('#mydiv').corner(), $('#myspan').corner(), $('#myp').corner() but NOT for $('#img').corner()! This rule is related with adding child DIVs into specified element for emulation round-corner effect. As we know IMG element couldn't have any child elements.

I've solved this by wrapping a needed element within the div and changing IMG to DIV with background: CSS property.

Good luck!

What does Visual Studio mean by normalize inconsistent line endings?

There'a an add-in for Visual Studio 2008 that converts the end of line format when a file is saved. You can download it here: http://grebulon.com/software/stripem.php

"The page has expired due to inactivity" - Laravel 5.5

I ran into the same issue in Laravel 5.5. In my case, it happened after changing a route from GET to POST. The issue was because I forgot to pass a CSRF token when I switched to POST.

You can either post a CSRF token in your form by calling:

 {{ csrf_field() }}

Or exclude your route in app/Http/Middleware/VerifyCsrfToken.php

 protected $except = [
        'your/route'
    ];

Primary key or Unique index?

In addition to what the other answers have said, some databases and systems may require a primary to be present. One situation comes to mind; when using enterprise replication with Informix a PK must be present for a table to participate in replication.

VB.NET: Clear DataGridView

For unbound cases note that:

DataGridView.Rows.Clear()

leaves the Columns collection in place.

DataGridView.Columns.Clear()

..will remove all the columns and rows. If you are using the DGV unbound, and on next use the columns change, clearing the Rows may not be adequate. For library code clear all the columns before adding columns.

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

How to validate an Email in PHP?

Use:

var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL));
$validator = new EmailValidator();
$multipleValidations = new MultipleValidationWithAnd([
    new RFCValidation(),
    new DNSCheckValidation()
]);
$validator->isValid("[email protected]", $multipleValidations); //true

Using Thymeleaf when the value is null

The shortest way is using '?' operator. If you have User entity with embedded Address entity in order to access fields of Address entity and print them if address is not null, otherwise here will be an empty column:

<td th:text="${user?.address?.city}"></td>

load json into variable

  • this will get JSON file externally to your javascript variable.
  • now this sample_data will contain the values of JSON file.

var sample_data = '';
$.getJSON("sample.json", function (data) {
    sample_data = data;
    $.each(data, function (key, value) {
        console.log(sample_data);
    });
});

Get Element value with minidom with Python

The above answer is correct, namely:

name[0].firstChild.nodeValue

However for me, like others, my value was further down the tree:

name[0].firstChild.firstChild.nodeValue

To find this I used the following:

def scandown( elements, indent ):
    for el in elements:
        print("   " * indent + "nodeName: " + str(el.nodeName) )
        print("   " * indent + "nodeValue: " + str(el.nodeValue) )
        print("   " * indent + "childNodes: " + str(el.childNodes) )
        scandown(el.childNodes, indent + 1)

scandown( doc.getElementsByTagName('text'), 0 )

Running this for my simple SVG file created with Inkscape this gave me:

nodeName: text
nodeValue: None
childNodes: [<DOM Element: tspan at 0x10392c6d0>]
   nodeName: tspan
   nodeValue: None
   childNodes: [<DOM Text node "'MY STRING'">]
      nodeName: #text
      nodeValue: MY STRING
      childNodes: ()
nodeName: text
nodeValue: None
childNodes: [<DOM Element: tspan at 0x10392c800>]
   nodeName: tspan
   nodeValue: None
   childNodes: [<DOM Text node "'MY WORDS'">]
      nodeName: #text
      nodeValue: MY WORDS
      childNodes: ()

I used xml.dom.minidom, the various fields are explained on this page, MiniDom Python.

Serializing and submitting a form with jQuery and PHP

Have you checked in console if data from form is properly serialized? Is ajax request successful? Also you didn't close placeholder quote in, which can cause some problems:

 <textarea name="comentarii" cols="36" rows="5" placeholder="Message>  

HTML how to clear input using javascript?

<script type="text/javascript">
    function clearThis(target){
        if(target.value=='[email protected]'){
        target.value= "";}
    }
    </script>

Is this really what your looking for?

What does status=canceled for a resource mean in Chrome Developer Tools?

One the reasons could be that the XMLHttpRequest.abort() was called somewhere in the code, in this case, the request will have the cancelled status in the Chrome Developer tools Network tab.

how to call a method in another Activity from Activity

Simple, use static.

In activity you have the method you want to call:

private static String name = "Robert";

...

public static String getData() {
    return name;
}

And in your activity where you make the call:

private static String name;

...

name = SplashActivity.getData();